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
aio-libs/aiomcache
aiomcache/pool.py
MemcachePool.acquire
def acquire(self): """Acquire connection from the pool, or spawn new one if pool maxsize permits. :return: ``tuple`` (reader, writer) """ while self.size() == 0 or self.size() < self._minsize: _conn = yield from self._create_new_conn() if _conn is None: break self._pool.put_nowait(_conn) conn = None while not conn: _conn = yield from self._pool.get() if _conn.reader.at_eof() or _conn.reader.exception(): self._do_close(_conn) conn = yield from self._create_new_conn() else: conn = _conn self._in_use.add(conn) return conn
python
def acquire(self): """Acquire connection from the pool, or spawn new one if pool maxsize permits. :return: ``tuple`` (reader, writer) """ while self.size() == 0 or self.size() < self._minsize: _conn = yield from self._create_new_conn() if _conn is None: break self._pool.put_nowait(_conn) conn = None while not conn: _conn = yield from self._pool.get() if _conn.reader.at_eof() or _conn.reader.exception(): self._do_close(_conn) conn = yield from self._create_new_conn() else: conn = _conn self._in_use.add(conn) return conn
[ "def", "acquire", "(", "self", ")", ":", "while", "self", ".", "size", "(", ")", "==", "0", "or", "self", ".", "size", "(", ")", "<", "self", ".", "_minsize", ":", "_conn", "=", "yield", "from", "self", ".", "_create_new_conn", "(", ")", "if", "_...
Acquire connection from the pool, or spawn new one if pool maxsize permits. :return: ``tuple`` (reader, writer)
[ "Acquire", "connection", "from", "the", "pool", "or", "spawn", "new", "one", "if", "pool", "maxsize", "permits", "." ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/pool.py#L34-L56
train
23,300
aio-libs/aiomcache
aiomcache/pool.py
MemcachePool.release
def release(self, conn): """Releases connection back to the pool. :param conn: ``namedtuple`` (reader, writer) """ self._in_use.remove(conn) if conn.reader.at_eof() or conn.reader.exception(): self._do_close(conn) else: self._pool.put_nowait(conn)
python
def release(self, conn): """Releases connection back to the pool. :param conn: ``namedtuple`` (reader, writer) """ self._in_use.remove(conn) if conn.reader.at_eof() or conn.reader.exception(): self._do_close(conn) else: self._pool.put_nowait(conn)
[ "def", "release", "(", "self", ",", "conn", ")", ":", "self", ".", "_in_use", ".", "remove", "(", "conn", ")", "if", "conn", ".", "reader", ".", "at_eof", "(", ")", "or", "conn", ".", "reader", ".", "exception", "(", ")", ":", "self", ".", "_do_c...
Releases connection back to the pool. :param conn: ``namedtuple`` (reader, writer)
[ "Releases", "connection", "back", "to", "the", "pool", "." ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/pool.py#L58-L67
train
23,301
aio-libs/aiomcache
aiomcache/client.py
Client.get
def get(self, conn, key, default=None): """Gets a single value from the server. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, is the data for this specified key. """ values, _ = yield from self._multi_get(conn, key) return values.get(key, default)
python
def get(self, conn, key, default=None): """Gets a single value from the server. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, is the data for this specified key. """ values, _ = yield from self._multi_get(conn, key) return values.get(key, default)
[ "def", "get", "(", "self", ",", "conn", ",", "key", ",", "default", "=", "None", ")", ":", "values", ",", "_", "=", "yield", "from", "self", ".", "_multi_get", "(", "conn", ",", "key", ")", "return", "values", ".", "get", "(", "key", ",", "defaul...
Gets a single value from the server. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, is the data for this specified key.
[ "Gets", "a", "single", "value", "from", "the", "server", "." ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L142-L150
train
23,302
aio-libs/aiomcache
aiomcache/client.py
Client.gets
def gets(self, conn, key, default=None): """Gets a single value from the server together with the cas token. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, ``bytes tuple with the value and the cas """ values, cas_tokens = yield from self._multi_get( conn, key, with_cas=True) return values.get(key, default), cas_tokens.get(key)
python
def gets(self, conn, key, default=None): """Gets a single value from the server together with the cas token. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, ``bytes tuple with the value and the cas """ values, cas_tokens = yield from self._multi_get( conn, key, with_cas=True) return values.get(key, default), cas_tokens.get(key)
[ "def", "gets", "(", "self", ",", "conn", ",", "key", ",", "default", "=", "None", ")", ":", "values", ",", "cas_tokens", "=", "yield", "from", "self", ".", "_multi_get", "(", "conn", ",", "key", ",", "with_cas", "=", "True", ")", "return", "values", ...
Gets a single value from the server together with the cas token. :param key: ``bytes``, is the key for the item being fetched :param default: default value if there is no value. :return: ``bytes``, ``bytes tuple with the value and the cas
[ "Gets", "a", "single", "value", "from", "the", "server", "together", "with", "the", "cas", "token", "." ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L153-L162
train
23,303
aio-libs/aiomcache
aiomcache/client.py
Client.multi_get
def multi_get(self, conn, *keys): """Takes a list of keys and returns a list of values. :param keys: ``list`` keys for the item being fetched. :return: ``list`` of values for the specified keys. :raises:``ValidationException``, ``ClientException``, and socket errors """ values, _ = yield from self._multi_get(conn, *keys) return tuple(values.get(key) for key in keys)
python
def multi_get(self, conn, *keys): """Takes a list of keys and returns a list of values. :param keys: ``list`` keys for the item being fetched. :return: ``list`` of values for the specified keys. :raises:``ValidationException``, ``ClientException``, and socket errors """ values, _ = yield from self._multi_get(conn, *keys) return tuple(values.get(key) for key in keys)
[ "def", "multi_get", "(", "self", ",", "conn", ",", "*", "keys", ")", ":", "values", ",", "_", "=", "yield", "from", "self", ".", "_multi_get", "(", "conn", ",", "*", "keys", ")", "return", "tuple", "(", "values", ".", "get", "(", "key", ")", "for...
Takes a list of keys and returns a list of values. :param keys: ``list`` keys for the item being fetched. :return: ``list`` of values for the specified keys. :raises:``ValidationException``, ``ClientException``, and socket errors
[ "Takes", "a", "list", "of", "keys", "and", "returns", "a", "list", "of", "values", "." ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L165-L174
train
23,304
aio-libs/aiomcache
aiomcache/client.py
Client.stats
def stats(self, conn, args=None): """Runs a stats command on the server.""" # req - stats [additional args]\r\n # resp - STAT <name> <value>\r\n (one per result) # END\r\n if args is None: args = b'' conn.writer.write(b''.join((b'stats ', args, b'\r\n'))) result = {} resp = yield from conn.reader.readline() while resp != b'END\r\n': terms = resp.split() if len(terms) == 2 and terms[0] == b'STAT': result[terms[1]] = None elif len(terms) == 3 and terms[0] == b'STAT': result[terms[1]] = terms[2] elif len(terms) >= 3 and terms[0] == b'STAT': result[terms[1]] = b' '.join(terms[2:]) else: raise ClientException('stats failed', resp) resp = yield from conn.reader.readline() return result
python
def stats(self, conn, args=None): """Runs a stats command on the server.""" # req - stats [additional args]\r\n # resp - STAT <name> <value>\r\n (one per result) # END\r\n if args is None: args = b'' conn.writer.write(b''.join((b'stats ', args, b'\r\n'))) result = {} resp = yield from conn.reader.readline() while resp != b'END\r\n': terms = resp.split() if len(terms) == 2 and terms[0] == b'STAT': result[terms[1]] = None elif len(terms) == 3 and terms[0] == b'STAT': result[terms[1]] = terms[2] elif len(terms) >= 3 and terms[0] == b'STAT': result[terms[1]] = b' '.join(terms[2:]) else: raise ClientException('stats failed', resp) resp = yield from conn.reader.readline() return result
[ "def", "stats", "(", "self", ",", "conn", ",", "args", "=", "None", ")", ":", "# req - stats [additional args]\\r\\n", "# resp - STAT <name> <value>\\r\\n (one per result)", "# END\\r\\n", "if", "args", "is", "None", ":", "args", "=", "b''", "conn", ".", "wr...
Runs a stats command on the server.
[ "Runs", "a", "stats", "command", "on", "the", "server", "." ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L177-L204
train
23,305
aio-libs/aiomcache
aiomcache/client.py
Client.append
def append(self, conn, key, value, exptime=0): """Add data to an existing key after existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, True in case of success. """ flags = 0 # TODO: fix when exception removed return (yield from self._storage_command( conn, b'append', key, value, flags, exptime))
python
def append(self, conn, key, value, exptime=0): """Add data to an existing key after existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, True in case of success. """ flags = 0 # TODO: fix when exception removed return (yield from self._storage_command( conn, b'append', key, value, flags, exptime))
[ "def", "append", "(", "self", ",", "conn", ",", "key", ",", "value", ",", "exptime", "=", "0", ")", ":", "flags", "=", "0", "# TODO: fix when exception removed", "return", "(", "yield", "from", "self", ".", "_storage_command", "(", "conn", ",", "b'append'"...
Add data to an existing key after existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, True in case of success.
[ "Add", "data", "to", "an", "existing", "key", "after", "existing", "data" ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L305-L316
train
23,306
aio-libs/aiomcache
aiomcache/client.py
Client.prepend
def prepend(self, conn, key, value, exptime=0): """Add data to an existing key before existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, True in case of success. """ flags = 0 # TODO: fix when exception removed return (yield from self._storage_command( conn, b'prepend', key, value, flags, exptime))
python
def prepend(self, conn, key, value, exptime=0): """Add data to an existing key before existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, True in case of success. """ flags = 0 # TODO: fix when exception removed return (yield from self._storage_command( conn, b'prepend', key, value, flags, exptime))
[ "def", "prepend", "(", "self", ",", "conn", ",", "key", ",", "value", ",", "exptime", "=", "0", ")", ":", "flags", "=", "0", "# TODO: fix when exception removed", "return", "(", "yield", "from", "self", ".", "_storage_command", "(", "conn", ",", "b'prepend...
Add data to an existing key before existing data :param key: ``bytes``, is the key of the item. :param value: ``bytes``, data to store. :param exptime: ``int`` is expiration time. If it's 0, the item never expires. :return: ``bool``, True in case of success.
[ "Add", "data", "to", "an", "existing", "key", "before", "existing", "data" ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L319-L330
train
23,307
aio-libs/aiomcache
aiomcache/client.py
Client.incr
def incr(self, conn, key, increment=1): """Command is used to change data for some item in-place, incrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param increment: ``int``, is the amount by which the client wants to increase the item. :return: ``int``, new value of the item's data, after the increment or ``None`` to indicate the item with this value was not found """ assert self._validate_key(key) resp = yield from self._incr_decr( conn, b'incr', key, increment) return resp
python
def incr(self, conn, key, increment=1): """Command is used to change data for some item in-place, incrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param increment: ``int``, is the amount by which the client wants to increase the item. :return: ``int``, new value of the item's data, after the increment or ``None`` to indicate the item with this value was not found """ assert self._validate_key(key) resp = yield from self._incr_decr( conn, b'incr', key, increment) return resp
[ "def", "incr", "(", "self", ",", "conn", ",", "key", ",", "increment", "=", "1", ")", ":", "assert", "self", ".", "_validate_key", "(", "key", ")", "resp", "=", "yield", "from", "self", ".", "_incr_decr", "(", "conn", ",", "b'incr'", ",", "key", ",...
Command is used to change data for some item in-place, incrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param increment: ``int``, is the amount by which the client wants to increase the item. :return: ``int``, new value of the item's data, after the increment or ``None`` to indicate the item with this value was not found
[ "Command", "is", "used", "to", "change", "data", "for", "some", "item", "in", "-", "place", "incrementing", "it", ".", "The", "data", "for", "the", "item", "is", "treated", "as", "decimal", "representation", "of", "a", "64", "-", "bit", "unsigned", "inte...
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L343-L359
train
23,308
aio-libs/aiomcache
aiomcache/client.py
Client.decr
def decr(self, conn, key, decrement=1): """Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param decrement: ``int``, is the amount by which the client wants to decrease the item. :return: ``int`` new value of the item's data, after the increment or ``None`` to indicate the item with this value was not found """ assert self._validate_key(key) resp = yield from self._incr_decr( conn, b'decr', key, decrement) return resp
python
def decr(self, conn, key, decrement=1): """Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param decrement: ``int``, is the amount by which the client wants to decrease the item. :return: ``int`` new value of the item's data, after the increment or ``None`` to indicate the item with this value was not found """ assert self._validate_key(key) resp = yield from self._incr_decr( conn, b'decr', key, decrement) return resp
[ "def", "decr", "(", "self", ",", "conn", ",", "key", ",", "decrement", "=", "1", ")", ":", "assert", "self", ".", "_validate_key", "(", "key", ")", "resp", "=", "yield", "from", "self", ".", "_incr_decr", "(", "conn", ",", "b'decr'", ",", "key", ",...
Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param decrement: ``int``, is the amount by which the client wants to decrease the item. :return: ``int`` new value of the item's data, after the increment or ``None`` to indicate the item with this value was not found
[ "Command", "is", "used", "to", "change", "data", "for", "some", "item", "in", "-", "place", "decrementing", "it", ".", "The", "data", "for", "the", "item", "is", "treated", "as", "decimal", "representation", "of", "a", "64", "-", "bit", "unsigned", "inte...
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L362-L378
train
23,309
aio-libs/aiomcache
aiomcache/client.py
Client.touch
def touch(self, conn, key, exptime): """The command is used to update the expiration time of an existing item without fetching it. :param key: ``bytes``, is the key to update expiration time :param exptime: ``int``, is expiration time. This replaces the existing expiration time. :return: ``bool``, True in case of success. """ assert self._validate_key(key) _cmd = b' '.join([b'touch', key, str(exptime).encode('utf-8')]) cmd = _cmd + b'\r\n' resp = yield from self._execute_simple_command(conn, cmd) if resp not in (const.TOUCHED, const.NOT_FOUND): raise ClientException('Memcached touch failed', resp) return resp == const.TOUCHED
python
def touch(self, conn, key, exptime): """The command is used to update the expiration time of an existing item without fetching it. :param key: ``bytes``, is the key to update expiration time :param exptime: ``int``, is expiration time. This replaces the existing expiration time. :return: ``bool``, True in case of success. """ assert self._validate_key(key) _cmd = b' '.join([b'touch', key, str(exptime).encode('utf-8')]) cmd = _cmd + b'\r\n' resp = yield from self._execute_simple_command(conn, cmd) if resp not in (const.TOUCHED, const.NOT_FOUND): raise ClientException('Memcached touch failed', resp) return resp == const.TOUCHED
[ "def", "touch", "(", "self", ",", "conn", ",", "key", ",", "exptime", ")", ":", "assert", "self", ".", "_validate_key", "(", "key", ")", "_cmd", "=", "b' '", ".", "join", "(", "[", "b'touch'", ",", "key", ",", "str", "(", "exptime", ")", ".", "en...
The command is used to update the expiration time of an existing item without fetching it. :param key: ``bytes``, is the key to update expiration time :param exptime: ``int``, is expiration time. This replaces the existing expiration time. :return: ``bool``, True in case of success.
[ "The", "command", "is", "used", "to", "update", "the", "expiration", "time", "of", "an", "existing", "item", "without", "fetching", "it", "." ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L381-L397
train
23,310
aio-libs/aiomcache
aiomcache/client.py
Client.version
def version(self, conn): """Current version of the server. :return: ``bytes``, memcached version for current the server. """ command = b'version\r\n' response = yield from self._execute_simple_command( conn, command) if not response.startswith(const.VERSION): raise ClientException('Memcached version failed', response) version, number = response.split() return number
python
def version(self, conn): """Current version of the server. :return: ``bytes``, memcached version for current the server. """ command = b'version\r\n' response = yield from self._execute_simple_command( conn, command) if not response.startswith(const.VERSION): raise ClientException('Memcached version failed', response) version, number = response.split() return number
[ "def", "version", "(", "self", ",", "conn", ")", ":", "command", "=", "b'version\\r\\n'", "response", "=", "yield", "from", "self", ".", "_execute_simple_command", "(", "conn", ",", "command", ")", "if", "not", "response", ".", "startswith", "(", "const", ...
Current version of the server. :return: ``bytes``, memcached version for current the server.
[ "Current", "version", "of", "the", "server", "." ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L400-L412
train
23,311
aio-libs/aiomcache
aiomcache/client.py
Client.flush_all
def flush_all(self, conn): """Its effect is to invalidate all existing items immediately""" command = b'flush_all\r\n' response = yield from self._execute_simple_command( conn, command) if const.OK != response: raise ClientException('Memcached flush_all failed', response)
python
def flush_all(self, conn): """Its effect is to invalidate all existing items immediately""" command = b'flush_all\r\n' response = yield from self._execute_simple_command( conn, command) if const.OK != response: raise ClientException('Memcached flush_all failed', response)
[ "def", "flush_all", "(", "self", ",", "conn", ")", ":", "command", "=", "b'flush_all\\r\\n'", "response", "=", "yield", "from", "self", ".", "_execute_simple_command", "(", "conn", ",", "command", ")", "if", "const", ".", "OK", "!=", "response", ":", "rais...
Its effect is to invalidate all existing items immediately
[ "Its", "effect", "is", "to", "invalidate", "all", "existing", "items", "immediately" ]
75d44b201aea91bc2856b10940922d5ebfbfcd7b
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L415-L422
train
23,312
python273/telegraph
telegraph/api.py
Telegraph.create_account
def create_account(self, short_name, author_name=None, author_url=None, replace_token=True): """ Create a new Telegraph account :param short_name: Account name, helps users with several accounts remember which they are currently using. Displayed to the user above the "Edit/Publish" button on Telegra.ph, other users don't see this name :param author_name: Default author name used when creating new articles :param author_url: Default profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channels :param replace_token: Replaces current token to a new user's token """ response = self._telegraph.method('createAccount', values={ 'short_name': short_name, 'author_name': author_name, 'author_url': author_url }) if replace_token: self._telegraph.access_token = response.get('access_token') return response
python
def create_account(self, short_name, author_name=None, author_url=None, replace_token=True): """ Create a new Telegraph account :param short_name: Account name, helps users with several accounts remember which they are currently using. Displayed to the user above the "Edit/Publish" button on Telegra.ph, other users don't see this name :param author_name: Default author name used when creating new articles :param author_url: Default profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channels :param replace_token: Replaces current token to a new user's token """ response = self._telegraph.method('createAccount', values={ 'short_name': short_name, 'author_name': author_name, 'author_url': author_url }) if replace_token: self._telegraph.access_token = response.get('access_token') return response
[ "def", "create_account", "(", "self", ",", "short_name", ",", "author_name", "=", "None", ",", "author_url", "=", "None", ",", "replace_token", "=", "True", ")", ":", "response", "=", "self", ".", "_telegraph", ".", "method", "(", "'createAccount'", ",", "...
Create a new Telegraph account :param short_name: Account name, helps users with several accounts remember which they are currently using. Displayed to the user above the "Edit/Publish" button on Telegra.ph, other users don't see this name :param author_name: Default author name used when creating new articles :param author_url: Default profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channels :param replace_token: Replaces current token to a new user's token
[ "Create", "a", "new", "Telegraph", "account" ]
6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc
https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L57-L84
train
23,313
python273/telegraph
telegraph/api.py
Telegraph.edit_account_info
def edit_account_info(self, short_name=None, author_name=None, author_url=None): """ Update information about a Telegraph account. Pass only the parameters that you want to edit :param short_name: Account name, helps users with several accounts remember which they are currently using. Displayed to the user above the "Edit/Publish" button on Telegra.ph, other users don't see this name :param author_name: Default author name used when creating new articles :param author_url: Default profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channels """ return self._telegraph.method('editAccountInfo', values={ 'short_name': short_name, 'author_name': author_name, 'author_url': author_url })
python
def edit_account_info(self, short_name=None, author_name=None, author_url=None): """ Update information about a Telegraph account. Pass only the parameters that you want to edit :param short_name: Account name, helps users with several accounts remember which they are currently using. Displayed to the user above the "Edit/Publish" button on Telegra.ph, other users don't see this name :param author_name: Default author name used when creating new articles :param author_url: Default profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channels """ return self._telegraph.method('editAccountInfo', values={ 'short_name': short_name, 'author_name': author_name, 'author_url': author_url })
[ "def", "edit_account_info", "(", "self", ",", "short_name", "=", "None", ",", "author_name", "=", "None", ",", "author_url", "=", "None", ")", ":", "return", "self", ".", "_telegraph", ".", "method", "(", "'editAccountInfo'", ",", "values", "=", "{", "'sho...
Update information about a Telegraph account. Pass only the parameters that you want to edit :param short_name: Account name, helps users with several accounts remember which they are currently using. Displayed to the user above the "Edit/Publish" button on Telegra.ph, other users don't see this name :param author_name: Default author name used when creating new articles :param author_url: Default profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channels
[ "Update", "information", "about", "a", "Telegraph", "account", ".", "Pass", "only", "the", "parameters", "that", "you", "want", "to", "edit" ]
6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc
https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L86-L107
train
23,314
python273/telegraph
telegraph/api.py
Telegraph.revoke_access_token
def revoke_access_token(self): """ Revoke access_token and generate a new one, for example, if the user would like to reset all connected sessions, or you have reasons to believe the token was compromised. On success, returns dict with new access_token and auth_url fields """ response = self._telegraph.method('revokeAccessToken') self._telegraph.access_token = response.get('access_token') return response
python
def revoke_access_token(self): """ Revoke access_token and generate a new one, for example, if the user would like to reset all connected sessions, or you have reasons to believe the token was compromised. On success, returns dict with new access_token and auth_url fields """ response = self._telegraph.method('revokeAccessToken') self._telegraph.access_token = response.get('access_token') return response
[ "def", "revoke_access_token", "(", "self", ")", ":", "response", "=", "self", ".", "_telegraph", ".", "method", "(", "'revokeAccessToken'", ")", "self", ".", "_telegraph", ".", "access_token", "=", "response", ".", "get", "(", "'access_token'", ")", "return", ...
Revoke access_token and generate a new one, for example, if the user would like to reset all connected sessions, or you have reasons to believe the token was compromised. On success, returns dict with new access_token and auth_url fields
[ "Revoke", "access_token", "and", "generate", "a", "new", "one", "for", "example", "if", "the", "user", "would", "like", "to", "reset", "all", "connected", "sessions", "or", "you", "have", "reasons", "to", "believe", "the", "token", "was", "compromised", ".",...
6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc
https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L109-L120
train
23,315
python273/telegraph
telegraph/api.py
Telegraph.get_page
def get_page(self, path, return_content=True, return_html=True): """ Get a Telegraph page :param path: Path to the Telegraph page (in the format Title-12-31, i.e. everything that comes after https://telegra.ph/) :param return_content: If true, content field will be returned :param return_html: If true, returns HTML instead of Nodes list """ response = self._telegraph.method('getPage', path=path, values={ 'return_content': return_content }) if return_content and return_html: response['content'] = nodes_to_html(response['content']) return response
python
def get_page(self, path, return_content=True, return_html=True): """ Get a Telegraph page :param path: Path to the Telegraph page (in the format Title-12-31, i.e. everything that comes after https://telegra.ph/) :param return_content: If true, content field will be returned :param return_html: If true, returns HTML instead of Nodes list """ response = self._telegraph.method('getPage', path=path, values={ 'return_content': return_content }) if return_content and return_html: response['content'] = nodes_to_html(response['content']) return response
[ "def", "get_page", "(", "self", ",", "path", ",", "return_content", "=", "True", ",", "return_html", "=", "True", ")", ":", "response", "=", "self", ".", "_telegraph", ".", "method", "(", "'getPage'", ",", "path", "=", "path", ",", "values", "=", "{", ...
Get a Telegraph page :param path: Path to the Telegraph page (in the format Title-12-31, i.e. everything that comes after https://telegra.ph/) :param return_content: If true, content field will be returned :param return_html: If true, returns HTML instead of Nodes list
[ "Get", "a", "Telegraph", "page" ]
6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc
https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L122-L139
train
23,316
python273/telegraph
telegraph/api.py
Telegraph.create_page
def create_page(self, title, content=None, html_content=None, author_name=None, author_url=None, return_content=False): """ Create a new Telegraph page :param title: Page title :param content: Content in nodes list format (see doc) :param html_content: Content in HTML format :param author_name: Author name, displayed below the article's title :param author_url: Profile link, opened when users click on the author's name below the title :param return_content: If true, a content field will be returned """ if content is None: content = html_to_nodes(html_content) content_json = json.dumps(content) return self._telegraph.method('createPage', values={ 'title': title, 'author_name': author_name, 'author_url': author_url, 'content': content_json, 'return_content': return_content })
python
def create_page(self, title, content=None, html_content=None, author_name=None, author_url=None, return_content=False): """ Create a new Telegraph page :param title: Page title :param content: Content in nodes list format (see doc) :param html_content: Content in HTML format :param author_name: Author name, displayed below the article's title :param author_url: Profile link, opened when users click on the author's name below the title :param return_content: If true, a content field will be returned """ if content is None: content = html_to_nodes(html_content) content_json = json.dumps(content) return self._telegraph.method('createPage', values={ 'title': title, 'author_name': author_name, 'author_url': author_url, 'content': content_json, 'return_content': return_content })
[ "def", "create_page", "(", "self", ",", "title", ",", "content", "=", "None", ",", "html_content", "=", "None", ",", "author_name", "=", "None", ",", "author_url", "=", "None", ",", "return_content", "=", "False", ")", ":", "if", "content", "is", "None",...
Create a new Telegraph page :param title: Page title :param content: Content in nodes list format (see doc) :param html_content: Content in HTML format :param author_name: Author name, displayed below the article's title :param author_url: Profile link, opened when users click on the author's name below the title :param return_content: If true, a content field will be returned
[ "Create", "a", "new", "Telegraph", "page" ]
6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc
https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L141-L170
train
23,317
python273/telegraph
telegraph/api.py
Telegraph.get_account_info
def get_account_info(self, fields=None): """ Get information about a Telegraph account :param fields: List of account fields to return. Available fields: short_name, author_name, author_url, auth_url, page_count Default: [“short_name”,“author_name”,“author_url”] """ return self._telegraph.method('getAccountInfo', { 'fields': json.dumps(fields) if fields else None })
python
def get_account_info(self, fields=None): """ Get information about a Telegraph account :param fields: List of account fields to return. Available fields: short_name, author_name, author_url, auth_url, page_count Default: [“short_name”,“author_name”,“author_url”] """ return self._telegraph.method('getAccountInfo', { 'fields': json.dumps(fields) if fields else None })
[ "def", "get_account_info", "(", "self", ",", "fields", "=", "None", ")", ":", "return", "self", ".", "_telegraph", ".", "method", "(", "'getAccountInfo'", ",", "{", "'fields'", ":", "json", ".", "dumps", "(", "fields", ")", "if", "fields", "else", "None"...
Get information about a Telegraph account :param fields: List of account fields to return. Available fields: short_name, author_name, author_url, auth_url, page_count Default: [“short_name”,“author_name”,“author_url”]
[ "Get", "information", "about", "a", "Telegraph", "account" ]
6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc
https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L205-L216
train
23,318
python273/telegraph
telegraph/api.py
Telegraph.get_views
def get_views(self, path, year=None, month=None, day=None, hour=None): """ Get the number of views for a Telegraph article :param path: Path to the Telegraph page :param year: Required if month is passed. If passed, the number of page views for the requested year will be returned :param month: Required if day is passed. If passed, the number of page views for the requested month will be returned :param day: Required if hour is passed. If passed, the number of page views for the requested day will be returned :param hour: If passed, the number of page views for the requested hour will be returned """ return self._telegraph.method('getViews', path=path, values={ 'year': year, 'month': month, 'day': day, 'hour': hour })
python
def get_views(self, path, year=None, month=None, day=None, hour=None): """ Get the number of views for a Telegraph article :param path: Path to the Telegraph page :param year: Required if month is passed. If passed, the number of page views for the requested year will be returned :param month: Required if day is passed. If passed, the number of page views for the requested month will be returned :param day: Required if hour is passed. If passed, the number of page views for the requested day will be returned :param hour: If passed, the number of page views for the requested hour will be returned """ return self._telegraph.method('getViews', path=path, values={ 'year': year, 'month': month, 'day': day, 'hour': hour })
[ "def", "get_views", "(", "self", ",", "path", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hour", "=", "None", ")", ":", "return", "self", ".", "_telegraph", ".", "method", "(", "'getViews'", ",", "path", "=",...
Get the number of views for a Telegraph article :param path: Path to the Telegraph page :param year: Required if month is passed. If passed, the number of page views for the requested year will be returned :param month: Required if day is passed. If passed, the number of page views for the requested month will be returned :param day: Required if hour is passed. If passed, the number of page views for the requested day will be returned :param hour: If passed, the number of page views for the requested hour will be returned
[ "Get", "the", "number", "of", "views", "for", "a", "Telegraph", "article" ]
6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc
https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L234-L257
train
23,319
python273/telegraph
telegraph/upload.py
upload_file
def upload_file(f): """ Upload file to Telegra.ph's servers. Returns a list of links. Allowed only .jpg, .jpeg, .png, .gif and .mp4 files. :param f: filename or file-like object. :type f: file, str or list """ with FilesOpener(f) as files: response = requests.post( 'https://telegra.ph/upload', files=files ).json() if isinstance(response, list): error = response[0].get('error') else: error = response.get('error') if error: raise TelegraphException(error) return [i['src'] for i in response]
python
def upload_file(f): """ Upload file to Telegra.ph's servers. Returns a list of links. Allowed only .jpg, .jpeg, .png, .gif and .mp4 files. :param f: filename or file-like object. :type f: file, str or list """ with FilesOpener(f) as files: response = requests.post( 'https://telegra.ph/upload', files=files ).json() if isinstance(response, list): error = response[0].get('error') else: error = response.get('error') if error: raise TelegraphException(error) return [i['src'] for i in response]
[ "def", "upload_file", "(", "f", ")", ":", "with", "FilesOpener", "(", "f", ")", "as", "files", ":", "response", "=", "requests", ".", "post", "(", "'https://telegra.ph/upload'", ",", "files", "=", "files", ")", ".", "json", "(", ")", "if", "isinstance", ...
Upload file to Telegra.ph's servers. Returns a list of links. Allowed only .jpg, .jpeg, .png, .gif and .mp4 files. :param f: filename or file-like object. :type f: file, str or list
[ "Upload", "file", "to", "Telegra", ".", "ph", "s", "servers", ".", "Returns", "a", "list", "of", "links", ".", "Allowed", "only", ".", "jpg", ".", "jpeg", ".", "png", ".", "gif", "and", ".", "mp4", "files", "." ]
6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc
https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/upload.py#L8-L29
train
23,320
wq/django-natural-keys
natural_keys/models.py
NaturalKeyModelManager.get_by_natural_key
def get_by_natural_key(self, *args): """ Return the object corresponding to the provided natural key. (This is a generic implementation of the standard Django function) """ kwargs = self.natural_key_kwargs(*args) # Since kwargs already has __ lookups in it, we could just do this: # return self.get(**kwargs) # But, we should call each related model's get_by_natural_key in case # it's been overridden for name, rel_to in self.model.get_natural_key_info(): if not rel_to: continue # Extract natural key for related object nested_key = extract_nested_key(kwargs, rel_to, name) if nested_key: # Update kwargs with related object try: kwargs[name] = rel_to.objects.get_by_natural_key( *nested_key ) except rel_to.DoesNotExist: # If related object doesn't exist, assume this one doesn't raise self.model.DoesNotExist() else: kwargs[name] = None return self.get(**kwargs)
python
def get_by_natural_key(self, *args): """ Return the object corresponding to the provided natural key. (This is a generic implementation of the standard Django function) """ kwargs = self.natural_key_kwargs(*args) # Since kwargs already has __ lookups in it, we could just do this: # return self.get(**kwargs) # But, we should call each related model's get_by_natural_key in case # it's been overridden for name, rel_to in self.model.get_natural_key_info(): if not rel_to: continue # Extract natural key for related object nested_key = extract_nested_key(kwargs, rel_to, name) if nested_key: # Update kwargs with related object try: kwargs[name] = rel_to.objects.get_by_natural_key( *nested_key ) except rel_to.DoesNotExist: # If related object doesn't exist, assume this one doesn't raise self.model.DoesNotExist() else: kwargs[name] = None return self.get(**kwargs)
[ "def", "get_by_natural_key", "(", "self", ",", "*", "args", ")", ":", "kwargs", "=", "self", ".", "natural_key_kwargs", "(", "*", "args", ")", "# Since kwargs already has __ lookups in it, we could just do this:", "# return self.get(**kwargs)", "# But, we should call each rel...
Return the object corresponding to the provided natural key. (This is a generic implementation of the standard Django function)
[ "Return", "the", "object", "corresponding", "to", "the", "provided", "natural", "key", "." ]
f6bd6baf848e709ae9920b259a3ad1a6be8af615
https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L38-L70
train
23,321
wq/django-natural-keys
natural_keys/models.py
NaturalKeyModelManager.create_by_natural_key
def create_by_natural_key(self, *args): """ Create a new object from the provided natural key values. If the natural key contains related objects, recursively get or create them by their natural keys. """ kwargs = self.natural_key_kwargs(*args) for name, rel_to in self.model.get_natural_key_info(): if not rel_to: continue nested_key = extract_nested_key(kwargs, rel_to, name) # Automatically create any related objects as needed if nested_key: kwargs[name], is_new = ( rel_to.objects.get_or_create_by_natural_key(*nested_key) ) else: kwargs[name] = None return self.create(**kwargs)
python
def create_by_natural_key(self, *args): """ Create a new object from the provided natural key values. If the natural key contains related objects, recursively get or create them by their natural keys. """ kwargs = self.natural_key_kwargs(*args) for name, rel_to in self.model.get_natural_key_info(): if not rel_to: continue nested_key = extract_nested_key(kwargs, rel_to, name) # Automatically create any related objects as needed if nested_key: kwargs[name], is_new = ( rel_to.objects.get_or_create_by_natural_key(*nested_key) ) else: kwargs[name] = None return self.create(**kwargs)
[ "def", "create_by_natural_key", "(", "self", ",", "*", "args", ")", ":", "kwargs", "=", "self", ".", "natural_key_kwargs", "(", "*", "args", ")", "for", "name", ",", "rel_to", "in", "self", ".", "model", ".", "get_natural_key_info", "(", ")", ":", "if", ...
Create a new object from the provided natural key values. If the natural key contains related objects, recursively get or create them by their natural keys.
[ "Create", "a", "new", "object", "from", "the", "provided", "natural", "key", "values", ".", "If", "the", "natural", "key", "contains", "related", "objects", "recursively", "get", "or", "create", "them", "by", "their", "natural", "keys", "." ]
f6bd6baf848e709ae9920b259a3ad1a6be8af615
https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L72-L91
train
23,322
wq/django-natural-keys
natural_keys/models.py
NaturalKeyModelManager.get_or_create_by_natural_key
def get_or_create_by_natural_key(self, *args): """ get_or_create + get_by_natural_key """ try: return self.get_by_natural_key(*args), False except self.model.DoesNotExist: return self.create_by_natural_key(*args), True
python
def get_or_create_by_natural_key(self, *args): """ get_or_create + get_by_natural_key """ try: return self.get_by_natural_key(*args), False except self.model.DoesNotExist: return self.create_by_natural_key(*args), True
[ "def", "get_or_create_by_natural_key", "(", "self", ",", "*", "args", ")", ":", "try", ":", "return", "self", ".", "get_by_natural_key", "(", "*", "args", ")", ",", "False", "except", "self", ".", "model", ".", "DoesNotExist", ":", "return", "self", ".", ...
get_or_create + get_by_natural_key
[ "get_or_create", "+", "get_by_natural_key" ]
f6bd6baf848e709ae9920b259a3ad1a6be8af615
https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L93-L100
train
23,323
wq/django-natural-keys
natural_keys/models.py
NaturalKeyModelManager.resolve_keys
def resolve_keys(self, keys, auto_create=False): """ Resolve the list of given keys into objects, if possible. Returns a mapping and a success indicator. """ resolved = {} success = True for key in keys: if auto_create: resolved[key] = self.find(*key) else: try: resolved[key] = self.get_by_natural_key(*key) except self.model.DoesNotExist: success = False resolved[key] = None return resolved, success
python
def resolve_keys(self, keys, auto_create=False): """ Resolve the list of given keys into objects, if possible. Returns a mapping and a success indicator. """ resolved = {} success = True for key in keys: if auto_create: resolved[key] = self.find(*key) else: try: resolved[key] = self.get_by_natural_key(*key) except self.model.DoesNotExist: success = False resolved[key] = None return resolved, success
[ "def", "resolve_keys", "(", "self", ",", "keys", ",", "auto_create", "=", "False", ")", ":", "resolved", "=", "{", "}", "success", "=", "True", "for", "key", "in", "keys", ":", "if", "auto_create", ":", "resolved", "[", "key", "]", "=", "self", ".", ...
Resolve the list of given keys into objects, if possible. Returns a mapping and a success indicator.
[ "Resolve", "the", "list", "of", "given", "keys", "into", "objects", "if", "possible", ".", "Returns", "a", "mapping", "and", "a", "success", "indicator", "." ]
f6bd6baf848e709ae9920b259a3ad1a6be8af615
https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L117-L133
train
23,324
wq/django-natural-keys
natural_keys/models.py
NaturalKeyModel.get_natural_key_info
def get_natural_key_info(cls): """ Derive natural key from first unique_together definition, noting which fields are related objects vs. regular fields. """ fields = cls.get_natural_key_def() info = [] for name in fields: field = cls._meta.get_field(name) rel_to = None if hasattr(field, 'rel'): rel_to = field.rel.to if field.rel else None elif hasattr(field, 'remote_field'): if field.remote_field: rel_to = field.remote_field.model else: rel_to = None info.append((name, rel_to)) return info
python
def get_natural_key_info(cls): """ Derive natural key from first unique_together definition, noting which fields are related objects vs. regular fields. """ fields = cls.get_natural_key_def() info = [] for name in fields: field = cls._meta.get_field(name) rel_to = None if hasattr(field, 'rel'): rel_to = field.rel.to if field.rel else None elif hasattr(field, 'remote_field'): if field.remote_field: rel_to = field.remote_field.model else: rel_to = None info.append((name, rel_to)) return info
[ "def", "get_natural_key_info", "(", "cls", ")", ":", "fields", "=", "cls", ".", "get_natural_key_def", "(", ")", "info", "=", "[", "]", "for", "name", "in", "fields", ":", "field", "=", "cls", ".", "_meta", ".", "get_field", "(", "name", ")", "rel_to",...
Derive natural key from first unique_together definition, noting which fields are related objects vs. regular fields.
[ "Derive", "natural", "key", "from", "first", "unique_together", "definition", "noting", "which", "fields", "are", "related", "objects", "vs", ".", "regular", "fields", "." ]
f6bd6baf848e709ae9920b259a3ad1a6be8af615
https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L144-L162
train
23,325
wq/django-natural-keys
natural_keys/models.py
NaturalKeyModel.get_natural_key_fields
def get_natural_key_fields(cls): """ Determine actual natural key field list, incorporating the natural keys of related objects as needed. """ natural_key = [] for name, rel_to in cls.get_natural_key_info(): if not rel_to: natural_key.append(name) else: nested_key = rel_to.get_natural_key_fields() natural_key.extend([ name + '__' + nname for nname in nested_key ]) return natural_key
python
def get_natural_key_fields(cls): """ Determine actual natural key field list, incorporating the natural keys of related objects as needed. """ natural_key = [] for name, rel_to in cls.get_natural_key_info(): if not rel_to: natural_key.append(name) else: nested_key = rel_to.get_natural_key_fields() natural_key.extend([ name + '__' + nname for nname in nested_key ]) return natural_key
[ "def", "get_natural_key_fields", "(", "cls", ")", ":", "natural_key", "=", "[", "]", "for", "name", ",", "rel_to", "in", "cls", ".", "get_natural_key_info", "(", ")", ":", "if", "not", "rel_to", ":", "natural_key", ".", "append", "(", "name", ")", "else"...
Determine actual natural key field list, incorporating the natural keys of related objects as needed.
[ "Determine", "actual", "natural", "key", "field", "list", "incorporating", "the", "natural", "keys", "of", "related", "objects", "as", "needed", "." ]
f6bd6baf848e709ae9920b259a3ad1a6be8af615
https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L177-L192
train
23,326
wq/django-natural-keys
natural_keys/models.py
NaturalKeyModel.natural_key
def natural_key(self): """ Return the natural key for this object. (This is a generic implementation of the standard Django function) """ # Recursively extract properties from related objects if needed vals = [reduce(getattr, name.split('__'), self) for name in self.get_natural_key_fields()] return vals
python
def natural_key(self): """ Return the natural key for this object. (This is a generic implementation of the standard Django function) """ # Recursively extract properties from related objects if needed vals = [reduce(getattr, name.split('__'), self) for name in self.get_natural_key_fields()] return vals
[ "def", "natural_key", "(", "self", ")", ":", "# Recursively extract properties from related objects if needed", "vals", "=", "[", "reduce", "(", "getattr", ",", "name", ".", "split", "(", "'__'", ")", ",", "self", ")", "for", "name", "in", "self", ".", "get_na...
Return the natural key for this object. (This is a generic implementation of the standard Django function)
[ "Return", "the", "natural", "key", "for", "this", "object", "." ]
f6bd6baf848e709ae9920b259a3ad1a6be8af615
https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L194-L203
train
23,327
SystemRDL/systemrdl-compiler
systemrdl/messages.py
SourceRef.derive_coordinates
def derive_coordinates(self): """ Depending on the compilation source, some members of the SourceRef object may be incomplete. Calling this function performs the necessary derivations to complete the object. """ if self._coordinates_resolved: # Coordinates were already resolved. Skip return if self.seg_map is not None: # Translate coordinates self.start, self.filename, include_ref = self.seg_map.derive_source_offset(self.start) self.end, end_filename, _ = self.seg_map.derive_source_offset(self.end, is_end=True) else: end_filename = self.filename line_start = 0 lineno = 1 file_pos = 0 # Skip deriving end coordinate if selection spans multiple files if self.filename != end_filename: get_end = False elif self.end is None: get_end = False else: get_end = True if (self.filename is not None) and (self.start is not None): with open(self.filename, 'r', newline='', encoding='utf_8') as fp: while True: line_text = fp.readline() file_pos += len(line_text) if line_text == "": break if (self.start_line is None) and (self.start < file_pos): self.start_line = lineno self.start_col = self.start - line_start self.start_line_text = line_text.rstrip("\n").rstrip("\r") if not get_end: break if get_end and (self.end_line is None) and (self.end < file_pos): self.end_line = lineno self.end_col = self.end - line_start break lineno += 1 line_start = file_pos # If no end coordinate was derived, just do a single char selection if not get_end: self.end_line = self.start_line self.end_col = self.start_col self.end = self.start self._coordinates_resolved = True
python
def derive_coordinates(self): """ Depending on the compilation source, some members of the SourceRef object may be incomplete. Calling this function performs the necessary derivations to complete the object. """ if self._coordinates_resolved: # Coordinates were already resolved. Skip return if self.seg_map is not None: # Translate coordinates self.start, self.filename, include_ref = self.seg_map.derive_source_offset(self.start) self.end, end_filename, _ = self.seg_map.derive_source_offset(self.end, is_end=True) else: end_filename = self.filename line_start = 0 lineno = 1 file_pos = 0 # Skip deriving end coordinate if selection spans multiple files if self.filename != end_filename: get_end = False elif self.end is None: get_end = False else: get_end = True if (self.filename is not None) and (self.start is not None): with open(self.filename, 'r', newline='', encoding='utf_8') as fp: while True: line_text = fp.readline() file_pos += len(line_text) if line_text == "": break if (self.start_line is None) and (self.start < file_pos): self.start_line = lineno self.start_col = self.start - line_start self.start_line_text = line_text.rstrip("\n").rstrip("\r") if not get_end: break if get_end and (self.end_line is None) and (self.end < file_pos): self.end_line = lineno self.end_col = self.end - line_start break lineno += 1 line_start = file_pos # If no end coordinate was derived, just do a single char selection if not get_end: self.end_line = self.start_line self.end_col = self.start_col self.end = self.start self._coordinates_resolved = True
[ "def", "derive_coordinates", "(", "self", ")", ":", "if", "self", ".", "_coordinates_resolved", ":", "# Coordinates were already resolved. Skip", "return", "if", "self", ".", "seg_map", "is", "not", "None", ":", "# Translate coordinates", "self", ".", "start", ",", ...
Depending on the compilation source, some members of the SourceRef object may be incomplete. Calling this function performs the necessary derivations to complete the object.
[ "Depending", "on", "the", "compilation", "source", "some", "members", "of", "the", "SourceRef", "object", "may", "be", "incomplete", ".", "Calling", "this", "function", "performs", "the", "necessary", "derivations", "to", "complete", "the", "object", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/messages.py#L108-L171
train
23,328
SystemRDL/systemrdl-compiler
systemrdl/messages.py
MessagePrinter.format_message
def format_message(self, severity, text, src_ref): """ Formats the message prior to emitting it. Parameters ---------- severity: :class:`Severity` Message severity. text: str Body of message src_ref: :class:`SourceRef` Reference to source context object Returns ------- list List of strings for each line of the message """ lines = [] if severity >= Severity.ERROR: color = Fore.RED elif severity >= Severity.WARNING: color = Fore.YELLOW else: color = Fore.GREEN if src_ref is None: # No message context available lines.append( color + Style.BRIGHT + severity.name.lower() + ": " + Style.RESET_ALL + text ) return lines src_ref.derive_coordinates() if (src_ref.start_line is not None) and (src_ref.start_col is not None): # Start line and column is known lines.append( Fore.WHITE + Style.BRIGHT + "%s:%d:%d: " % (src_ref.filename, src_ref.start_line, src_ref.start_col) + color + severity.name.lower() + ": " + Style.RESET_ALL + text ) elif src_ref.start_line is not None: # Only line number is known lines.append( Fore.WHITE + Style.BRIGHT + "%s:%d: " % (src_ref.filename, src_ref.start_line) + color + severity.name.lower() + ": " + Style.RESET_ALL + text ) else: # Only filename is known lines.append( Fore.WHITE + Style.BRIGHT + "%s: " % src_ref.filename + color + severity.name.lower() + ": " + Style.RESET_ALL + text ) # If src_ref highlights a span within a single line of text, print it if (src_ref.start_line is not None) and (src_ref.end_line is not None): if src_ref.start_line != src_ref.end_line: # multi-line reference # Select remainder of the line width = len(src_ref.start_line_text) - src_ref.start_col lines.append( src_ref.start_line_text[:src_ref.start_col] + color + Style.BRIGHT + src_ref.start_line_text[src_ref.start_col:] + Style.RESET_ALL ) lines.append( " "*src_ref.start_col + color + Style.BRIGHT + "^"*width + Style.RESET_ALL ) else: # Single line width = src_ref.end_col - src_ref.start_col + 1 lines.append( src_ref.start_line_text[:src_ref.start_col] + color + Style.BRIGHT + src_ref.start_line_text[src_ref.start_col : src_ref.end_col+1] + Style.RESET_ALL + src_ref.start_line_text[src_ref.end_col+1:] ) lines.append( " "*src_ref.start_col + color + Style.BRIGHT + "^"*width + Style.RESET_ALL ) return lines
python
def format_message(self, severity, text, src_ref): """ Formats the message prior to emitting it. Parameters ---------- severity: :class:`Severity` Message severity. text: str Body of message src_ref: :class:`SourceRef` Reference to source context object Returns ------- list List of strings for each line of the message """ lines = [] if severity >= Severity.ERROR: color = Fore.RED elif severity >= Severity.WARNING: color = Fore.YELLOW else: color = Fore.GREEN if src_ref is None: # No message context available lines.append( color + Style.BRIGHT + severity.name.lower() + ": " + Style.RESET_ALL + text ) return lines src_ref.derive_coordinates() if (src_ref.start_line is not None) and (src_ref.start_col is not None): # Start line and column is known lines.append( Fore.WHITE + Style.BRIGHT + "%s:%d:%d: " % (src_ref.filename, src_ref.start_line, src_ref.start_col) + color + severity.name.lower() + ": " + Style.RESET_ALL + text ) elif src_ref.start_line is not None: # Only line number is known lines.append( Fore.WHITE + Style.BRIGHT + "%s:%d: " % (src_ref.filename, src_ref.start_line) + color + severity.name.lower() + ": " + Style.RESET_ALL + text ) else: # Only filename is known lines.append( Fore.WHITE + Style.BRIGHT + "%s: " % src_ref.filename + color + severity.name.lower() + ": " + Style.RESET_ALL + text ) # If src_ref highlights a span within a single line of text, print it if (src_ref.start_line is not None) and (src_ref.end_line is not None): if src_ref.start_line != src_ref.end_line: # multi-line reference # Select remainder of the line width = len(src_ref.start_line_text) - src_ref.start_col lines.append( src_ref.start_line_text[:src_ref.start_col] + color + Style.BRIGHT + src_ref.start_line_text[src_ref.start_col:] + Style.RESET_ALL ) lines.append( " "*src_ref.start_col + color + Style.BRIGHT + "^"*width + Style.RESET_ALL ) else: # Single line width = src_ref.end_col - src_ref.start_col + 1 lines.append( src_ref.start_line_text[:src_ref.start_col] + color + Style.BRIGHT + src_ref.start_line_text[src_ref.start_col : src_ref.end_col+1] + Style.RESET_ALL + src_ref.start_line_text[src_ref.end_col+1:] ) lines.append( " "*src_ref.start_col + color + Style.BRIGHT + "^"*width + Style.RESET_ALL ) return lines
[ "def", "format_message", "(", "self", ",", "severity", ",", "text", ",", "src_ref", ")", ":", "lines", "=", "[", "]", "if", "severity", ">=", "Severity", ".", "ERROR", ":", "color", "=", "Fore", ".", "RED", "elif", "severity", ">=", "Severity", ".", ...
Formats the message prior to emitting it. Parameters ---------- severity: :class:`Severity` Message severity. text: str Body of message src_ref: :class:`SourceRef` Reference to source context object Returns ------- list List of strings for each line of the message
[ "Formats", "the", "message", "prior", "to", "emitting", "it", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/messages.py#L240-L344
train
23,329
SystemRDL/systemrdl-compiler
systemrdl/messages.py
MessagePrinter.emit_message
def emit_message(self, lines): """ Emit message. Default printer emits messages to stderr Parameters ---------- lines: list List of strings containing each line of the message """ for line in lines: print(line, file=sys.stderr)
python
def emit_message(self, lines): """ Emit message. Default printer emits messages to stderr Parameters ---------- lines: list List of strings containing each line of the message """ for line in lines: print(line, file=sys.stderr)
[ "def", "emit_message", "(", "self", ",", "lines", ")", ":", "for", "line", "in", "lines", ":", "print", "(", "line", ",", "file", "=", "sys", ".", "stderr", ")" ]
Emit message. Default printer emits messages to stderr Parameters ---------- lines: list List of strings containing each line of the message
[ "Emit", "message", ".", "Default", "printer", "emits", "messages", "to", "stderr" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/messages.py#L347-L359
train
23,330
SystemRDL/systemrdl-compiler
systemrdl/core/parameter.py
Parameter.get_value
def get_value(self): """ Evaluate self.expr to get the parameter's value """ if (self._value is None) and (self.expr is not None): self._value = self.expr.get_value() return self._value
python
def get_value(self): """ Evaluate self.expr to get the parameter's value """ if (self._value is None) and (self.expr is not None): self._value = self.expr.get_value() return self._value
[ "def", "get_value", "(", "self", ")", ":", "if", "(", "self", ".", "_value", "is", "None", ")", "and", "(", "self", ".", "expr", "is", "not", "None", ")", ":", "self", ".", "_value", "=", "self", ".", "expr", ".", "get_value", "(", ")", "return",...
Evaluate self.expr to get the parameter's value
[ "Evaluate", "self", ".", "expr", "to", "get", "the", "parameter", "s", "value" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/parameter.py#L17-L24
train
23,331
SystemRDL/systemrdl-compiler
systemrdl/core/expressions.py
is_castable
def is_castable(src, dst): """ Check if src type can be cast to dst type """ if ((src in [int, bool]) or rdltypes.is_user_enum(src)) and (dst in [int, bool]): # Pure numeric or enum can be cast to a numeric return True elif (src == rdltypes.ArrayPlaceholder) and (dst == rdltypes.ArrayPlaceholder): # Check that array element types also match if src.element_type is None: # indeterminate array type. Is castable return True elif src.element_type == dst.element_type: return True else: return False elif rdltypes.is_user_struct(dst): # Structs can be assigned their derived counterparts - aka their subclasses return issubclass(src, dst) elif dst == rdltypes.PropertyReference: return issubclass(src, rdltypes.PropertyReference) elif src == dst: return True else: return False
python
def is_castable(src, dst): """ Check if src type can be cast to dst type """ if ((src in [int, bool]) or rdltypes.is_user_enum(src)) and (dst in [int, bool]): # Pure numeric or enum can be cast to a numeric return True elif (src == rdltypes.ArrayPlaceholder) and (dst == rdltypes.ArrayPlaceholder): # Check that array element types also match if src.element_type is None: # indeterminate array type. Is castable return True elif src.element_type == dst.element_type: return True else: return False elif rdltypes.is_user_struct(dst): # Structs can be assigned their derived counterparts - aka their subclasses return issubclass(src, dst) elif dst == rdltypes.PropertyReference: return issubclass(src, rdltypes.PropertyReference) elif src == dst: return True else: return False
[ "def", "is_castable", "(", "src", ",", "dst", ")", ":", "if", "(", "(", "src", "in", "[", "int", ",", "bool", "]", ")", "or", "rdltypes", ".", "is_user_enum", "(", "src", ")", ")", "and", "(", "dst", "in", "[", "int", ",", "bool", "]", ")", "...
Check if src type can be cast to dst type
[ "Check", "if", "src", "type", "can", "be", "cast", "to", "dst", "type" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/expressions.py#L1193-L1217
train
23,332
SystemRDL/systemrdl-compiler
systemrdl/core/expressions.py
InstRef.predict_type
def predict_type(self): """ Traverse the ref_elements path and determine the component type being referenced. Also do some checks on the array indexes """ current_comp = self.ref_root for name, array_suffixes, name_src_ref in self.ref_elements: # find instance current_comp = current_comp.get_child_by_name(name) if current_comp is None: # Not found! self.msg.fatal( "Could not resolve hierarchical reference to '%s'" % name, name_src_ref ) # Do type-check in array suffixes for array_suffix in array_suffixes: array_suffix.predict_type() # Check array suffixes if (isinstance(current_comp, comp.AddressableComponent)) and current_comp.is_array: # is an array if len(array_suffixes) != len(current_comp.array_dimensions): self.msg.fatal( "Incompatible number of index dimensions after '%s'. Expected %d, found %d." % (name, len(current_comp.array_dimensions), len(array_suffixes)), name_src_ref ) elif array_suffixes: # Has array suffixes. Check if compatible with referenced component self.msg.fatal( "Unable to index non-array component '%s'" % name, name_src_ref ) return type(current_comp)
python
def predict_type(self): """ Traverse the ref_elements path and determine the component type being referenced. Also do some checks on the array indexes """ current_comp = self.ref_root for name, array_suffixes, name_src_ref in self.ref_elements: # find instance current_comp = current_comp.get_child_by_name(name) if current_comp is None: # Not found! self.msg.fatal( "Could not resolve hierarchical reference to '%s'" % name, name_src_ref ) # Do type-check in array suffixes for array_suffix in array_suffixes: array_suffix.predict_type() # Check array suffixes if (isinstance(current_comp, comp.AddressableComponent)) and current_comp.is_array: # is an array if len(array_suffixes) != len(current_comp.array_dimensions): self.msg.fatal( "Incompatible number of index dimensions after '%s'. Expected %d, found %d." % (name, len(current_comp.array_dimensions), len(array_suffixes)), name_src_ref ) elif array_suffixes: # Has array suffixes. Check if compatible with referenced component self.msg.fatal( "Unable to index non-array component '%s'" % name, name_src_ref ) return type(current_comp)
[ "def", "predict_type", "(", "self", ")", ":", "current_comp", "=", "self", ".", "ref_root", "for", "name", ",", "array_suffixes", ",", "name_src_ref", "in", "self", ".", "ref_elements", ":", "# find instance", "current_comp", "=", "current_comp", ".", "get_child...
Traverse the ref_elements path and determine the component type being referenced. Also do some checks on the array indexes
[ "Traverse", "the", "ref_elements", "path", "and", "determine", "the", "component", "type", "being", "referenced", ".", "Also", "do", "some", "checks", "on", "the", "array", "indexes" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/expressions.py#L1063-L1101
train
23,333
SystemRDL/systemrdl-compiler
systemrdl/core/expressions.py
InstRef.get_value
def get_value(self, eval_width=None): """ Build a resolved ComponentRef container that describes the relative path """ resolved_ref_elements = [] for name, array_suffixes, name_src_ref in self.ref_elements: idx_list = [ suffix.get_value() for suffix in array_suffixes ] resolved_ref_elements.append((name, idx_list, name_src_ref)) # Create container cref = rdltypes.ComponentRef(self.ref_root, resolved_ref_elements) return cref
python
def get_value(self, eval_width=None): """ Build a resolved ComponentRef container that describes the relative path """ resolved_ref_elements = [] for name, array_suffixes, name_src_ref in self.ref_elements: idx_list = [ suffix.get_value() for suffix in array_suffixes ] resolved_ref_elements.append((name, idx_list, name_src_ref)) # Create container cref = rdltypes.ComponentRef(self.ref_root, resolved_ref_elements) return cref
[ "def", "get_value", "(", "self", ",", "eval_width", "=", "None", ")", ":", "resolved_ref_elements", "=", "[", "]", "for", "name", ",", "array_suffixes", ",", "name_src_ref", "in", "self", ".", "ref_elements", ":", "idx_list", "=", "[", "suffix", ".", "get_...
Build a resolved ComponentRef container that describes the relative path
[ "Build", "a", "resolved", "ComponentRef", "container", "that", "describes", "the", "relative", "path" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/expressions.py#L1103-L1117
train
23,334
SystemRDL/systemrdl-compiler
systemrdl/core/expressions.py
PropRef.predict_type
def predict_type(self): """ Predict the type of the inst_ref, and make sure the property being referenced is allowed """ inst_type = self.inst_ref.predict_type() if self.prop_ref_type.allowed_inst_type != inst_type: self.msg.fatal( "'%s' is not a valid property of instance" % self.prop_ref_type.get_name(), self.src_ref ) return self.prop_ref_type
python
def predict_type(self): """ Predict the type of the inst_ref, and make sure the property being referenced is allowed """ inst_type = self.inst_ref.predict_type() if self.prop_ref_type.allowed_inst_type != inst_type: self.msg.fatal( "'%s' is not a valid property of instance" % self.prop_ref_type.get_name(), self.src_ref ) return self.prop_ref_type
[ "def", "predict_type", "(", "self", ")", ":", "inst_type", "=", "self", ".", "inst_ref", ".", "predict_type", "(", ")", "if", "self", ".", "prop_ref_type", ".", "allowed_inst_type", "!=", "inst_type", ":", "self", ".", "msg", ".", "fatal", "(", "\"'%s' is ...
Predict the type of the inst_ref, and make sure the property being referenced is allowed
[ "Predict", "the", "type", "of", "the", "inst_ref", "and", "make", "sure", "the", "property", "being", "referenced", "is", "allowed" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/expressions.py#L1129-L1142
train
23,335
SystemRDL/systemrdl-compiler
systemrdl/node.py
get_group_node_size
def get_group_node_size(node): """ Shared getter for AddrmapNode and RegfileNode's "size" property """ # After structural placement, children are sorted if( not node.inst.children or (not isinstance(node.inst.children[-1], comp.AddressableComponent)) ): # No addressable child exists. return 0 # Current node's size is based on last child last_child_node = Node._factory(node.inst.children[-1], node.env, node) return( last_child_node.inst.addr_offset + last_child_node.total_size )
python
def get_group_node_size(node): """ Shared getter for AddrmapNode and RegfileNode's "size" property """ # After structural placement, children are sorted if( not node.inst.children or (not isinstance(node.inst.children[-1], comp.AddressableComponent)) ): # No addressable child exists. return 0 # Current node's size is based on last child last_child_node = Node._factory(node.inst.children[-1], node.env, node) return( last_child_node.inst.addr_offset + last_child_node.total_size )
[ "def", "get_group_node_size", "(", "node", ")", ":", "# After structural placement, children are sorted", "if", "(", "not", "node", ".", "inst", ".", "children", "or", "(", "not", "isinstance", "(", "node", ".", "inst", ".", "children", "[", "-", "1", "]", "...
Shared getter for AddrmapNode and RegfileNode's "size" property
[ "Shared", "getter", "for", "AddrmapNode", "and", "RegfileNode", "s", "size", "property" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L810-L826
train
23,336
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.add_derived_property
def add_derived_property(cls, getter_function, name=None): """ Register a user-defined derived property Parameters ---------- getter_function : function Function that fetches the result of the user-defined derived property name : str Derived property name If unassigned, will default to the function's name """ if name is None: name = getter_function.__name__ mp = property(fget=getter_function) setattr(cls, name, mp)
python
def add_derived_property(cls, getter_function, name=None): """ Register a user-defined derived property Parameters ---------- getter_function : function Function that fetches the result of the user-defined derived property name : str Derived property name If unassigned, will default to the function's name """ if name is None: name = getter_function.__name__ mp = property(fget=getter_function) setattr(cls, name, mp)
[ "def", "add_derived_property", "(", "cls", ",", "getter_function", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "getter_function", ".", "__name__", "mp", "=", "property", "(", "fget", "=", "getter_function", ")", "setat...
Register a user-defined derived property Parameters ---------- getter_function : function Function that fetches the result of the user-defined derived property name : str Derived property name If unassigned, will default to the function's name
[ "Register", "a", "user", "-", "defined", "derived", "property" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L55-L71
train
23,337
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.children
def children(self, unroll=False, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate children of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~Node` All immediate children """ for child_inst in self.inst.children: if skip_not_present: # Check if property ispresent == False if not child_inst.properties.get('ispresent', True): # ispresent was explicitly set to False. Skip it continue if unroll and isinstance(child_inst, comp.AddressableComponent) and child_inst.is_array: # Unroll the array range_list = [range(n) for n in child_inst.array_dimensions] for idxs in itertools.product(*range_list): N = Node._factory(child_inst, self.env, self) N.current_idx = idxs # pylint: disable=attribute-defined-outside-init yield N else: yield Node._factory(child_inst, self.env, self)
python
def children(self, unroll=False, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate children of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~Node` All immediate children """ for child_inst in self.inst.children: if skip_not_present: # Check if property ispresent == False if not child_inst.properties.get('ispresent', True): # ispresent was explicitly set to False. Skip it continue if unroll and isinstance(child_inst, comp.AddressableComponent) and child_inst.is_array: # Unroll the array range_list = [range(n) for n in child_inst.array_dimensions] for idxs in itertools.product(*range_list): N = Node._factory(child_inst, self.env, self) N.current_idx = idxs # pylint: disable=attribute-defined-outside-init yield N else: yield Node._factory(child_inst, self.env, self)
[ "def", "children", "(", "self", ",", "unroll", "=", "False", ",", "skip_not_present", "=", "True", ")", ":", "for", "child_inst", "in", "self", ".", "inst", ".", "children", ":", "if", "skip_not_present", ":", "# Check if property ispresent == False", "if", "n...
Returns an iterator that provides nodes for all immediate children of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~Node` All immediate children
[ "Returns", "an", "iterator", "that", "provides", "nodes", "for", "all", "immediate", "children", "of", "this", "component", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L74-L107
train
23,338
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.descendants
def descendants(self, unroll=False, skip_not_present=True, in_post_order=False): """ Returns an iterator that provides nodes for all descendants of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is set to False in_post_order : bool If True, descendants are walked using post-order traversal (children first) rather than the default pre-order traversal (parents first). Yields ------ :class:`~Node` All descendant nodes of this component """ for child in self.children(unroll, skip_not_present): if in_post_order: yield from child.descendants(unroll, skip_not_present, in_post_order) yield child if not in_post_order: yield from child.descendants(unroll, skip_not_present, in_post_order)
python
def descendants(self, unroll=False, skip_not_present=True, in_post_order=False): """ Returns an iterator that provides nodes for all descendants of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is set to False in_post_order : bool If True, descendants are walked using post-order traversal (children first) rather than the default pre-order traversal (parents first). Yields ------ :class:`~Node` All descendant nodes of this component """ for child in self.children(unroll, skip_not_present): if in_post_order: yield from child.descendants(unroll, skip_not_present, in_post_order) yield child if not in_post_order: yield from child.descendants(unroll, skip_not_present, in_post_order)
[ "def", "descendants", "(", "self", ",", "unroll", "=", "False", ",", "skip_not_present", "=", "True", ",", "in_post_order", "=", "False", ")", ":", "for", "child", "in", "self", ".", "children", "(", "unroll", ",", "skip_not_present", ")", ":", "if", "in...
Returns an iterator that provides nodes for all descendants of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is set to False in_post_order : bool If True, descendants are walked using post-order traversal (children first) rather than the default pre-order traversal (parents first). Yields ------ :class:`~Node` All descendant nodes of this component
[ "Returns", "an", "iterator", "that", "provides", "nodes", "for", "all", "descendants", "of", "this", "component", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L110-L140
train
23,339
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.signals
def signals(self, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate signals of this component. Parameters ---------- skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~SignalNode` All signals in this component """ for child in self.children(skip_not_present=skip_not_present): if isinstance(child, SignalNode): yield child
python
def signals(self, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate signals of this component. Parameters ---------- skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~SignalNode` All signals in this component """ for child in self.children(skip_not_present=skip_not_present): if isinstance(child, SignalNode): yield child
[ "def", "signals", "(", "self", ",", "skip_not_present", "=", "True", ")", ":", "for", "child", "in", "self", ".", "children", "(", "skip_not_present", "=", "skip_not_present", ")", ":", "if", "isinstance", "(", "child", ",", "SignalNode", ")", ":", "yield"...
Returns an iterator that provides nodes for all immediate signals of this component. Parameters ---------- skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~SignalNode` All signals in this component
[ "Returns", "an", "iterator", "that", "provides", "nodes", "for", "all", "immediate", "signals", "of", "this", "component", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L143-L160
train
23,340
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.fields
def fields(self, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate fields of this component. Parameters ---------- skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~FieldNode` All fields in this component """ for child in self.children(skip_not_present=skip_not_present): if isinstance(child, FieldNode): yield child
python
def fields(self, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate fields of this component. Parameters ---------- skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~FieldNode` All fields in this component """ for child in self.children(skip_not_present=skip_not_present): if isinstance(child, FieldNode): yield child
[ "def", "fields", "(", "self", ",", "skip_not_present", "=", "True", ")", ":", "for", "child", "in", "self", ".", "children", "(", "skip_not_present", "=", "skip_not_present", ")", ":", "if", "isinstance", "(", "child", ",", "FieldNode", ")", ":", "yield", ...
Returns an iterator that provides nodes for all immediate fields of this component. Parameters ---------- skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~FieldNode` All fields in this component
[ "Returns", "an", "iterator", "that", "provides", "nodes", "for", "all", "immediate", "fields", "of", "this", "component", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L163-L180
train
23,341
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.registers
def registers(self, unroll=False, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate registers of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~RegNode` All registers in this component """ for child in self.children(unroll, skip_not_present): if isinstance(child, RegNode): yield child
python
def registers(self, unroll=False, skip_not_present=True): """ Returns an iterator that provides nodes for all immediate registers of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~RegNode` All registers in this component """ for child in self.children(unroll, skip_not_present): if isinstance(child, RegNode): yield child
[ "def", "registers", "(", "self", ",", "unroll", "=", "False", ",", "skip_not_present", "=", "True", ")", ":", "for", "child", "in", "self", ".", "children", "(", "unroll", ",", "skip_not_present", ")", ":", "if", "isinstance", "(", "child", ",", "RegNode...
Returns an iterator that provides nodes for all immediate registers of this component. Parameters ---------- unroll : bool If True, any children that are arrays are unrolled. skip_not_present : bool If True, skips children whose 'ispresent' property is set to False Yields ------ :class:`~RegNode` All registers in this component
[ "Returns", "an", "iterator", "that", "provides", "nodes", "for", "all", "immediate", "registers", "of", "this", "component", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L183-L203
train
23,342
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.find_by_path
def find_by_path(self, path): """ Finds the descendant node that is located at the relative path Returns ``None`` if not found Raises exception if path is malformed, or array index is out of range Parameters ---------- path: str Path to target relative to current node Returns ------- :class:`~Node` or None Descendant Node. None if not found. Raises ------ ValueError If path syntax is invalid IndexError If an array index in the path is invalid """ pathparts = path.split('.') current_node = self for pathpart in pathparts: m = re.fullmatch(r'^(\w+)((?:\[(?:\d+|0[xX][\da-fA-F]+)\])*)$', pathpart) if not m: raise ValueError("Invalid path") inst_name, array_suffix = m.group(1,2) idx_list = [ int(s,0) for s in re.findall(r'\[(\d+|0[xX][\da-fA-F]+)\]', array_suffix) ] current_node = current_node.get_child_by_name(inst_name) if current_node is None: return None if idx_list: if (isinstance(current_node, AddressableNode)) and current_node.inst.is_array: # is an array if len(idx_list) != len(current_node.inst.array_dimensions): raise IndexError("Wrong number of array dimensions") current_node.current_idx = [] # pylint: disable=attribute-defined-outside-init for i,idx in enumerate(idx_list): if idx >= current_node.inst.array_dimensions[i]: raise IndexError("Array index out of range") current_node.current_idx.append(idx) else: raise IndexError("Index attempted on non-array component") return current_node
python
def find_by_path(self, path): """ Finds the descendant node that is located at the relative path Returns ``None`` if not found Raises exception if path is malformed, or array index is out of range Parameters ---------- path: str Path to target relative to current node Returns ------- :class:`~Node` or None Descendant Node. None if not found. Raises ------ ValueError If path syntax is invalid IndexError If an array index in the path is invalid """ pathparts = path.split('.') current_node = self for pathpart in pathparts: m = re.fullmatch(r'^(\w+)((?:\[(?:\d+|0[xX][\da-fA-F]+)\])*)$', pathpart) if not m: raise ValueError("Invalid path") inst_name, array_suffix = m.group(1,2) idx_list = [ int(s,0) for s in re.findall(r'\[(\d+|0[xX][\da-fA-F]+)\]', array_suffix) ] current_node = current_node.get_child_by_name(inst_name) if current_node is None: return None if idx_list: if (isinstance(current_node, AddressableNode)) and current_node.inst.is_array: # is an array if len(idx_list) != len(current_node.inst.array_dimensions): raise IndexError("Wrong number of array dimensions") current_node.current_idx = [] # pylint: disable=attribute-defined-outside-init for i,idx in enumerate(idx_list): if idx >= current_node.inst.array_dimensions[i]: raise IndexError("Array index out of range") current_node.current_idx.append(idx) else: raise IndexError("Index attempted on non-array component") return current_node
[ "def", "find_by_path", "(", "self", ",", "path", ")", ":", "pathparts", "=", "path", ".", "split", "(", "'.'", ")", "current_node", "=", "self", "for", "pathpart", "in", "pathparts", ":", "m", "=", "re", ".", "fullmatch", "(", "r'^(\\w+)((?:\\[(?:\\d+|0[xX...
Finds the descendant node that is located at the relative path Returns ``None`` if not found Raises exception if path is malformed, or array index is out of range Parameters ---------- path: str Path to target relative to current node Returns ------- :class:`~Node` or None Descendant Node. None if not found. Raises ------ ValueError If path syntax is invalid IndexError If an array index in the path is invalid
[ "Finds", "the", "descendant", "node", "that", "is", "located", "at", "the", "relative", "path", "Returns", "None", "if", "not", "found", "Raises", "exception", "if", "path", "is", "malformed", "or", "array", "index", "is", "out", "of", "range" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L228-L278
train
23,343
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.get_property
def get_property(self, prop_name, **kwargs): """ Gets the SystemRDL component property If a property was not explicitly set in the RDL source, its default value is derived. In some cases, a default value is implied according to other property values. Properties values that are a reference to a component instance are converted to a :class:`~Node` overlay object. Parameters ---------- prop_name: str SystemRDL property name default: Override built-in default value of property. If the property was not explicitly set, return this value rather than the property's intrinsic default value. Raises ------ LookupError If prop_name is invalid """ ovr_default = False default = None if 'default' in kwargs: ovr_default = True default = kwargs.pop('default') # Check for stray kwargs if kwargs: raise TypeError("got an unexpected keyword argument '%s'" % list(kwargs.keys())[0]) # If its already in the component, then safe to bypass checks if prop_name in self.inst.properties: prop_value = self.inst.properties[prop_name] if isinstance(prop_value, rdltypes.ComponentRef): # If this is a hierarchical component reference, convert it to a Node reference prop_value = prop_value.build_node_ref(self, self.env) if isinstance(prop_value, rdltypes.PropertyReference): prop_value._resolve_node(self) return prop_value if ovr_default: # Default value is being overridden by user. Return their value return default # Otherwise, return its default value based on the property's rules rule = self.env.property_rules.lookup_property(prop_name) # Is it even a valid property or allowed for this component type? if rule is None: raise LookupError("Unknown property '%s'" % prop_name) if type(self.inst) not in rule.bindable_to: raise LookupError("Unknown property '%s'" % prop_name) # Return the default value as specified by the rulebook return rule.get_default(self)
python
def get_property(self, prop_name, **kwargs): """ Gets the SystemRDL component property If a property was not explicitly set in the RDL source, its default value is derived. In some cases, a default value is implied according to other property values. Properties values that are a reference to a component instance are converted to a :class:`~Node` overlay object. Parameters ---------- prop_name: str SystemRDL property name default: Override built-in default value of property. If the property was not explicitly set, return this value rather than the property's intrinsic default value. Raises ------ LookupError If prop_name is invalid """ ovr_default = False default = None if 'default' in kwargs: ovr_default = True default = kwargs.pop('default') # Check for stray kwargs if kwargs: raise TypeError("got an unexpected keyword argument '%s'" % list(kwargs.keys())[0]) # If its already in the component, then safe to bypass checks if prop_name in self.inst.properties: prop_value = self.inst.properties[prop_name] if isinstance(prop_value, rdltypes.ComponentRef): # If this is a hierarchical component reference, convert it to a Node reference prop_value = prop_value.build_node_ref(self, self.env) if isinstance(prop_value, rdltypes.PropertyReference): prop_value._resolve_node(self) return prop_value if ovr_default: # Default value is being overridden by user. Return their value return default # Otherwise, return its default value based on the property's rules rule = self.env.property_rules.lookup_property(prop_name) # Is it even a valid property or allowed for this component type? if rule is None: raise LookupError("Unknown property '%s'" % prop_name) if type(self.inst) not in rule.bindable_to: raise LookupError("Unknown property '%s'" % prop_name) # Return the default value as specified by the rulebook return rule.get_default(self)
[ "def", "get_property", "(", "self", ",", "prop_name", ",", "*", "*", "kwargs", ")", ":", "ovr_default", "=", "False", "default", "=", "None", "if", "'default'", "in", "kwargs", ":", "ovr_default", "=", "True", "default", "=", "kwargs", ".", "pop", "(", ...
Gets the SystemRDL component property If a property was not explicitly set in the RDL source, its default value is derived. In some cases, a default value is implied according to other property values. Properties values that are a reference to a component instance are converted to a :class:`~Node` overlay object. Parameters ---------- prop_name: str SystemRDL property name default: Override built-in default value of property. If the property was not explicitly set, return this value rather than the property's intrinsic default value. Raises ------ LookupError If prop_name is invalid
[ "Gets", "the", "SystemRDL", "component", "property" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L281-L343
train
23,344
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.list_properties
def list_properties(self, list_all=False): """ Lists properties associated with this node. By default, only lists properties that were explicitly set. If ``list_all`` is set to ``True`` then lists all valid properties of this component type Parameters ---------- list_all: bool If true, lists all valid properties of this component type. """ if list_all: props = [] for k,v in self.env.property_rules.rdl_properties.items(): if type(self.inst) in v.bindable_to: props.append(k) for k,v in self.env.property_rules.user_properties.items(): if type(self.inst) in v.bindable_to: props.append(k) return props else: return list(self.inst.properties.keys())
python
def list_properties(self, list_all=False): """ Lists properties associated with this node. By default, only lists properties that were explicitly set. If ``list_all`` is set to ``True`` then lists all valid properties of this component type Parameters ---------- list_all: bool If true, lists all valid properties of this component type. """ if list_all: props = [] for k,v in self.env.property_rules.rdl_properties.items(): if type(self.inst) in v.bindable_to: props.append(k) for k,v in self.env.property_rules.user_properties.items(): if type(self.inst) in v.bindable_to: props.append(k) return props else: return list(self.inst.properties.keys())
[ "def", "list_properties", "(", "self", ",", "list_all", "=", "False", ")", ":", "if", "list_all", ":", "props", "=", "[", "]", "for", "k", ",", "v", "in", "self", ".", "env", ".", "property_rules", ".", "rdl_properties", ".", "items", "(", ")", ":", ...
Lists properties associated with this node. By default, only lists properties that were explicitly set. If ``list_all`` is set to ``True`` then lists all valid properties of this component type Parameters ---------- list_all: bool If true, lists all valid properties of this component type.
[ "Lists", "properties", "associated", "with", "this", "node", ".", "By", "default", "only", "lists", "properties", "that", "were", "explicitly", "set", ".", "If", "list_all", "is", "set", "to", "True", "then", "lists", "all", "valid", "properties", "of", "thi...
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L346-L368
train
23,345
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.get_path
def get_path(self, hier_separator=".", array_suffix="[{index:d}]", empty_array_suffix="[]"): """ Generate an absolute path string to this node Parameters ---------- hier_separator: str Override the hierarchy separator array_suffix: str Override how array suffixes are represented when the index is known empty_array_suffix: str Override how array suffixes are represented when the index is not known """ if self.parent and not isinstance(self.parent, RootNode): return( self.parent.get_path(hier_separator, array_suffix, empty_array_suffix) + hier_separator + self.get_path_segment(array_suffix, empty_array_suffix) ) else: return self.get_path_segment(array_suffix, empty_array_suffix)
python
def get_path(self, hier_separator=".", array_suffix="[{index:d}]", empty_array_suffix="[]"): """ Generate an absolute path string to this node Parameters ---------- hier_separator: str Override the hierarchy separator array_suffix: str Override how array suffixes are represented when the index is known empty_array_suffix: str Override how array suffixes are represented when the index is not known """ if self.parent and not isinstance(self.parent, RootNode): return( self.parent.get_path(hier_separator, array_suffix, empty_array_suffix) + hier_separator + self.get_path_segment(array_suffix, empty_array_suffix) ) else: return self.get_path_segment(array_suffix, empty_array_suffix)
[ "def", "get_path", "(", "self", ",", "hier_separator", "=", "\".\"", ",", "array_suffix", "=", "\"[{index:d}]\"", ",", "empty_array_suffix", "=", "\"[]\"", ")", ":", "if", "self", ".", "parent", "and", "not", "isinstance", "(", "self", ".", "parent", ",", ...
Generate an absolute path string to this node Parameters ---------- hier_separator: str Override the hierarchy separator array_suffix: str Override how array suffixes are represented when the index is known empty_array_suffix: str Override how array suffixes are represented when the index is not known
[ "Generate", "an", "absolute", "path", "string", "to", "this", "node" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L387-L407
train
23,346
SystemRDL/systemrdl-compiler
systemrdl/node.py
Node.get_html_desc
def get_html_desc(self, markdown_inst=None): """ Translates the node's 'desc' property into HTML. Any RDLFormatCode tags used in the description are converted to HTML. The text is also fed through a Markdown processor. The additional Markdown processing allows designers the choice to use a more modern lightweight markup language as an alternative to SystemRDL's "RDLFormatCode". Parameters ---------- markdown_inst: ``markdown.Markdown`` Override the class instance of the Markdown processor. See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_ for more details. Returns ------- str or None HTML formatted string. If node does not have a description, returns ``None`` """ desc_str = self.get_property("desc") if desc_str is None: return None return rdlformatcode.rdlfc_to_html(desc_str, self, md=markdown_inst)
python
def get_html_desc(self, markdown_inst=None): """ Translates the node's 'desc' property into HTML. Any RDLFormatCode tags used in the description are converted to HTML. The text is also fed through a Markdown processor. The additional Markdown processing allows designers the choice to use a more modern lightweight markup language as an alternative to SystemRDL's "RDLFormatCode". Parameters ---------- markdown_inst: ``markdown.Markdown`` Override the class instance of the Markdown processor. See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_ for more details. Returns ------- str or None HTML formatted string. If node does not have a description, returns ``None`` """ desc_str = self.get_property("desc") if desc_str is None: return None return rdlformatcode.rdlfc_to_html(desc_str, self, md=markdown_inst)
[ "def", "get_html_desc", "(", "self", ",", "markdown_inst", "=", "None", ")", ":", "desc_str", "=", "self", ".", "get_property", "(", "\"desc\"", ")", "if", "desc_str", "is", "None", ":", "return", "None", "return", "rdlformatcode", ".", "rdlfc_to_html", "(",...
Translates the node's 'desc' property into HTML. Any RDLFormatCode tags used in the description are converted to HTML. The text is also fed through a Markdown processor. The additional Markdown processing allows designers the choice to use a more modern lightweight markup language as an alternative to SystemRDL's "RDLFormatCode". Parameters ---------- markdown_inst: ``markdown.Markdown`` Override the class instance of the Markdown processor. See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_ for more details. Returns ------- str or None HTML formatted string. If node does not have a description, returns ``None``
[ "Translates", "the", "node", "s", "desc", "property", "into", "HTML", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L409-L437
train
23,347
SystemRDL/systemrdl-compiler
systemrdl/node.py
AddressableNode.address_offset
def address_offset(self): """ Byte address offset of this node relative to it's parent If this node is an array, it's index must be known Raises ------ ValueError If this property is referenced on a node whose array index is not fully defined """ if self.inst.is_array: if self.current_idx is None: raise ValueError("Index of array element must be known to derive address") # Calculate the "flattened" index of a general multidimensional array # For example, a component array declared as: # foo[S0][S1][S2] # and referenced as: # foo[I0][I1][I2] # Is flattened like this: # idx = I0*S1*S2 + I1*S2 + I2 idx = 0 for i in range(len(self.current_idx)): sz = 1 for j in range(i+1, len(self.inst.array_dimensions)): sz *= self.inst.array_dimensions[j] idx += sz * self.current_idx[i] offset = self.inst.addr_offset + idx * self.inst.array_stride else: offset = self.inst.addr_offset return offset
python
def address_offset(self): """ Byte address offset of this node relative to it's parent If this node is an array, it's index must be known Raises ------ ValueError If this property is referenced on a node whose array index is not fully defined """ if self.inst.is_array: if self.current_idx is None: raise ValueError("Index of array element must be known to derive address") # Calculate the "flattened" index of a general multidimensional array # For example, a component array declared as: # foo[S0][S1][S2] # and referenced as: # foo[I0][I1][I2] # Is flattened like this: # idx = I0*S1*S2 + I1*S2 + I2 idx = 0 for i in range(len(self.current_idx)): sz = 1 for j in range(i+1, len(self.inst.array_dimensions)): sz *= self.inst.array_dimensions[j] idx += sz * self.current_idx[i] offset = self.inst.addr_offset + idx * self.inst.array_stride else: offset = self.inst.addr_offset return offset
[ "def", "address_offset", "(", "self", ")", ":", "if", "self", ".", "inst", ".", "is_array", ":", "if", "self", ".", "current_idx", "is", "None", ":", "raise", "ValueError", "(", "\"Index of array element must be known to derive address\"", ")", "# Calculate the \"fl...
Byte address offset of this node relative to it's parent If this node is an array, it's index must be known Raises ------ ValueError If this property is referenced on a node whose array index is not fully defined
[ "Byte", "address", "offset", "of", "this", "node", "relative", "to", "it", "s", "parent" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L496-L531
train
23,348
SystemRDL/systemrdl-compiler
systemrdl/node.py
AddressableNode.absolute_address
def absolute_address(self): """ Get the absolute byte address of this node. Indexes of all arrays in the node's lineage must be known Raises ------ ValueError If this property is referenced on a node whose array lineage is not fully defined """ if self.parent and not isinstance(self.parent, RootNode): return self.parent.absolute_address + self.address_offset else: return self.address_offset
python
def absolute_address(self): """ Get the absolute byte address of this node. Indexes of all arrays in the node's lineage must be known Raises ------ ValueError If this property is referenced on a node whose array lineage is not fully defined """ if self.parent and not isinstance(self.parent, RootNode): return self.parent.absolute_address + self.address_offset else: return self.address_offset
[ "def", "absolute_address", "(", "self", ")", ":", "if", "self", ".", "parent", "and", "not", "isinstance", "(", "self", ".", "parent", ",", "RootNode", ")", ":", "return", "self", ".", "parent", ".", "absolute_address", "+", "self", ".", "address_offset", ...
Get the absolute byte address of this node. Indexes of all arrays in the node's lineage must be known Raises ------ ValueError If this property is referenced on a node whose array lineage is not fully defined
[ "Get", "the", "absolute", "byte", "address", "of", "this", "node", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L535-L551
train
23,349
SystemRDL/systemrdl-compiler
systemrdl/node.py
RootNode.top
def top(self): """ Returns the top-level addrmap node """ for child in self.children(skip_not_present=False): if not isinstance(child, AddrmapNode): continue return child raise RuntimeError
python
def top(self): """ Returns the top-level addrmap node """ for child in self.children(skip_not_present=False): if not isinstance(child, AddrmapNode): continue return child raise RuntimeError
[ "def", "top", "(", "self", ")", ":", "for", "child", "in", "self", ".", "children", "(", "skip_not_present", "=", "False", ")", ":", "if", "not", "isinstance", "(", "child", ",", "AddrmapNode", ")", ":", "continue", "return", "child", "raise", "RuntimeEr...
Returns the top-level addrmap node
[ "Returns", "the", "top", "-", "level", "addrmap", "node" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L653-L661
train
23,350
SystemRDL/systemrdl-compiler
systemrdl/node.py
FieldNode.is_sw_writable
def is_sw_writable(self): """ Field is writable by software """ sw = self.get_property('sw') return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1, rdltypes.AccessType.w, rdltypes.AccessType.w1)
python
def is_sw_writable(self): """ Field is writable by software """ sw = self.get_property('sw') return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1, rdltypes.AccessType.w, rdltypes.AccessType.w1)
[ "def", "is_sw_writable", "(", "self", ")", ":", "sw", "=", "self", ".", "get_property", "(", "'sw'", ")", "return", "sw", "in", "(", "rdltypes", ".", "AccessType", ".", "rw", ",", "rdltypes", ".", "AccessType", ".", "rw1", ",", "rdltypes", ".", "Access...
Field is writable by software
[ "Field", "is", "writable", "by", "software" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L696-L703
train
23,351
SystemRDL/systemrdl-compiler
systemrdl/node.py
FieldNode.is_sw_readable
def is_sw_readable(self): """ Field is readable by software """ sw = self.get_property('sw') return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1, rdltypes.AccessType.r)
python
def is_sw_readable(self): """ Field is readable by software """ sw = self.get_property('sw') return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1, rdltypes.AccessType.r)
[ "def", "is_sw_readable", "(", "self", ")", ":", "sw", "=", "self", ".", "get_property", "(", "'sw'", ")", "return", "sw", "in", "(", "rdltypes", ".", "AccessType", ".", "rw", ",", "rdltypes", ".", "AccessType", ".", "rw1", ",", "rdltypes", ".", "Access...
Field is readable by software
[ "Field", "is", "readable", "by", "software" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L706-L713
train
23,352
SystemRDL/systemrdl-compiler
systemrdl/node.py
FieldNode.implements_storage
def implements_storage(self): """ True if combination of field access properties imply that the field implements a storage element. """ # 9.4.1, Table 12 sw = self.get_property('sw') hw = self.get_property('hw') if sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1): # Software can read and write, implying a storage element return True if hw == rdltypes.AccessType.rw: # Hardware can read and write, implying a storage element return True if (sw in (rdltypes.AccessType.w, rdltypes.AccessType.w1)) and (hw == rdltypes.AccessType.r): # Write-only register visible to hardware is stored return True onread = self.get_property('onread') if onread is not None: # 9.6.1-c: Onread side-effects imply storage regardless of whether # or not the field is writable by sw return True if self.get_property('hwset') or self.get_property('hwclr'): # Not in spec, but these imply that a storage element exists return True return False
python
def implements_storage(self): """ True if combination of field access properties imply that the field implements a storage element. """ # 9.4.1, Table 12 sw = self.get_property('sw') hw = self.get_property('hw') if sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1): # Software can read and write, implying a storage element return True if hw == rdltypes.AccessType.rw: # Hardware can read and write, implying a storage element return True if (sw in (rdltypes.AccessType.w, rdltypes.AccessType.w1)) and (hw == rdltypes.AccessType.r): # Write-only register visible to hardware is stored return True onread = self.get_property('onread') if onread is not None: # 9.6.1-c: Onread side-effects imply storage regardless of whether # or not the field is writable by sw return True if self.get_property('hwset') or self.get_property('hwclr'): # Not in spec, but these imply that a storage element exists return True return False
[ "def", "implements_storage", "(", "self", ")", ":", "# 9.4.1, Table 12", "sw", "=", "self", ".", "get_property", "(", "'sw'", ")", "hw", "=", "self", ".", "get_property", "(", "'hw'", ")", "if", "sw", "in", "(", "rdltypes", ".", "AccessType", ".", "rw", ...
True if combination of field access properties imply that the field implements a storage element.
[ "True", "if", "combination", "of", "field", "access", "properties", "imply", "that", "the", "field", "implements", "a", "storage", "element", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L716-L747
train
23,353
SystemRDL/systemrdl-compiler
systemrdl/core/ComponentVisitor.py
ComponentVisitor.visitComponent_def
def visitComponent_def(self, ctx:SystemRDLParser.Component_defContext): """ Create, and possibly instantiate a component """ # Get definition. Returns Component if ctx.component_anon_def() is not None: comp_def = self.visit(ctx.component_anon_def()) elif ctx.component_named_def() is not None: comp_def = self.visit(ctx.component_named_def()) else: raise RuntimeError comp_def.parent_scope = self.component if ctx.component_insts() is not None: if isinstance(self, RootVisitor) and isinstance(comp_def, comp.Addrmap): self.msg.warning( "Non-standard instantiation of an addrmap in root namespace will be ignored", SourceRef.from_antlr(ctx.component_insts().component_inst(0).ID()) ) else: # Component is instantiated one or more times if ctx.component_inst_type() is not None: inst_type = self.visit(ctx.component_inst_type()) else: inst_type = None # Pass some temporary info to visitComponent_insts self._tmp = (comp_def, inst_type, None) self.visit(ctx.component_insts()) return None
python
def visitComponent_def(self, ctx:SystemRDLParser.Component_defContext): """ Create, and possibly instantiate a component """ # Get definition. Returns Component if ctx.component_anon_def() is not None: comp_def = self.visit(ctx.component_anon_def()) elif ctx.component_named_def() is not None: comp_def = self.visit(ctx.component_named_def()) else: raise RuntimeError comp_def.parent_scope = self.component if ctx.component_insts() is not None: if isinstance(self, RootVisitor) and isinstance(comp_def, comp.Addrmap): self.msg.warning( "Non-standard instantiation of an addrmap in root namespace will be ignored", SourceRef.from_antlr(ctx.component_insts().component_inst(0).ID()) ) else: # Component is instantiated one or more times if ctx.component_inst_type() is not None: inst_type = self.visit(ctx.component_inst_type()) else: inst_type = None # Pass some temporary info to visitComponent_insts self._tmp = (comp_def, inst_type, None) self.visit(ctx.component_insts()) return None
[ "def", "visitComponent_def", "(", "self", ",", "ctx", ":", "SystemRDLParser", ".", "Component_defContext", ")", ":", "# Get definition. Returns Component", "if", "ctx", ".", "component_anon_def", "(", ")", "is", "not", "None", ":", "comp_def", "=", "self", ".", ...
Create, and possibly instantiate a component
[ "Create", "and", "possibly", "instantiate", "a", "component" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L76-L108
train
23,354
SystemRDL/systemrdl-compiler
systemrdl/core/ComponentVisitor.py
ComponentVisitor.define_component
def define_component(self, body, type_token, def_name, param_defs): """ Given component definition, recurse to another ComponentVisitor to define a new component """ for subclass in ComponentVisitor.__subclasses__(): if subclass.comp_type == self._CompType_Map[type_token.type]: visitor = subclass(self.compiler, def_name, param_defs) return visitor.visit(body) raise RuntimeError
python
def define_component(self, body, type_token, def_name, param_defs): """ Given component definition, recurse to another ComponentVisitor to define a new component """ for subclass in ComponentVisitor.__subclasses__(): if subclass.comp_type == self._CompType_Map[type_token.type]: visitor = subclass(self.compiler, def_name, param_defs) return visitor.visit(body) raise RuntimeError
[ "def", "define_component", "(", "self", ",", "body", ",", "type_token", ",", "def_name", ",", "param_defs", ")", ":", "for", "subclass", "in", "ComponentVisitor", ".", "__subclasses__", "(", ")", ":", "if", "subclass", ".", "comp_type", "==", "self", ".", ...
Given component definition, recurse to another ComponentVisitor to define a new component
[ "Given", "component", "definition", "recurse", "to", "another", "ComponentVisitor", "to", "define", "a", "new", "component" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L153-L162
train
23,355
SystemRDL/systemrdl-compiler
systemrdl/core/ComponentVisitor.py
ComponentVisitor.get_instance_assignment
def get_instance_assignment(self, ctx): """ Gets the integer expression in any of the four instance assignment operators ('=' '@' '+=' '%=') """ if ctx is None: return None visitor = ExprVisitor(self.compiler) expr = visitor.visit(ctx.expr()) expr = expressions.AssignmentCast(self.compiler.env, SourceRef.from_antlr(ctx.op), expr, int) expr.predict_type() return expr
python
def get_instance_assignment(self, ctx): """ Gets the integer expression in any of the four instance assignment operators ('=' '@' '+=' '%=') """ if ctx is None: return None visitor = ExprVisitor(self.compiler) expr = visitor.visit(ctx.expr()) expr = expressions.AssignmentCast(self.compiler.env, SourceRef.from_antlr(ctx.op), expr, int) expr.predict_type() return expr
[ "def", "get_instance_assignment", "(", "self", ",", "ctx", ")", ":", "if", "ctx", "is", "None", ":", "return", "None", "visitor", "=", "ExprVisitor", "(", "self", ".", "compiler", ")", "expr", "=", "visitor", ".", "visit", "(", "ctx", ".", "expr", "(",...
Gets the integer expression in any of the four instance assignment operators ('=' '@' '+=' '%=')
[ "Gets", "the", "integer", "expression", "in", "any", "of", "the", "four", "instance", "assignment", "operators", "(", "=" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L311-L323
train
23,356
SystemRDL/systemrdl-compiler
systemrdl/core/ComponentVisitor.py
ComponentVisitor.visitParam_def
def visitParam_def(self, ctx:SystemRDLParser.Param_defContext): """ Parameter Definition block """ self.compiler.namespace.enter_scope() param_defs = [] for elem in ctx.getTypedRuleContexts(SystemRDLParser.Param_def_elemContext): param_def = self.visit(elem) param_defs.append(param_def) self.compiler.namespace.exit_scope() return param_defs
python
def visitParam_def(self, ctx:SystemRDLParser.Param_defContext): """ Parameter Definition block """ self.compiler.namespace.enter_scope() param_defs = [] for elem in ctx.getTypedRuleContexts(SystemRDLParser.Param_def_elemContext): param_def = self.visit(elem) param_defs.append(param_def) self.compiler.namespace.exit_scope() return param_defs
[ "def", "visitParam_def", "(", "self", ",", "ctx", ":", "SystemRDLParser", ".", "Param_defContext", ")", ":", "self", ".", "compiler", ".", "namespace", ".", "enter_scope", "(", ")", "param_defs", "=", "[", "]", "for", "elem", "in", "ctx", ".", "getTypedRul...
Parameter Definition block
[ "Parameter", "Definition", "block" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L471-L483
train
23,357
SystemRDL/systemrdl-compiler
systemrdl/core/ComponentVisitor.py
ComponentVisitor.visitParam_def_elem
def visitParam_def_elem(self, ctx:SystemRDLParser.Param_def_elemContext): """ Individual parameter definition elements """ # Construct parameter type data_type_token = self.visit(ctx.data_type()) param_data_type = self.datatype_from_token(data_type_token) if ctx.array_type_suffix() is None: # Non-array type param_type = param_data_type else: # Array-like type param_type = rdltypes.ArrayPlaceholder(param_data_type) # Get parameter name param_name = get_ID_text(ctx.ID()) # Get expression for parameter default, if any if ctx.expr() is not None: visitor = ExprVisitor(self.compiler) default_expr = visitor.visit(ctx.expr()) default_expr = expressions.AssignmentCast(self.compiler.env, SourceRef.from_antlr(ctx.ID()), default_expr, param_type) default_expr.predict_type() else: default_expr = None # Create Parameter object param = Parameter(param_type, param_name, default_expr) # Register it in the parameter def namespace scope self.compiler.namespace.register_element(param_name, param, None, SourceRef.from_antlr(ctx.ID())) return param
python
def visitParam_def_elem(self, ctx:SystemRDLParser.Param_def_elemContext): """ Individual parameter definition elements """ # Construct parameter type data_type_token = self.visit(ctx.data_type()) param_data_type = self.datatype_from_token(data_type_token) if ctx.array_type_suffix() is None: # Non-array type param_type = param_data_type else: # Array-like type param_type = rdltypes.ArrayPlaceholder(param_data_type) # Get parameter name param_name = get_ID_text(ctx.ID()) # Get expression for parameter default, if any if ctx.expr() is not None: visitor = ExprVisitor(self.compiler) default_expr = visitor.visit(ctx.expr()) default_expr = expressions.AssignmentCast(self.compiler.env, SourceRef.from_antlr(ctx.ID()), default_expr, param_type) default_expr.predict_type() else: default_expr = None # Create Parameter object param = Parameter(param_type, param_name, default_expr) # Register it in the parameter def namespace scope self.compiler.namespace.register_element(param_name, param, None, SourceRef.from_antlr(ctx.ID())) return param
[ "def", "visitParam_def_elem", "(", "self", ",", "ctx", ":", "SystemRDLParser", ".", "Param_def_elemContext", ")", ":", "# Construct parameter type", "data_type_token", "=", "self", ".", "visit", "(", "ctx", ".", "data_type", "(", ")", ")", "param_data_type", "=", ...
Individual parameter definition elements
[ "Individual", "parameter", "definition", "elements" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L485-L518
train
23,358
SystemRDL/systemrdl-compiler
systemrdl/core/BaseVisitor.py
BaseVisitor.datatype_from_token
def datatype_from_token(self, token): """ Given a SystemRDLParser token, lookup the type This only includes types under the "data_type" grammar rule """ if token.type == SystemRDLParser.ID: # Is an identifier for either an enum or struct type typ = self.compiler.namespace.lookup_type(get_ID_text(token)) if typ is None: self.msg.fatal( "Type '%s' is not defined" % get_ID_text(token), SourceRef.from_antlr(token) ) if rdltypes.is_user_enum(typ) or rdltypes.is_user_struct(typ): return typ else: self.msg.fatal( "Type '%s' is not a struct or enum" % get_ID_text(token), SourceRef.from_antlr(token) ) else: return self._DataType_Map[token.type]
python
def datatype_from_token(self, token): """ Given a SystemRDLParser token, lookup the type This only includes types under the "data_type" grammar rule """ if token.type == SystemRDLParser.ID: # Is an identifier for either an enum or struct type typ = self.compiler.namespace.lookup_type(get_ID_text(token)) if typ is None: self.msg.fatal( "Type '%s' is not defined" % get_ID_text(token), SourceRef.from_antlr(token) ) if rdltypes.is_user_enum(typ) or rdltypes.is_user_struct(typ): return typ else: self.msg.fatal( "Type '%s' is not a struct or enum" % get_ID_text(token), SourceRef.from_antlr(token) ) else: return self._DataType_Map[token.type]
[ "def", "datatype_from_token", "(", "self", ",", "token", ")", ":", "if", "token", ".", "type", "==", "SystemRDLParser", ".", "ID", ":", "# Is an identifier for either an enum or struct type", "typ", "=", "self", ".", "compiler", ".", "namespace", ".", "lookup_type...
Given a SystemRDLParser token, lookup the type This only includes types under the "data_type" grammar rule
[ "Given", "a", "SystemRDLParser", "token", "lookup", "the", "type", "This", "only", "includes", "types", "under", "the", "data_type", "grammar", "rule" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/BaseVisitor.py#L29-L54
train
23,359
SystemRDL/systemrdl-compiler
systemrdl/rdltypes.py
get_rdltype
def get_rdltype(value): """ Given a value, return the type identifier object used within the RDL compiler If not a supported type, return None """ if isinstance(value, (int, bool, str)): # Pass canonical types as-is return type(value) elif is_user_enum(type(value)): return type(value) elif is_user_struct(type(value)): return type(value) elif isinstance(value, enum.Enum): return type(value) elif isinstance(value, list): # Create ArrayPlaceholder representation # Determine element type and make sure it is uniform array_el_type = None for el in value: el_type = get_rdltype(el) if el_type is None: return None if (array_el_type is not None) and (el_type != array_el_type): return None array_el_type = el_type return ArrayPlaceholder(array_el_type) else: return None
python
def get_rdltype(value): """ Given a value, return the type identifier object used within the RDL compiler If not a supported type, return None """ if isinstance(value, (int, bool, str)): # Pass canonical types as-is return type(value) elif is_user_enum(type(value)): return type(value) elif is_user_struct(type(value)): return type(value) elif isinstance(value, enum.Enum): return type(value) elif isinstance(value, list): # Create ArrayPlaceholder representation # Determine element type and make sure it is uniform array_el_type = None for el in value: el_type = get_rdltype(el) if el_type is None: return None if (array_el_type is not None) and (el_type != array_el_type): return None array_el_type = el_type return ArrayPlaceholder(array_el_type) else: return None
[ "def", "get_rdltype", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "int", ",", "bool", ",", "str", ")", ")", ":", "# Pass canonical types as-is", "return", "type", "(", "value", ")", "elif", "is_user_enum", "(", "type", "(", "value...
Given a value, return the type identifier object used within the RDL compiler If not a supported type, return None
[ "Given", "a", "value", "return", "the", "type", "identifier", "object", "used", "within", "the", "RDL", "compiler", "If", "not", "a", "supported", "type", "return", "None" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L507-L536
train
23,360
SystemRDL/systemrdl-compiler
systemrdl/rdltypes.py
UserEnum.get_html_desc
def get_html_desc(self, markdown_inst=None): """ Translates the enum's 'desc' property into HTML. Any RDLFormatCode tags used in the description are converted to HTML. The text is also fed through a Markdown processor. The additional Markdown processing allows designers the choice to use a more modern lightweight markup language as an alternative to SystemRDL's "RDLFormatCode". Parameters ---------- markdown_inst: ``markdown.Markdown`` Override the class instance of the Markdown processor. See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_ for more details. Returns ------- str or None HTML formatted string. If node does not have a description, returns ``None`` """ desc_str = self._rdl_desc_ if desc_str is None: return None return rdlformatcode.rdlfc_to_html(desc_str, md=markdown_inst)
python
def get_html_desc(self, markdown_inst=None): """ Translates the enum's 'desc' property into HTML. Any RDLFormatCode tags used in the description are converted to HTML. The text is also fed through a Markdown processor. The additional Markdown processing allows designers the choice to use a more modern lightweight markup language as an alternative to SystemRDL's "RDLFormatCode". Parameters ---------- markdown_inst: ``markdown.Markdown`` Override the class instance of the Markdown processor. See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_ for more details. Returns ------- str or None HTML formatted string. If node does not have a description, returns ``None`` """ desc_str = self._rdl_desc_ if desc_str is None: return None return rdlformatcode.rdlfc_to_html(desc_str, md=markdown_inst)
[ "def", "get_html_desc", "(", "self", ",", "markdown_inst", "=", "None", ")", ":", "desc_str", "=", "self", ".", "_rdl_desc_", "if", "desc_str", "is", "None", ":", "return", "None", "return", "rdlformatcode", ".", "rdlfc_to_html", "(", "desc_str", ",", "md", ...
Translates the enum's 'desc' property into HTML. Any RDLFormatCode tags used in the description are converted to HTML. The text is also fed through a Markdown processor. The additional Markdown processing allows designers the choice to use a more modern lightweight markup language as an alternative to SystemRDL's "RDLFormatCode". Parameters ---------- markdown_inst: ``markdown.Markdown`` Override the class instance of the Markdown processor. See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_ for more details. Returns ------- str or None HTML formatted string. If node does not have a description, returns ``None``
[ "Translates", "the", "enum", "s", "desc", "property", "into", "HTML", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L147-L174
train
23,361
SystemRDL/systemrdl-compiler
systemrdl/rdltypes.py
UserEnum.get_scope_path
def get_scope_path(cls, scope_separator="::"): """ Generate a string that represents this enum's declaration namespace scope. Parameters ---------- scope_separator: str Override the separator between namespace scopes """ if cls.get_parent_scope() is None: return "" elif isinstance(cls.get_parent_scope(), comp.Root): return "" else: parent_path = cls.get_parent_scope().get_scope_path(scope_separator) if parent_path: return( parent_path + scope_separator + cls.get_parent_scope().type_name ) else: return cls.get_parent_scope().type_name
python
def get_scope_path(cls, scope_separator="::"): """ Generate a string that represents this enum's declaration namespace scope. Parameters ---------- scope_separator: str Override the separator between namespace scopes """ if cls.get_parent_scope() is None: return "" elif isinstance(cls.get_parent_scope(), comp.Root): return "" else: parent_path = cls.get_parent_scope().get_scope_path(scope_separator) if parent_path: return( parent_path + scope_separator + cls.get_parent_scope().type_name ) else: return cls.get_parent_scope().type_name
[ "def", "get_scope_path", "(", "cls", ",", "scope_separator", "=", "\"::\"", ")", ":", "if", "cls", ".", "get_parent_scope", "(", ")", "is", "None", ":", "return", "\"\"", "elif", "isinstance", "(", "cls", ".", "get_parent_scope", "(", ")", ",", "comp", "...
Generate a string that represents this enum's declaration namespace scope. Parameters ---------- scope_separator: str Override the separator between namespace scopes
[ "Generate", "a", "string", "that", "represents", "this", "enum", "s", "declaration", "namespace", "scope", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L188-L211
train
23,362
SystemRDL/systemrdl-compiler
systemrdl/rdltypes.py
UserStruct.define_new
def define_new(cls, name, members, is_abstract=False): """ Define a new struct type derived from the current type. Parameters ---------- name: str Name of the struct type members: {member_name : type} Dictionary of struct member types. is_abstract: bool If set, marks the struct as abstract. """ m = OrderedDict(cls._members) # Make sure derivation does not have any overlapping keys with its parent if set(m.keys()) & set(members.keys()): raise ValueError("'members' contains keys that overlap with parent") m.update(members) dct = { '_members' : m, '_is_abstract': is_abstract, } newcls = type(name, (cls,), dct) return newcls
python
def define_new(cls, name, members, is_abstract=False): """ Define a new struct type derived from the current type. Parameters ---------- name: str Name of the struct type members: {member_name : type} Dictionary of struct member types. is_abstract: bool If set, marks the struct as abstract. """ m = OrderedDict(cls._members) # Make sure derivation does not have any overlapping keys with its parent if set(m.keys()) & set(members.keys()): raise ValueError("'members' contains keys that overlap with parent") m.update(members) dct = { '_members' : m, '_is_abstract': is_abstract, } newcls = type(name, (cls,), dct) return newcls
[ "def", "define_new", "(", "cls", ",", "name", ",", "members", ",", "is_abstract", "=", "False", ")", ":", "m", "=", "OrderedDict", "(", "cls", ".", "_members", ")", "# Make sure derivation does not have any overlapping keys with its parent", "if", "set", "(", "m",...
Define a new struct type derived from the current type. Parameters ---------- name: str Name of the struct type members: {member_name : type} Dictionary of struct member types. is_abstract: bool If set, marks the struct as abstract.
[ "Define", "a", "new", "struct", "type", "derived", "from", "the", "current", "type", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L288-L314
train
23,363
SystemRDL/systemrdl-compiler
systemrdl/compiler.py
RDLCompiler.define_udp
def define_udp(self, name, valid_type, valid_components=None, default=None): """ Pre-define a user-defined property. This is the equivalent to the following RDL: .. code-block:: none property <name> { type = <valid_type>; component = <valid_components>; default = <default> }; Parameters ---------- name: str Property name valid_components: list List of :class:`~systemrdl.component.Component` types the UDP can be bound to. If None, then UDP can be bound to all components. valid_type: type Assignment type that this UDP will enforce default: Default if a value is not specified when the UDP is bound to a component. Value must be compatible with ``valid_type`` """ if valid_components is None: valid_components = [ comp.Field, comp.Reg, comp.Regfile, comp.Addrmap, comp.Mem, comp.Signal, #TODO constraint, ] if name in self.env.property_rules.rdl_properties: raise ValueError("name '%s' conflicts with existing built-in RDL property") udp = UserProperty(self.env, name, valid_components, [valid_type], default) self.env.property_rules.user_properties[udp.name] = udp
python
def define_udp(self, name, valid_type, valid_components=None, default=None): """ Pre-define a user-defined property. This is the equivalent to the following RDL: .. code-block:: none property <name> { type = <valid_type>; component = <valid_components>; default = <default> }; Parameters ---------- name: str Property name valid_components: list List of :class:`~systemrdl.component.Component` types the UDP can be bound to. If None, then UDP can be bound to all components. valid_type: type Assignment type that this UDP will enforce default: Default if a value is not specified when the UDP is bound to a component. Value must be compatible with ``valid_type`` """ if valid_components is None: valid_components = [ comp.Field, comp.Reg, comp.Regfile, comp.Addrmap, comp.Mem, comp.Signal, #TODO constraint, ] if name in self.env.property_rules.rdl_properties: raise ValueError("name '%s' conflicts with existing built-in RDL property") udp = UserProperty(self.env, name, valid_components, [valid_type], default) self.env.property_rules.user_properties[udp.name] = udp
[ "def", "define_udp", "(", "self", ",", "name", ",", "valid_type", ",", "valid_components", "=", "None", ",", "default", "=", "None", ")", ":", "if", "valid_components", "is", "None", ":", "valid_components", "=", "[", "comp", ".", "Field", ",", "comp", "...
Pre-define a user-defined property. This is the equivalent to the following RDL: .. code-block:: none property <name> { type = <valid_type>; component = <valid_components>; default = <default> }; Parameters ---------- name: str Property name valid_components: list List of :class:`~systemrdl.component.Component` types the UDP can be bound to. If None, then UDP can be bound to all components. valid_type: type Assignment type that this UDP will enforce default: Default if a value is not specified when the UDP is bound to a component. Value must be compatible with ``valid_type``
[ "Pre", "-", "define", "a", "user", "-", "defined", "property", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/compiler.py#L47-L91
train
23,364
SystemRDL/systemrdl-compiler
systemrdl/compiler.py
RDLCompiler.compile_file
def compile_file(self, path, incl_search_paths=None): """ Parse & compile a single file and append it to RDLCompiler's root namespace. If any exceptions (:class:`~systemrdl.RDLCompileError` or other) occur during compilation, then the RDLCompiler object should be discarded. Parameters ---------- path:str Path to an RDL source file incl_search_paths:list List of additional paths to search to resolve includes. If unset, defaults to an empty list. Relative include paths are resolved in the following order: 1. Search each path specified in ``incl_search_paths``. 2. Path relative to the source file performing the include. Raises ------ :class:`~systemrdl.RDLCompileError` If any fatal compile error is encountered. """ if incl_search_paths is None: incl_search_paths = [] fpp = preprocessor.FilePreprocessor(self.env, path, incl_search_paths) preprocessed_text, seg_map = fpp.preprocess() input_stream = preprocessor.PreprocessedInputStream(preprocessed_text, seg_map) lexer = SystemRDLLexer(input_stream) lexer.removeErrorListeners() lexer.addErrorListener(messages.RDLAntlrErrorListener(self.msg)) token_stream = CommonTokenStream(lexer) parser = SystemRDLParser(token_stream) parser.removeErrorListeners() parser.addErrorListener(messages.RDLAntlrErrorListener(self.msg)) # Run Antlr parser on input parsed_tree = parser.root() if self.msg.had_error: self.msg.fatal("Parse aborted due to previous errors") # Traverse parse tree with RootVisitor self.visitor.visit(parsed_tree) # Reset default property assignments from namespace. # They should not be shared between files since that would be confusing. self.namespace.default_property_ns_stack = [{}] if self.msg.had_error: self.msg.fatal("Compile aborted due to previous errors")
python
def compile_file(self, path, incl_search_paths=None): """ Parse & compile a single file and append it to RDLCompiler's root namespace. If any exceptions (:class:`~systemrdl.RDLCompileError` or other) occur during compilation, then the RDLCompiler object should be discarded. Parameters ---------- path:str Path to an RDL source file incl_search_paths:list List of additional paths to search to resolve includes. If unset, defaults to an empty list. Relative include paths are resolved in the following order: 1. Search each path specified in ``incl_search_paths``. 2. Path relative to the source file performing the include. Raises ------ :class:`~systemrdl.RDLCompileError` If any fatal compile error is encountered. """ if incl_search_paths is None: incl_search_paths = [] fpp = preprocessor.FilePreprocessor(self.env, path, incl_search_paths) preprocessed_text, seg_map = fpp.preprocess() input_stream = preprocessor.PreprocessedInputStream(preprocessed_text, seg_map) lexer = SystemRDLLexer(input_stream) lexer.removeErrorListeners() lexer.addErrorListener(messages.RDLAntlrErrorListener(self.msg)) token_stream = CommonTokenStream(lexer) parser = SystemRDLParser(token_stream) parser.removeErrorListeners() parser.addErrorListener(messages.RDLAntlrErrorListener(self.msg)) # Run Antlr parser on input parsed_tree = parser.root() if self.msg.had_error: self.msg.fatal("Parse aborted due to previous errors") # Traverse parse tree with RootVisitor self.visitor.visit(parsed_tree) # Reset default property assignments from namespace. # They should not be shared between files since that would be confusing. self.namespace.default_property_ns_stack = [{}] if self.msg.had_error: self.msg.fatal("Compile aborted due to previous errors")
[ "def", "compile_file", "(", "self", ",", "path", ",", "incl_search_paths", "=", "None", ")", ":", "if", "incl_search_paths", "is", "None", ":", "incl_search_paths", "=", "[", "]", "fpp", "=", "preprocessor", ".", "FilePreprocessor", "(", "self", ".", "env", ...
Parse & compile a single file and append it to RDLCompiler's root namespace. If any exceptions (:class:`~systemrdl.RDLCompileError` or other) occur during compilation, then the RDLCompiler object should be discarded. Parameters ---------- path:str Path to an RDL source file incl_search_paths:list List of additional paths to search to resolve includes. If unset, defaults to an empty list. Relative include paths are resolved in the following order: 1. Search each path specified in ``incl_search_paths``. 2. Path relative to the source file performing the include. Raises ------ :class:`~systemrdl.RDLCompileError` If any fatal compile error is encountered.
[ "Parse", "&", "compile", "a", "single", "file", "and", "append", "it", "to", "RDLCompiler", "s", "root", "namespace", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/compiler.py#L94-L152
train
23,365
SystemRDL/systemrdl-compiler
systemrdl/compiler.py
RDLCompiler.elaborate
def elaborate(self, top_def_name=None, inst_name=None, parameters=None): """ Elaborates the design for the given top-level addrmap component. During elaboration, the following occurs: - An instance of the ``$root`` meta-component is created. - The addrmap component specified by ``top_def_name`` is instantiated as a child of ``$root``. - Expressions, parameters, and inferred address/field placements are elaborated. - Validation checks are performed. If a design contains multiple root-level addrmaps, ``elaborate()`` can be called multiple times in order to elaborate each individually. If any exceptions (:class:`~systemrdl.RDLCompileError` or other) occur during elaboration, then the RDLCompiler object should be discarded. Parameters ---------- top_def_name: str Explicitly choose which addrmap in the root namespace will be the top-level component. If unset, The last addrmap defined will be chosen. inst_name: str Overrides the top-component's instantiated name. By default, instantiated name is the same as ``top_def_name`` parameters: dict Dictionary of parameter overrides for the top component instance. Raises ------ :class:`~systemrdl.RDLCompileError` If any fatal elaboration error is encountered Returns ------- :class:`~systemrdl.node.RootNode` Elaborated root meta-component's Node object. """ if parameters is None: parameters = {} # Get top-level component definition to elaborate if top_def_name is not None: # Lookup top_def_name if top_def_name not in self.root.comp_defs: self.msg.fatal("Elaboration target '%s' not found" % top_def_name) top_def = self.root.comp_defs[top_def_name] if not isinstance(top_def, comp.Addrmap): self.msg.fatal("Elaboration target '%s' is not an 'addrmap' component" % top_def_name) else: # Not specified. Find the last addrmap defined for comp_def in reversed(list(self.root.comp_defs.values())): if isinstance(comp_def, comp.Addrmap): top_def = comp_def top_def_name = comp_def.type_name break else: self.msg.fatal("Could not find any 'addrmap' components to elaborate") # Create an instance of the root component root_inst = deepcopy(self.root) root_inst.is_instance = True root_inst.original_def = self.root root_inst.inst_name = "$root" # Create a top-level instance top_inst = deepcopy(top_def) top_inst.is_instance = True top_inst.original_def = top_def top_inst.addr_offset = 0 top_inst.external = True # addrmap is always implied as external if inst_name is not None: top_inst.inst_name = inst_name else: top_inst.inst_name = top_def_name # Override parameters as needed for param_name, value in parameters.items(): # Find the parameter to override parameter = None for p in top_inst.parameters: if p.name == param_name: parameter = p break else: raise ValueError("Parameter '%s' is not available for override" % param_name) value_expr = expr.ExternalLiteral(self.env, value) value_type = value_expr.predict_type() if value_type is None: raise TypeError("Override value for parameter '%s' is an unrecognized type" % param_name) if value_type != parameter.param_type: raise TypeError("Incorrect type for parameter '%s'" % param_name) parameter.expr = value_expr # instantiate top_inst into the root component instance root_inst.children.append(top_inst) root_node = RootNode(root_inst, self.env, None) # Resolve all expressions walker.RDLWalker(skip_not_present=False).walk( root_node, ElabExpressionsListener(self.msg) ) # Resolve address and field placement walker.RDLWalker(skip_not_present=False).walk( root_node, PrePlacementValidateListener(self.msg), StructuralPlacementListener(self.msg), LateElabListener(self.msg) ) # Validate design # Only need to validate nodes that are present walker.RDLWalker(skip_not_present=True).walk(root_node, ValidateListener(self.env)) if self.msg.had_error: self.msg.fatal("Elaborate aborted due to previous errors") return root_node
python
def elaborate(self, top_def_name=None, inst_name=None, parameters=None): """ Elaborates the design for the given top-level addrmap component. During elaboration, the following occurs: - An instance of the ``$root`` meta-component is created. - The addrmap component specified by ``top_def_name`` is instantiated as a child of ``$root``. - Expressions, parameters, and inferred address/field placements are elaborated. - Validation checks are performed. If a design contains multiple root-level addrmaps, ``elaborate()`` can be called multiple times in order to elaborate each individually. If any exceptions (:class:`~systemrdl.RDLCompileError` or other) occur during elaboration, then the RDLCompiler object should be discarded. Parameters ---------- top_def_name: str Explicitly choose which addrmap in the root namespace will be the top-level component. If unset, The last addrmap defined will be chosen. inst_name: str Overrides the top-component's instantiated name. By default, instantiated name is the same as ``top_def_name`` parameters: dict Dictionary of parameter overrides for the top component instance. Raises ------ :class:`~systemrdl.RDLCompileError` If any fatal elaboration error is encountered Returns ------- :class:`~systemrdl.node.RootNode` Elaborated root meta-component's Node object. """ if parameters is None: parameters = {} # Get top-level component definition to elaborate if top_def_name is not None: # Lookup top_def_name if top_def_name not in self.root.comp_defs: self.msg.fatal("Elaboration target '%s' not found" % top_def_name) top_def = self.root.comp_defs[top_def_name] if not isinstance(top_def, comp.Addrmap): self.msg.fatal("Elaboration target '%s' is not an 'addrmap' component" % top_def_name) else: # Not specified. Find the last addrmap defined for comp_def in reversed(list(self.root.comp_defs.values())): if isinstance(comp_def, comp.Addrmap): top_def = comp_def top_def_name = comp_def.type_name break else: self.msg.fatal("Could not find any 'addrmap' components to elaborate") # Create an instance of the root component root_inst = deepcopy(self.root) root_inst.is_instance = True root_inst.original_def = self.root root_inst.inst_name = "$root" # Create a top-level instance top_inst = deepcopy(top_def) top_inst.is_instance = True top_inst.original_def = top_def top_inst.addr_offset = 0 top_inst.external = True # addrmap is always implied as external if inst_name is not None: top_inst.inst_name = inst_name else: top_inst.inst_name = top_def_name # Override parameters as needed for param_name, value in parameters.items(): # Find the parameter to override parameter = None for p in top_inst.parameters: if p.name == param_name: parameter = p break else: raise ValueError("Parameter '%s' is not available for override" % param_name) value_expr = expr.ExternalLiteral(self.env, value) value_type = value_expr.predict_type() if value_type is None: raise TypeError("Override value for parameter '%s' is an unrecognized type" % param_name) if value_type != parameter.param_type: raise TypeError("Incorrect type for parameter '%s'" % param_name) parameter.expr = value_expr # instantiate top_inst into the root component instance root_inst.children.append(top_inst) root_node = RootNode(root_inst, self.env, None) # Resolve all expressions walker.RDLWalker(skip_not_present=False).walk( root_node, ElabExpressionsListener(self.msg) ) # Resolve address and field placement walker.RDLWalker(skip_not_present=False).walk( root_node, PrePlacementValidateListener(self.msg), StructuralPlacementListener(self.msg), LateElabListener(self.msg) ) # Validate design # Only need to validate nodes that are present walker.RDLWalker(skip_not_present=True).walk(root_node, ValidateListener(self.env)) if self.msg.had_error: self.msg.fatal("Elaborate aborted due to previous errors") return root_node
[ "def", "elaborate", "(", "self", ",", "top_def_name", "=", "None", ",", "inst_name", "=", "None", ",", "parameters", "=", "None", ")", ":", "if", "parameters", "is", "None", ":", "parameters", "=", "{", "}", "# Get top-level component definition to elaborate", ...
Elaborates the design for the given top-level addrmap component. During elaboration, the following occurs: - An instance of the ``$root`` meta-component is created. - The addrmap component specified by ``top_def_name`` is instantiated as a child of ``$root``. - Expressions, parameters, and inferred address/field placements are elaborated. - Validation checks are performed. If a design contains multiple root-level addrmaps, ``elaborate()`` can be called multiple times in order to elaborate each individually. If any exceptions (:class:`~systemrdl.RDLCompileError` or other) occur during elaboration, then the RDLCompiler object should be discarded. Parameters ---------- top_def_name: str Explicitly choose which addrmap in the root namespace will be the top-level component. If unset, The last addrmap defined will be chosen. inst_name: str Overrides the top-component's instantiated name. By default, instantiated name is the same as ``top_def_name`` parameters: dict Dictionary of parameter overrides for the top component instance. Raises ------ :class:`~systemrdl.RDLCompileError` If any fatal elaboration error is encountered Returns ------- :class:`~systemrdl.node.RootNode` Elaborated root meta-component's Node object.
[ "Elaborates", "the", "design", "for", "the", "given", "top", "-", "level", "addrmap", "component", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/compiler.py#L154-L285
train
23,366
SystemRDL/systemrdl-compiler
systemrdl/core/properties.py
PropertyRuleBoolPair.get_default
def get_default(self, node): """ If not explicitly set, check if the opposite was set first before returning default """ if self.opposite_property in node.inst.properties: return not node.inst.properties[self.opposite_property] else: return self.default
python
def get_default(self, node): """ If not explicitly set, check if the opposite was set first before returning default """ if self.opposite_property in node.inst.properties: return not node.inst.properties[self.opposite_property] else: return self.default
[ "def", "get_default", "(", "self", ",", "node", ")", ":", "if", "self", ".", "opposite_property", "in", "node", ".", "inst", ".", "properties", ":", "return", "not", "node", ".", "inst", ".", "properties", "[", "self", ".", "opposite_property", "]", "els...
If not explicitly set, check if the opposite was set first before returning default
[ "If", "not", "explicitly", "set", "check", "if", "the", "opposite", "was", "set", "first", "before", "returning", "default" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L165-L173
train
23,367
SystemRDL/systemrdl-compiler
systemrdl/core/properties.py
Prop_rset.get_default
def get_default(self, node): """ If not explicitly set, check if onread sets the equivalent """ if node.inst.properties.get("onread", None) == rdltypes.OnReadType.rset: return True else: return self.default
python
def get_default(self, node): """ If not explicitly set, check if onread sets the equivalent """ if node.inst.properties.get("onread", None) == rdltypes.OnReadType.rset: return True else: return self.default
[ "def", "get_default", "(", "self", ",", "node", ")", ":", "if", "node", ".", "inst", ".", "properties", ".", "get", "(", "\"onread\"", ",", "None", ")", "==", "rdltypes", ".", "OnReadType", ".", "rset", ":", "return", "True", "else", ":", "return", "...
If not explicitly set, check if onread sets the equivalent
[ "If", "not", "explicitly", "set", "check", "if", "onread", "sets", "the", "equivalent" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L622-L629
train
23,368
SystemRDL/systemrdl-compiler
systemrdl/core/properties.py
Prop_onread.assign_value
def assign_value(self, comp_def, value, src_ref): """ Overrides other related properties """ super().assign_value(comp_def, value, src_ref) if "rclr" in comp_def.properties: del comp_def.properties["rclr"] if "rset" in comp_def.properties: del comp_def.properties["rset"]
python
def assign_value(self, comp_def, value, src_ref): """ Overrides other related properties """ super().assign_value(comp_def, value, src_ref) if "rclr" in comp_def.properties: del comp_def.properties["rclr"] if "rset" in comp_def.properties: del comp_def.properties["rset"]
[ "def", "assign_value", "(", "self", ",", "comp_def", ",", "value", ",", "src_ref", ")", ":", "super", "(", ")", ".", "assign_value", "(", "comp_def", ",", "value", ",", "src_ref", ")", "if", "\"rclr\"", "in", "comp_def", ".", "properties", ":", "del", ...
Overrides other related properties
[ "Overrides", "other", "related", "properties" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L642-L650
train
23,369
SystemRDL/systemrdl-compiler
systemrdl/core/properties.py
Prop_onread.get_default
def get_default(self, node): """ If not explicitly set, check if rset or rclr imply the value """ if node.inst.properties.get("rset", False): return rdltypes.OnReadType.rset elif node.inst.properties.get("rclr", False): return rdltypes.OnReadType.rclr else: return self.default
python
def get_default(self, node): """ If not explicitly set, check if rset or rclr imply the value """ if node.inst.properties.get("rset", False): return rdltypes.OnReadType.rset elif node.inst.properties.get("rclr", False): return rdltypes.OnReadType.rclr else: return self.default
[ "def", "get_default", "(", "self", ",", "node", ")", ":", "if", "node", ".", "inst", ".", "properties", ".", "get", "(", "\"rset\"", ",", "False", ")", ":", "return", "rdltypes", ".", "OnReadType", ".", "rset", "elif", "node", ".", "inst", ".", "prop...
If not explicitly set, check if rset or rclr imply the value
[ "If", "not", "explicitly", "set", "check", "if", "rset", "or", "rclr", "imply", "the", "value" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L652-L661
train
23,370
SystemRDL/systemrdl-compiler
systemrdl/core/properties.py
Prop_woclr.get_default
def get_default(self, node): """ If not explicitly set, check if onwrite sets the equivalent """ if node.inst.properties.get("onwrite", None) == rdltypes.OnWriteType.woclr: return True else: return self.default
python
def get_default(self, node): """ If not explicitly set, check if onwrite sets the equivalent """ if node.inst.properties.get("onwrite", None) == rdltypes.OnWriteType.woclr: return True else: return self.default
[ "def", "get_default", "(", "self", ",", "node", ")", ":", "if", "node", ".", "inst", ".", "properties", ".", "get", "(", "\"onwrite\"", ",", "None", ")", "==", "rdltypes", ".", "OnWriteType", ".", "woclr", ":", "return", "True", "else", ":", "return", ...
If not explicitly set, check if onwrite sets the equivalent
[ "If", "not", "explicitly", "set", "check", "if", "onwrite", "sets", "the", "equivalent" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L702-L709
train
23,371
SystemRDL/systemrdl-compiler
systemrdl/core/properties.py
Prop_onwrite.get_default
def get_default(self, node): """ If not explicitly set, check if woset or woclr imply the value """ if node.inst.properties.get("woset", False): return rdltypes.OnWriteType.woset elif node.inst.properties.get("woclr", False): return rdltypes.OnWriteType.woclr else: return self.default
python
def get_default(self, node): """ If not explicitly set, check if woset or woclr imply the value """ if node.inst.properties.get("woset", False): return rdltypes.OnWriteType.woset elif node.inst.properties.get("woclr", False): return rdltypes.OnWriteType.woclr else: return self.default
[ "def", "get_default", "(", "self", ",", "node", ")", ":", "if", "node", ".", "inst", ".", "properties", ".", "get", "(", "\"woset\"", ",", "False", ")", ":", "return", "rdltypes", ".", "OnWriteType", ".", "woset", "elif", "node", ".", "inst", ".", "p...
If not explicitly set, check if woset or woclr imply the value
[ "If", "not", "explicitly", "set", "check", "if", "woset", "or", "woclr", "imply", "the", "value" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L762-L771
train
23,372
SystemRDL/systemrdl-compiler
systemrdl/core/properties.py
Prop_threshold.assign_value
def assign_value(self, comp_def, value, src_ref): """ Set both alias and actual value """ super().assign_value(comp_def, value, src_ref) comp_def.properties['incrthreshold'] = value
python
def assign_value(self, comp_def, value, src_ref): """ Set both alias and actual value """ super().assign_value(comp_def, value, src_ref) comp_def.properties['incrthreshold'] = value
[ "def", "assign_value", "(", "self", ",", "comp_def", ",", "value", ",", "src_ref", ")", ":", "super", "(", ")", ".", "assign_value", "(", "comp_def", ",", "value", ",", "src_ref", ")", "comp_def", ".", "properties", "[", "'incrthreshold'", "]", "=", "val...
Set both alias and actual value
[ "Set", "both", "alias", "and", "actual", "value" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L1008-L1013
train
23,373
SystemRDL/systemrdl-compiler
systemrdl/core/properties.py
Prop_stickybit.get_default
def get_default(self, node): """ Unless specified otherwise, intr fields are implicitly stickybit """ if node.inst.properties.get("intr", False): # Interrupt is set! # Default is implicitly stickybit, unless the mutually-exclusive # sticky property was set instead return not node.inst.properties.get("sticky", False) else: return False
python
def get_default(self, node): """ Unless specified otherwise, intr fields are implicitly stickybit """ if node.inst.properties.get("intr", False): # Interrupt is set! # Default is implicitly stickybit, unless the mutually-exclusive # sticky property was set instead return not node.inst.properties.get("sticky", False) else: return False
[ "def", "get_default", "(", "self", ",", "node", ")", ":", "if", "node", ".", "inst", ".", "properties", ".", "get", "(", "\"intr\"", ",", "False", ")", ":", "# Interrupt is set!", "# Default is implicitly stickybit, unless the mutually-exclusive", "# sticky property w...
Unless specified otherwise, intr fields are implicitly stickybit
[ "Unless", "specified", "otherwise", "intr", "fields", "are", "implicitly", "stickybit" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L1198-L1208
train
23,374
SystemRDL/systemrdl-compiler
systemrdl/core/elaborate.py
StructuralPlacementListener.resolve_addresses
def resolve_addresses(self, node): """ Resolve addresses of children of Addrmap and Regfile components """ # Get alignment based on 'alignment' property # This remains constant for all children prop_alignment = self.alignment_stack[-1] if prop_alignment is None: # was not specified. Does not contribute to alignment prop_alignment = 1 prev_node = None for child_node in node.children(skip_not_present=False): if not isinstance(child_node, AddressableNode): continue if child_node.inst.addr_offset is not None: # Address is already known. Do not need to infer prev_node = child_node continue if node.env.chk_implicit_addr: node.env.msg.message( node.env.chk_implicit_addr, "Address offset of component '%s' is not explicitly set" % child_node.inst.inst_name, child_node.inst.inst_src_ref ) # Get alignment specified by '%=' allocator, if any alloc_alignment = child_node.inst.addr_align if alloc_alignment is None: # was not specified. Does not contribute to alignment alloc_alignment = 1 # Calculate alignment based on current addressing mode if self.addressing_mode_stack[-1] == rdltypes.AddressingType.compact: if isinstance(child_node, RegNode): # Regs are aligned based on their accesswidth mode_alignment = child_node.get_property('accesswidth') // 8 else: # Spec does not specify for other components # Assuming absolutely compact packing mode_alignment = 1 elif self.addressing_mode_stack[-1] == rdltypes.AddressingType.regalign: # Components are aligned to a multiple of their size # Spec vaguely suggests that alignment is also a power of 2 mode_alignment = child_node.size mode_alignment = roundup_pow2(mode_alignment) elif self.addressing_mode_stack[-1] == rdltypes.AddressingType.fullalign: # Same as regalign except for arrays # Arrays are aligned to their total size # Both are rounded to power of 2 mode_alignment = child_node.total_size mode_alignment = roundup_pow2(mode_alignment) else: raise RuntimeError # Calculate resulting address offset alignment = max(prop_alignment, alloc_alignment, mode_alignment) if prev_node is None: next_offset = 0 else: next_offset = prev_node.inst.addr_offset + prev_node.total_size # round next_offset up to alignment child_node.inst.addr_offset = roundup_to(next_offset, alignment) prev_node = child_node # Sort children by address offset # Non-addressable child components are sorted to be first (signals) def get_child_sort_key(inst): if not isinstance(inst, comp.AddressableComponent): return -1 else: return inst.addr_offset node.inst.children.sort(key=get_child_sort_key)
python
def resolve_addresses(self, node): """ Resolve addresses of children of Addrmap and Regfile components """ # Get alignment based on 'alignment' property # This remains constant for all children prop_alignment = self.alignment_stack[-1] if prop_alignment is None: # was not specified. Does not contribute to alignment prop_alignment = 1 prev_node = None for child_node in node.children(skip_not_present=False): if not isinstance(child_node, AddressableNode): continue if child_node.inst.addr_offset is not None: # Address is already known. Do not need to infer prev_node = child_node continue if node.env.chk_implicit_addr: node.env.msg.message( node.env.chk_implicit_addr, "Address offset of component '%s' is not explicitly set" % child_node.inst.inst_name, child_node.inst.inst_src_ref ) # Get alignment specified by '%=' allocator, if any alloc_alignment = child_node.inst.addr_align if alloc_alignment is None: # was not specified. Does not contribute to alignment alloc_alignment = 1 # Calculate alignment based on current addressing mode if self.addressing_mode_stack[-1] == rdltypes.AddressingType.compact: if isinstance(child_node, RegNode): # Regs are aligned based on their accesswidth mode_alignment = child_node.get_property('accesswidth') // 8 else: # Spec does not specify for other components # Assuming absolutely compact packing mode_alignment = 1 elif self.addressing_mode_stack[-1] == rdltypes.AddressingType.regalign: # Components are aligned to a multiple of their size # Spec vaguely suggests that alignment is also a power of 2 mode_alignment = child_node.size mode_alignment = roundup_pow2(mode_alignment) elif self.addressing_mode_stack[-1] == rdltypes.AddressingType.fullalign: # Same as regalign except for arrays # Arrays are aligned to their total size # Both are rounded to power of 2 mode_alignment = child_node.total_size mode_alignment = roundup_pow2(mode_alignment) else: raise RuntimeError # Calculate resulting address offset alignment = max(prop_alignment, alloc_alignment, mode_alignment) if prev_node is None: next_offset = 0 else: next_offset = prev_node.inst.addr_offset + prev_node.total_size # round next_offset up to alignment child_node.inst.addr_offset = roundup_to(next_offset, alignment) prev_node = child_node # Sort children by address offset # Non-addressable child components are sorted to be first (signals) def get_child_sort_key(inst): if not isinstance(inst, comp.AddressableComponent): return -1 else: return inst.addr_offset node.inst.children.sort(key=get_child_sort_key)
[ "def", "resolve_addresses", "(", "self", ",", "node", ")", ":", "# Get alignment based on 'alignment' property", "# This remains constant for all children", "prop_alignment", "=", "self", ".", "alignment_stack", "[", "-", "1", "]", "if", "prop_alignment", "is", "None", ...
Resolve addresses of children of Addrmap and Regfile components
[ "Resolve", "addresses", "of", "children", "of", "Addrmap", "and", "Regfile", "components" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/elaborate.py#L408-L488
train
23,375
SystemRDL/systemrdl-compiler
systemrdl/core/helpers.py
get_ID_text
def get_ID_text(token): """ Get the text from the ID token. Strips off leading slash escape if present """ if isinstance(token, CommonToken): text = token.text else: text = token.getText() text = text.lstrip('\\') return text
python
def get_ID_text(token): """ Get the text from the ID token. Strips off leading slash escape if present """ if isinstance(token, CommonToken): text = token.text else: text = token.getText() text = text.lstrip('\\') return text
[ "def", "get_ID_text", "(", "token", ")", ":", "if", "isinstance", "(", "token", ",", "CommonToken", ")", ":", "text", "=", "token", ".", "text", "else", ":", "text", "=", "token", ".", "getText", "(", ")", "text", "=", "text", ".", "lstrip", "(", "...
Get the text from the ID token. Strips off leading slash escape if present
[ "Get", "the", "text", "from", "the", "ID", "token", ".", "Strips", "off", "leading", "slash", "escape", "if", "present" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/helpers.py#L16-L27
train
23,376
SystemRDL/systemrdl-compiler
systemrdl/preprocessor/segment_map.py
SegmentMap.derive_source_offset
def derive_source_offset(self, offset, is_end=False): """ Given a post-preprocessed coordinate, derives the corresponding coordinate in the original source file. Returns result in the following tuple: (src_offset, src_path, include_ref) where: - src_offset is the translated coordinate If the input offset lands on a macro expansion, then src_offset returns the start or end coordinate according to is_end - src_path points to the original source file - include_ref describes any `include lineage using a IncludeRef object Is none if file was not referenced via include """ for segment in self.segments: if offset <= segment.end: if isinstance(segment, MacroSegment): if is_end: return ( segment.src_end, segment.src, segment.incl_ref ) else: return ( segment.src_start, segment.src, segment.incl_ref ) else: return ( segment.src_start + (offset - segment.start), segment.src, segment.incl_ref ) # Reached end. Assume end of last segment return ( self.segments[-1].src_end, self.segments[-1].src, self.segments[-1].incl_ref )
python
def derive_source_offset(self, offset, is_end=False): """ Given a post-preprocessed coordinate, derives the corresponding coordinate in the original source file. Returns result in the following tuple: (src_offset, src_path, include_ref) where: - src_offset is the translated coordinate If the input offset lands on a macro expansion, then src_offset returns the start or end coordinate according to is_end - src_path points to the original source file - include_ref describes any `include lineage using a IncludeRef object Is none if file was not referenced via include """ for segment in self.segments: if offset <= segment.end: if isinstance(segment, MacroSegment): if is_end: return ( segment.src_end, segment.src, segment.incl_ref ) else: return ( segment.src_start, segment.src, segment.incl_ref ) else: return ( segment.src_start + (offset - segment.start), segment.src, segment.incl_ref ) # Reached end. Assume end of last segment return ( self.segments[-1].src_end, self.segments[-1].src, self.segments[-1].incl_ref )
[ "def", "derive_source_offset", "(", "self", ",", "offset", ",", "is_end", "=", "False", ")", ":", "for", "segment", "in", "self", ".", "segments", ":", "if", "offset", "<=", "segment", ".", "end", ":", "if", "isinstance", "(", "segment", ",", "MacroSegme...
Given a post-preprocessed coordinate, derives the corresponding coordinate in the original source file. Returns result in the following tuple: (src_offset, src_path, include_ref) where: - src_offset is the translated coordinate If the input offset lands on a macro expansion, then src_offset returns the start or end coordinate according to is_end - src_path points to the original source file - include_ref describes any `include lineage using a IncludeRef object Is none if file was not referenced via include
[ "Given", "a", "post", "-", "preprocessed", "coordinate", "derives", "the", "corresponding", "coordinate", "in", "the", "original", "source", "file", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/segment_map.py#L8-L50
train
23,377
SystemRDL/systemrdl-compiler
systemrdl/preprocessor/preprocessor.py
FilePreprocessor.preprocess
def preprocess(self): """ Run preprocessor on a top-level file. Performs the following preprocess steps: - Expand `include directives - Perl Preprocessor Returns ------- tuple (preprocessed_text, SegmentMap) """ tokens = self.tokenize() pl_segments, has_perl_tags = self.get_perl_segments(tokens) # Generate flattened output str_parts = [] smap = segment_map.SegmentMap() offset = 0 if has_perl_tags: # Needs to be processed through perl interpreter emit_list = self.run_perl_miniscript(pl_segments) for entry in emit_list: if entry['type'] == "ref": pl_seg = pl_segments[entry['ref']] emit_text = pl_seg.get_text() map_seg = segment_map.UnalteredSegment( offset, offset + len(emit_text) - 1, pl_seg.start, pl_seg.end, pl_seg.file_pp.path, pl_seg.file_pp.incl_ref ) offset += len(emit_text) smap.segments.append(map_seg) str_parts.append(emit_text) elif entry['type'] == "text": pl_seg = pl_segments[entry['ref']] emit_text = entry['text'] map_seg = segment_map.MacroSegment( offset, offset + len(emit_text) - 1, pl_seg.start, pl_seg.end, pl_seg.file_pp.path, pl_seg.file_pp.incl_ref ) offset += len(emit_text) smap.segments.append(map_seg) str_parts.append(emit_text) else: # OK to bypass perl interpreter for pl_seg in pl_segments: emit_text = pl_seg.get_text() map_seg = segment_map.UnalteredSegment( offset, offset + len(emit_text) - 1, pl_seg.start, pl_seg.end, pl_seg.file_pp.path, pl_seg.file_pp.incl_ref ) offset += len(emit_text) smap.segments.append(map_seg) str_parts.append(emit_text) #segment_map.print_segment_debug("".join(str_parts), smap) return ("".join(str_parts), smap)
python
def preprocess(self): """ Run preprocessor on a top-level file. Performs the following preprocess steps: - Expand `include directives - Perl Preprocessor Returns ------- tuple (preprocessed_text, SegmentMap) """ tokens = self.tokenize() pl_segments, has_perl_tags = self.get_perl_segments(tokens) # Generate flattened output str_parts = [] smap = segment_map.SegmentMap() offset = 0 if has_perl_tags: # Needs to be processed through perl interpreter emit_list = self.run_perl_miniscript(pl_segments) for entry in emit_list: if entry['type'] == "ref": pl_seg = pl_segments[entry['ref']] emit_text = pl_seg.get_text() map_seg = segment_map.UnalteredSegment( offset, offset + len(emit_text) - 1, pl_seg.start, pl_seg.end, pl_seg.file_pp.path, pl_seg.file_pp.incl_ref ) offset += len(emit_text) smap.segments.append(map_seg) str_parts.append(emit_text) elif entry['type'] == "text": pl_seg = pl_segments[entry['ref']] emit_text = entry['text'] map_seg = segment_map.MacroSegment( offset, offset + len(emit_text) - 1, pl_seg.start, pl_seg.end, pl_seg.file_pp.path, pl_seg.file_pp.incl_ref ) offset += len(emit_text) smap.segments.append(map_seg) str_parts.append(emit_text) else: # OK to bypass perl interpreter for pl_seg in pl_segments: emit_text = pl_seg.get_text() map_seg = segment_map.UnalteredSegment( offset, offset + len(emit_text) - 1, pl_seg.start, pl_seg.end, pl_seg.file_pp.path, pl_seg.file_pp.incl_ref ) offset += len(emit_text) smap.segments.append(map_seg) str_parts.append(emit_text) #segment_map.print_segment_debug("".join(str_parts), smap) return ("".join(str_parts), smap)
[ "def", "preprocess", "(", "self", ")", ":", "tokens", "=", "self", ".", "tokenize", "(", ")", "pl_segments", ",", "has_perl_tags", "=", "self", ".", "get_perl_segments", "(", "tokens", ")", "# Generate flattened output", "str_parts", "=", "[", "]", "smap", "...
Run preprocessor on a top-level file. Performs the following preprocess steps: - Expand `include directives - Perl Preprocessor Returns ------- tuple (preprocessed_text, SegmentMap)
[ "Run", "preprocessor", "on", "a", "top", "-", "level", "file", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/preprocessor.py#L26-L93
train
23,378
SystemRDL/systemrdl-compiler
systemrdl/preprocessor/preprocessor.py
FilePreprocessor.tokenize
def tokenize(self): """ Tokenize the input text Scans for instances of perl tags and include directives. Tokenization skips line and block comments. Returns ------- list List of tuples: (typ, start, end) Where: - typ is "perl" or "incl" - start/end mark the first/last char offset of the token """ tokens = [] token_spec = [ ('mlc', r'/\*.*?\*/'), ('slc', r'//[^\r\n]*?\r?\n'), ('perl', r'<%.*?%>'), ('incl', r'`include'), ] tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_spec) for m in re.finditer(tok_regex, self.text, re.DOTALL): if m.lastgroup in ("incl", "perl"): tokens.append((m.lastgroup, m.start(0), m.end(0)-1)) return tokens
python
def tokenize(self): """ Tokenize the input text Scans for instances of perl tags and include directives. Tokenization skips line and block comments. Returns ------- list List of tuples: (typ, start, end) Where: - typ is "perl" or "incl" - start/end mark the first/last char offset of the token """ tokens = [] token_spec = [ ('mlc', r'/\*.*?\*/'), ('slc', r'//[^\r\n]*?\r?\n'), ('perl', r'<%.*?%>'), ('incl', r'`include'), ] tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_spec) for m in re.finditer(tok_regex, self.text, re.DOTALL): if m.lastgroup in ("incl", "perl"): tokens.append((m.lastgroup, m.start(0), m.end(0)-1)) return tokens
[ "def", "tokenize", "(", "self", ")", ":", "tokens", "=", "[", "]", "token_spec", "=", "[", "(", "'mlc'", ",", "r'/\\*.*?\\*/'", ")", ",", "(", "'slc'", ",", "r'//[^\\r\\n]*?\\r?\\n'", ")", ",", "(", "'perl'", ",", "r'<%.*?%>'", ")", ",", "(", "'incl'",...
Tokenize the input text Scans for instances of perl tags and include directives. Tokenization skips line and block comments. Returns ------- list List of tuples: (typ, start, end) Where: - typ is "perl" or "incl" - start/end mark the first/last char offset of the token
[ "Tokenize", "the", "input", "text" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/preprocessor.py#L96-L124
train
23,379
SystemRDL/systemrdl-compiler
systemrdl/preprocessor/preprocessor.py
FilePreprocessor.parse_include
def parse_include(self, start): """ Extract include from text based on start position of token Returns ------- (end, incl_path) - end: last char in include - incl_path: Resolved path to include """ # Seek back to start of line i = start while i: if self.text[i] == '\n': i += 1 break i -= 1 line_start = i # check that there is no unexpected text before the include if not (self.text[line_start:start] == "" or self.text[line_start:start].isspace()): self.env.msg.fatal( "Unexpected text before include", messages.SourceRef(line_start, start-1, filename=self.path) ) # Capture include contents inc_regex = re.compile(r'`include\s+("([^\r\n]+)"|<([^\r\n]+)>)') m_inc = inc_regex.match(self.text, start) if m_inc is None: self.env.msg.fatal( "Invalid usage of include directive", messages.SourceRef(start, start+7, filename=self.path) ) incl_path_raw = m_inc.group(2) or m_inc.group(3) end = m_inc.end(0)-1 path_start = m_inc.start(1) #[^\r\n]*?\r?\n # Check that only comments follow tail_regex = re.compile(r'(?:[ \t]*/\*[^\r\n]*?\*/)*[ \t]*(?://[^\r\n]*?|/\*[^\r\n]*?)?\r?\n') if not tail_regex.match(self.text, end+1): tail_capture_regex = re.compile(r'[^\r\n]*?\r?\n') m = tail_capture_regex.match(self.text, end+1) self.env.msg.fatal( "Unexpected text after include", messages.SourceRef(end+1, m.end(0)-1, filename=self.path) ) # Resolve include path. if os.path.isabs(incl_path_raw): incl_path = incl_path_raw else: # Search include paths first. for search_path in self.search_paths: incl_path = os.path.join(search_path, incl_path_raw) if os.path.isfile(incl_path): # found match! break else: # Otherwise, assume it is relative to the current file incl_path = os.path.join(os.path.dirname(self.path), incl_path_raw) if not os.path.isfile(incl_path): self.env.msg.fatal( "Could not find '%s' in include search paths" % incl_path_raw, messages.SourceRef(path_start, end, filename=self.path) ) # Check if path has already been referenced before incl_ref = self.incl_ref while incl_ref: if os.path.samefile(incl_path, incl_ref.path): self.env.msg.fatal( "Include of '%s' results in a circular reference" % incl_path_raw, messages.SourceRef(path_start, end, filename=self.path) ) incl_ref = incl_ref.parent return(end, incl_path)
python
def parse_include(self, start): """ Extract include from text based on start position of token Returns ------- (end, incl_path) - end: last char in include - incl_path: Resolved path to include """ # Seek back to start of line i = start while i: if self.text[i] == '\n': i += 1 break i -= 1 line_start = i # check that there is no unexpected text before the include if not (self.text[line_start:start] == "" or self.text[line_start:start].isspace()): self.env.msg.fatal( "Unexpected text before include", messages.SourceRef(line_start, start-1, filename=self.path) ) # Capture include contents inc_regex = re.compile(r'`include\s+("([^\r\n]+)"|<([^\r\n]+)>)') m_inc = inc_regex.match(self.text, start) if m_inc is None: self.env.msg.fatal( "Invalid usage of include directive", messages.SourceRef(start, start+7, filename=self.path) ) incl_path_raw = m_inc.group(2) or m_inc.group(3) end = m_inc.end(0)-1 path_start = m_inc.start(1) #[^\r\n]*?\r?\n # Check that only comments follow tail_regex = re.compile(r'(?:[ \t]*/\*[^\r\n]*?\*/)*[ \t]*(?://[^\r\n]*?|/\*[^\r\n]*?)?\r?\n') if not tail_regex.match(self.text, end+1): tail_capture_regex = re.compile(r'[^\r\n]*?\r?\n') m = tail_capture_regex.match(self.text, end+1) self.env.msg.fatal( "Unexpected text after include", messages.SourceRef(end+1, m.end(0)-1, filename=self.path) ) # Resolve include path. if os.path.isabs(incl_path_raw): incl_path = incl_path_raw else: # Search include paths first. for search_path in self.search_paths: incl_path = os.path.join(search_path, incl_path_raw) if os.path.isfile(incl_path): # found match! break else: # Otherwise, assume it is relative to the current file incl_path = os.path.join(os.path.dirname(self.path), incl_path_raw) if not os.path.isfile(incl_path): self.env.msg.fatal( "Could not find '%s' in include search paths" % incl_path_raw, messages.SourceRef(path_start, end, filename=self.path) ) # Check if path has already been referenced before incl_ref = self.incl_ref while incl_ref: if os.path.samefile(incl_path, incl_ref.path): self.env.msg.fatal( "Include of '%s' results in a circular reference" % incl_path_raw, messages.SourceRef(path_start, end, filename=self.path) ) incl_ref = incl_ref.parent return(end, incl_path)
[ "def", "parse_include", "(", "self", ",", "start", ")", ":", "# Seek back to start of line", "i", "=", "start", "while", "i", ":", "if", "self", ".", "text", "[", "i", "]", "==", "'\\n'", ":", "i", "+=", "1", "break", "i", "-=", "1", "line_start", "=...
Extract include from text based on start position of token Returns ------- (end, incl_path) - end: last char in include - incl_path: Resolved path to include
[ "Extract", "include", "from", "text", "based", "on", "start", "position", "of", "token" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/preprocessor.py#L127-L204
train
23,380
SystemRDL/systemrdl-compiler
systemrdl/preprocessor/preprocessor.py
FilePreprocessor.run_perl_miniscript
def run_perl_miniscript(self, segments): """ Generates and runs a perl miniscript that derives the text that will be emitted from the preprocessor returns the resulting emit list """ # Check if perl is installed if shutil.which("perl") is None: self.env.msg.fatal( "Input contains Perl preprocessor tags, but an installation of Perl could not be found" ) # Generate minimal perl script that captures activities described in the source file lines = [] for i,pp_seg in enumerate(segments): if isinstance(pp_seg, PPPUnalteredSegment): # Text outside preprocessor tags that should remain unaltered # Insert command to emit reference to this text segment lines.append("rdlppp_utils::emit_ref(%d);" % i) elif isinstance(pp_seg, PPPPerlSegment): # Perl code snippet. Insert directly lines.append(pp_seg.get_text()) elif isinstance(pp_seg, PPPMacroSegment): # Preprocessor macro print tag # Insert command to store resulting text var = pp_seg.get_text() # Check for any illegal characters if re.match(r'[\s;]', var): self.env.msg.fatal( "Invalid text found in Perl macro expansion", messages.SourceRef(pp_seg.start, pp_seg.end, filename=self.path) ) lines.append("rdlppp_utils::emit_text(%d, %s);" % (i, var)) miniscript = '\n'.join(lines) # Run miniscript result = subprocess_run( ["perl", os.path.join(os.path.dirname(__file__), "ppp_runner.pl")], input=miniscript.encode("utf-8"), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5 ) if result.returncode: self.env.msg.fatal( "Encountered a Perl syntax error while executing embedded Perl preprocessor commands:\n" + result.stderr.decode("utf-8"), # TODO: Fix useless context somehow messages.SourceRef(filename=self.path) ) # miniscript returns the emit list in JSON format. Convert it emit_list = json.loads(result.stdout.decode('utf-8')) return emit_list
python
def run_perl_miniscript(self, segments): """ Generates and runs a perl miniscript that derives the text that will be emitted from the preprocessor returns the resulting emit list """ # Check if perl is installed if shutil.which("perl") is None: self.env.msg.fatal( "Input contains Perl preprocessor tags, but an installation of Perl could not be found" ) # Generate minimal perl script that captures activities described in the source file lines = [] for i,pp_seg in enumerate(segments): if isinstance(pp_seg, PPPUnalteredSegment): # Text outside preprocessor tags that should remain unaltered # Insert command to emit reference to this text segment lines.append("rdlppp_utils::emit_ref(%d);" % i) elif isinstance(pp_seg, PPPPerlSegment): # Perl code snippet. Insert directly lines.append(pp_seg.get_text()) elif isinstance(pp_seg, PPPMacroSegment): # Preprocessor macro print tag # Insert command to store resulting text var = pp_seg.get_text() # Check for any illegal characters if re.match(r'[\s;]', var): self.env.msg.fatal( "Invalid text found in Perl macro expansion", messages.SourceRef(pp_seg.start, pp_seg.end, filename=self.path) ) lines.append("rdlppp_utils::emit_text(%d, %s);" % (i, var)) miniscript = '\n'.join(lines) # Run miniscript result = subprocess_run( ["perl", os.path.join(os.path.dirname(__file__), "ppp_runner.pl")], input=miniscript.encode("utf-8"), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5 ) if result.returncode: self.env.msg.fatal( "Encountered a Perl syntax error while executing embedded Perl preprocessor commands:\n" + result.stderr.decode("utf-8"), # TODO: Fix useless context somehow messages.SourceRef(filename=self.path) ) # miniscript returns the emit list in JSON format. Convert it emit_list = json.loads(result.stdout.decode('utf-8')) return emit_list
[ "def", "run_perl_miniscript", "(", "self", ",", "segments", ")", ":", "# Check if perl is installed", "if", "shutil", ".", "which", "(", "\"perl\"", ")", "is", "None", ":", "self", ".", "env", ".", "msg", ".", "fatal", "(", "\"Input contains Perl preprocessor ta...
Generates and runs a perl miniscript that derives the text that will be emitted from the preprocessor returns the resulting emit list
[ "Generates", "and", "runs", "a", "perl", "miniscript", "that", "derives", "the", "text", "that", "will", "be", "emitted", "from", "the", "preprocessor" ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/preprocessor.py#L264-L323
train
23,381
SystemRDL/systemrdl-compiler
systemrdl/core/namespace.py
NamespaceRegistry.get_default_properties
def get_default_properties(self, comp_type): """ Returns a flattened dictionary of all default property assignments visible in the current scope that apply to the current component type. """ # Flatten out all the default assignments that apply to the current scope # This does not include any default assignments made within the current # scope, so exclude those. props = {} for scope in self.default_property_ns_stack[:-1]: props.update(scope) # filter out properties that are not relevant prop_names = list(props.keys()) for prop_name in prop_names: rule = self.env.property_rules.lookup_property(prop_name) if rule is None: self.msg.fatal( "Unrecognized property '%s'" % prop_name, props[prop_name][0] ) if comp_type not in rule.bindable_to: del props[prop_name] return props
python
def get_default_properties(self, comp_type): """ Returns a flattened dictionary of all default property assignments visible in the current scope that apply to the current component type. """ # Flatten out all the default assignments that apply to the current scope # This does not include any default assignments made within the current # scope, so exclude those. props = {} for scope in self.default_property_ns_stack[:-1]: props.update(scope) # filter out properties that are not relevant prop_names = list(props.keys()) for prop_name in prop_names: rule = self.env.property_rules.lookup_property(prop_name) if rule is None: self.msg.fatal( "Unrecognized property '%s'" % prop_name, props[prop_name][0] ) if comp_type not in rule.bindable_to: del props[prop_name] return props
[ "def", "get_default_properties", "(", "self", ",", "comp_type", ")", ":", "# Flatten out all the default assignments that apply to the current scope", "# This does not include any default assignments made within the current", "# scope, so exclude those.", "props", "=", "{", "}", "for",...
Returns a flattened dictionary of all default property assignments visible in the current scope that apply to the current component type.
[ "Returns", "a", "flattened", "dictionary", "of", "all", "default", "property", "assignments", "visible", "in", "the", "current", "scope", "that", "apply", "to", "the", "current", "component", "type", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/namespace.py#L59-L83
train
23,382
SystemRDL/systemrdl-compiler
systemrdl/component.py
Component.get_scope_path
def get_scope_path(self, scope_separator="::"): """ Generate a string that represents this component's declaration namespace scope. Parameters ---------- scope_separator: str Override the separator between namespace scopes """ if self.parent_scope is None: return "" elif isinstance(self.parent_scope, Root): return "" else: parent_path = self.parent_scope.get_scope_path(scope_separator) if parent_path: return( parent_path + scope_separator + self.parent_scope.type_name ) else: return self.parent_scope.type_name
python
def get_scope_path(self, scope_separator="::"): """ Generate a string that represents this component's declaration namespace scope. Parameters ---------- scope_separator: str Override the separator between namespace scopes """ if self.parent_scope is None: return "" elif isinstance(self.parent_scope, Root): return "" else: parent_path = self.parent_scope.get_scope_path(scope_separator) if parent_path: return( parent_path + scope_separator + self.parent_scope.type_name ) else: return self.parent_scope.type_name
[ "def", "get_scope_path", "(", "self", ",", "scope_separator", "=", "\"::\"", ")", ":", "if", "self", ".", "parent_scope", "is", "None", ":", "return", "\"\"", "elif", "isinstance", "(", "self", ".", "parent_scope", ",", "Root", ")", ":", "return", "\"\"", ...
Generate a string that represents this component's declaration namespace scope. Parameters ---------- scope_separator: str Override the separator between namespace scopes
[ "Generate", "a", "string", "that", "represents", "this", "component", "s", "declaration", "namespace", "scope", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/component.py#L112-L135
train
23,383
SystemRDL/systemrdl-compiler
systemrdl/component.py
AddressableComponent.n_elements
def n_elements(self): """ Total number of array elements. If array is multidimensional, array is flattened. Returns 1 if not an array. """ if self.is_array: return functools.reduce(operator.mul, self.array_dimensions) else: return 1
python
def n_elements(self): """ Total number of array elements. If array is multidimensional, array is flattened. Returns 1 if not an array. """ if self.is_array: return functools.reduce(operator.mul, self.array_dimensions) else: return 1
[ "def", "n_elements", "(", "self", ")", ":", "if", "self", ".", "is_array", ":", "return", "functools", ".", "reduce", "(", "operator", ".", "mul", ",", "self", ".", "array_dimensions", ")", "else", ":", "return", "1" ]
Total number of array elements. If array is multidimensional, array is flattened. Returns 1 if not an array.
[ "Total", "number", "of", "array", "elements", ".", "If", "array", "is", "multidimensional", "array", "is", "flattened", ".", "Returns", "1", "if", "not", "an", "array", "." ]
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/component.py#L171-L180
train
23,384
SystemRDL/systemrdl-compiler
systemrdl/walker.py
RDLWalker.walk
def walk(self, node, *listeners:RDLListener): """ Initiates the walker to traverse the current ``node`` and its children. Calls the corresponding callback for each of the ``listeners`` provided in the order that they are listed. Parameters ---------- node : :class:`~systemrdl.node.Node` Node to start traversing. Listener traversal includes this node. listeners : list List of :class:`~RDLListener` that are invoked during node traversal. Listener callbacks are executed in the same order as provided by this parameter. """ for listener in listeners: self.do_enter(node, listener) for child in node.children(unroll=self.unroll, skip_not_present=self.skip_not_present): self.walk(child, *listeners) for listener in listeners: self.do_exit(node, listener)
python
def walk(self, node, *listeners:RDLListener): """ Initiates the walker to traverse the current ``node`` and its children. Calls the corresponding callback for each of the ``listeners`` provided in the order that they are listed. Parameters ---------- node : :class:`~systemrdl.node.Node` Node to start traversing. Listener traversal includes this node. listeners : list List of :class:`~RDLListener` that are invoked during node traversal. Listener callbacks are executed in the same order as provided by this parameter. """ for listener in listeners: self.do_enter(node, listener) for child in node.children(unroll=self.unroll, skip_not_present=self.skip_not_present): self.walk(child, *listeners) for listener in listeners: self.do_exit(node, listener)
[ "def", "walk", "(", "self", ",", "node", ",", "*", "listeners", ":", "RDLListener", ")", ":", "for", "listener", "in", "listeners", ":", "self", ".", "do_enter", "(", "node", ",", "listener", ")", "for", "child", "in", "node", ".", "children", "(", "...
Initiates the walker to traverse the current ``node`` and its children. Calls the corresponding callback for each of the ``listeners`` provided in the order that they are listed. Parameters ---------- node : :class:`~systemrdl.node.Node` Node to start traversing. Listener traversal includes this node. listeners : list List of :class:`~RDLListener` that are invoked during node traversal. Listener callbacks are executed in the same order as provided by this parameter.
[ "Initiates", "the", "walker", "to", "traverse", "the", "current", "node", "and", "its", "children", ".", "Calls", "the", "corresponding", "callback", "for", "each", "of", "the", "listeners", "provided", "in", "the", "order", "that", "they", "are", "listed", ...
6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/walker.py#L99-L124
train
23,385
elmotec/massedit
massedit.py
get_function
def get_function(fn_name): """Retrieve the function defined by the function_name. Arguments: fn_name: specification of the type module:function_name. """ module_name, callable_name = fn_name.split(':') current = globals() if not callable_name: callable_name = module_name else: import importlib try: module = importlib.import_module(module_name) except ImportError: log.error("failed to import %s", module_name) raise current = module for level in callable_name.split('.'): current = getattr(current, level) code = current.__code__ if code.co_argcount != 2: raise ValueError('function should take 2 arguments: lines, file_name') return current
python
def get_function(fn_name): """Retrieve the function defined by the function_name. Arguments: fn_name: specification of the type module:function_name. """ module_name, callable_name = fn_name.split(':') current = globals() if not callable_name: callable_name = module_name else: import importlib try: module = importlib.import_module(module_name) except ImportError: log.error("failed to import %s", module_name) raise current = module for level in callable_name.split('.'): current = getattr(current, level) code = current.__code__ if code.co_argcount != 2: raise ValueError('function should take 2 arguments: lines, file_name') return current
[ "def", "get_function", "(", "fn_name", ")", ":", "module_name", ",", "callable_name", "=", "fn_name", ".", "split", "(", "':'", ")", "current", "=", "globals", "(", ")", "if", "not", "callable_name", ":", "callable_name", "=", "module_name", "else", ":", "...
Retrieve the function defined by the function_name. Arguments: fn_name: specification of the type module:function_name.
[ "Retrieve", "the", "function", "defined", "by", "the", "function_name", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L66-L90
train
23,386
elmotec/massedit
massedit.py
parse_command_line
def parse_command_line(argv): """Parse command line argument. See -h option. Arguments: argv: arguments on the command line must include caller file name. """ import textwrap example = textwrap.dedent(""" Examples: # Simple string substitution (-e). Will show a diff. No changes applied. {0} -e "re.sub('failIf', 'assertFalse', line)" *.py # File level modifications (-f). Overwrites the files in place (-w). {0} -w -f fixer:fixit *.py # Will change all test*.py in subdirectories of tests. {0} -e "re.sub('failIf', 'assertFalse', line)" -s tests test*.py """).format(os.path.basename(argv[0])) formatter_class = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(description="Python mass editor", epilog=example, formatter_class=formatter_class) parser.add_argument("-V", "--version", action="version", version="%(prog)s {}".format(__version__)) parser.add_argument("-w", "--write", dest="dry_run", action="store_false", default=True, help="modify target file(s) in place. " "Shows diff otherwise.") parser.add_argument("-v", "--verbose", dest="verbose_count", action="count", default=0, help="increases log verbosity (can be specified " "multiple times)") parser.add_argument("-e", "--expression", dest="expressions", nargs=1, help="Python expressions applied to target files. " "Use the line variable to reference the current line.") parser.add_argument("-f", "--function", dest="functions", nargs=1, help="Python function to apply to target file. " "Takes file content as input and yield lines. " "Specify function as [module]:?<function name>.") parser.add_argument("-x", "--executable", dest="executables", nargs=1, help="Python executable to apply to target file.") parser.add_argument("-s", "--start", dest="start_dirs", help="Directory(ies) from which to look for targets.") parser.add_argument("-m", "--max-depth-level", type=int, dest="max_depth", help="Maximum depth when walking subdirectories.") parser.add_argument("-o", "--output", metavar="FILE", type=argparse.FileType("w"), default=sys.stdout, help="redirect output to a file") parser.add_argument("-g", "--generate", metavar="FILE", type=str, help="generate input file suitable for -f option") parser.add_argument("--encoding", dest="encoding", help="Encoding of input and output files") parser.add_argument("--newline", dest="newline", help="Newline character for output files") parser.add_argument("patterns", metavar="pattern", nargs="*", # argparse.REMAINDER, help="shell-like file name patterns to process.") arguments = parser.parse_args(argv[1:]) if not (arguments.expressions or arguments.functions or arguments.generate or arguments.executables): parser.error( '--expression, --function, --generate or --executable missing') # Sets log level to WARN going more verbose for each new -V. log.setLevel(max(3 - arguments.verbose_count, 0) * 10) return arguments
python
def parse_command_line(argv): """Parse command line argument. See -h option. Arguments: argv: arguments on the command line must include caller file name. """ import textwrap example = textwrap.dedent(""" Examples: # Simple string substitution (-e). Will show a diff. No changes applied. {0} -e "re.sub('failIf', 'assertFalse', line)" *.py # File level modifications (-f). Overwrites the files in place (-w). {0} -w -f fixer:fixit *.py # Will change all test*.py in subdirectories of tests. {0} -e "re.sub('failIf', 'assertFalse', line)" -s tests test*.py """).format(os.path.basename(argv[0])) formatter_class = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(description="Python mass editor", epilog=example, formatter_class=formatter_class) parser.add_argument("-V", "--version", action="version", version="%(prog)s {}".format(__version__)) parser.add_argument("-w", "--write", dest="dry_run", action="store_false", default=True, help="modify target file(s) in place. " "Shows diff otherwise.") parser.add_argument("-v", "--verbose", dest="verbose_count", action="count", default=0, help="increases log verbosity (can be specified " "multiple times)") parser.add_argument("-e", "--expression", dest="expressions", nargs=1, help="Python expressions applied to target files. " "Use the line variable to reference the current line.") parser.add_argument("-f", "--function", dest="functions", nargs=1, help="Python function to apply to target file. " "Takes file content as input and yield lines. " "Specify function as [module]:?<function name>.") parser.add_argument("-x", "--executable", dest="executables", nargs=1, help="Python executable to apply to target file.") parser.add_argument("-s", "--start", dest="start_dirs", help="Directory(ies) from which to look for targets.") parser.add_argument("-m", "--max-depth-level", type=int, dest="max_depth", help="Maximum depth when walking subdirectories.") parser.add_argument("-o", "--output", metavar="FILE", type=argparse.FileType("w"), default=sys.stdout, help="redirect output to a file") parser.add_argument("-g", "--generate", metavar="FILE", type=str, help="generate input file suitable for -f option") parser.add_argument("--encoding", dest="encoding", help="Encoding of input and output files") parser.add_argument("--newline", dest="newline", help="Newline character for output files") parser.add_argument("patterns", metavar="pattern", nargs="*", # argparse.REMAINDER, help="shell-like file name patterns to process.") arguments = parser.parse_args(argv[1:]) if not (arguments.expressions or arguments.functions or arguments.generate or arguments.executables): parser.error( '--expression, --function, --generate or --executable missing') # Sets log level to WARN going more verbose for each new -V. log.setLevel(max(3 - arguments.verbose_count, 0) * 10) return arguments
[ "def", "parse_command_line", "(", "argv", ")", ":", "import", "textwrap", "example", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n Examples:\n # Simple string substitution (-e). Will show a diff. No changes applied.\n {0} -e \"re.sub('failIf', 'assertFalse', line)\" *.py\n\n ...
Parse command line argument. See -h option. Arguments: argv: arguments on the command line must include caller file name.
[ "Parse", "command", "line", "argument", ".", "See", "-", "h", "option", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L332-L402
train
23,387
elmotec/massedit
massedit.py
get_paths
def get_paths(patterns, start_dirs=None, max_depth=1): """Retrieve files that match any of the patterns.""" # Shortcut: if there is only one pattern, make sure we process just that. if len(patterns) == 1 and not start_dirs: pattern = patterns[0] directory = os.path.dirname(pattern) if directory: patterns = [os.path.basename(pattern)] start_dirs = directory max_depth = 1 if not start_dirs or start_dirs == '.': start_dirs = os.getcwd() for start_dir in start_dirs.split(','): for root, dirs, files in os.walk(start_dir): # pylint: disable=W0612 if max_depth is not None: relpath = os.path.relpath(root, start=start_dir) depth = len(relpath.split(os.sep)) if depth > max_depth: continue names = [] for pattern in patterns: names += fnmatch.filter(files, pattern) for name in names: path = os.path.join(root, name) yield path
python
def get_paths(patterns, start_dirs=None, max_depth=1): """Retrieve files that match any of the patterns.""" # Shortcut: if there is only one pattern, make sure we process just that. if len(patterns) == 1 and not start_dirs: pattern = patterns[0] directory = os.path.dirname(pattern) if directory: patterns = [os.path.basename(pattern)] start_dirs = directory max_depth = 1 if not start_dirs or start_dirs == '.': start_dirs = os.getcwd() for start_dir in start_dirs.split(','): for root, dirs, files in os.walk(start_dir): # pylint: disable=W0612 if max_depth is not None: relpath = os.path.relpath(root, start=start_dir) depth = len(relpath.split(os.sep)) if depth > max_depth: continue names = [] for pattern in patterns: names += fnmatch.filter(files, pattern) for name in names: path = os.path.join(root, name) yield path
[ "def", "get_paths", "(", "patterns", ",", "start_dirs", "=", "None", ",", "max_depth", "=", "1", ")", ":", "# Shortcut: if there is only one pattern, make sure we process just that.", "if", "len", "(", "patterns", ")", "==", "1", "and", "not", "start_dirs", ":", "...
Retrieve files that match any of the patterns.
[ "Retrieve", "files", "that", "match", "any", "of", "the", "patterns", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L405-L430
train
23,388
elmotec/massedit
massedit.py
edit_files
def edit_files(patterns, expressions=None, functions=None, executables=None, start_dirs=None, max_depth=1, dry_run=True, output=sys.stdout, encoding=None, newline=None): """Process patterns with MassEdit. Arguments: patterns: file pattern to identify the files to be processed. expressions: single python expression to be applied line by line. functions: functions to process files contents. executables: os executables to execute on the argument files. Keyword arguments: max_depth: maximum recursion level when looking for file matches. start_dirs: workspace(ies) where to start the file search. dry_run: only display differences if True. Save modified file otherwise. output: handle where the output should be redirected. Return: list of files processed. """ if not is_list(patterns): raise TypeError("patterns should be a list") if expressions and not is_list(expressions): raise TypeError("expressions should be a list of exec expressions") if functions and not is_list(functions): raise TypeError("functions should be a list of functions") if executables and not is_list(executables): raise TypeError("executables should be a list of program names") editor = MassEdit(dry_run=dry_run, encoding=encoding, newline=newline) if expressions: editor.set_code_exprs(expressions) if functions: editor.set_functions(functions) if executables: editor.set_executables(executables) processed_paths = [] for path in get_paths(patterns, start_dirs=start_dirs, max_depth=max_depth): try: diffs = list(editor.edit_file(path)) if dry_run: # At this point, encoding is the input encoding. diff = "".join(diffs) if not diff: continue # The encoding of the target output may not match the input # encoding. If it's defined, we round trip the diff text # to bytes and back to silence any conversion errors. encoding = output.encoding if encoding: bytes_diff = diff.encode(encoding=encoding, errors='ignore') diff = bytes_diff.decode(encoding=output.encoding) output.write(diff) except UnicodeDecodeError as err: log.error("failed to process %s: %s", path, err) continue processed_paths.append(os.path.abspath(path)) return processed_paths
python
def edit_files(patterns, expressions=None, functions=None, executables=None, start_dirs=None, max_depth=1, dry_run=True, output=sys.stdout, encoding=None, newline=None): """Process patterns with MassEdit. Arguments: patterns: file pattern to identify the files to be processed. expressions: single python expression to be applied line by line. functions: functions to process files contents. executables: os executables to execute on the argument files. Keyword arguments: max_depth: maximum recursion level when looking for file matches. start_dirs: workspace(ies) where to start the file search. dry_run: only display differences if True. Save modified file otherwise. output: handle where the output should be redirected. Return: list of files processed. """ if not is_list(patterns): raise TypeError("patterns should be a list") if expressions and not is_list(expressions): raise TypeError("expressions should be a list of exec expressions") if functions and not is_list(functions): raise TypeError("functions should be a list of functions") if executables and not is_list(executables): raise TypeError("executables should be a list of program names") editor = MassEdit(dry_run=dry_run, encoding=encoding, newline=newline) if expressions: editor.set_code_exprs(expressions) if functions: editor.set_functions(functions) if executables: editor.set_executables(executables) processed_paths = [] for path in get_paths(patterns, start_dirs=start_dirs, max_depth=max_depth): try: diffs = list(editor.edit_file(path)) if dry_run: # At this point, encoding is the input encoding. diff = "".join(diffs) if not diff: continue # The encoding of the target output may not match the input # encoding. If it's defined, we round trip the diff text # to bytes and back to silence any conversion errors. encoding = output.encoding if encoding: bytes_diff = diff.encode(encoding=encoding, errors='ignore') diff = bytes_diff.decode(encoding=output.encoding) output.write(diff) except UnicodeDecodeError as err: log.error("failed to process %s: %s", path, err) continue processed_paths.append(os.path.abspath(path)) return processed_paths
[ "def", "edit_files", "(", "patterns", ",", "expressions", "=", "None", ",", "functions", "=", "None", ",", "executables", "=", "None", ",", "start_dirs", "=", "None", ",", "max_depth", "=", "1", ",", "dry_run", "=", "True", ",", "output", "=", "sys", "...
Process patterns with MassEdit. Arguments: patterns: file pattern to identify the files to be processed. expressions: single python expression to be applied line by line. functions: functions to process files contents. executables: os executables to execute on the argument files. Keyword arguments: max_depth: maximum recursion level when looking for file matches. start_dirs: workspace(ies) where to start the file search. dry_run: only display differences if True. Save modified file otherwise. output: handle where the output should be redirected. Return: list of files processed.
[ "Process", "patterns", "with", "MassEdit", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L469-L530
train
23,389
elmotec/massedit
massedit.py
command_line
def command_line(argv): """Instantiate an editor and process arguments. Optional argument: - processed_paths: paths processed are appended to the list. """ arguments = parse_command_line(argv) if arguments.generate: generate_fixer_file(arguments.generate) paths = edit_files(arguments.patterns, expressions=arguments.expressions, functions=arguments.functions, executables=arguments.executables, start_dirs=arguments.start_dirs, max_depth=arguments.max_depth, dry_run=arguments.dry_run, output=arguments.output, encoding=arguments.encoding, newline=arguments.newline) # If the output is not sys.stdout, we need to close it because # argparse.FileType does not do it for us. is_sys = arguments.output in [sys.stdout, sys.stderr] if not is_sys and isinstance(arguments.output, io.IOBase): arguments.output.close() return paths
python
def command_line(argv): """Instantiate an editor and process arguments. Optional argument: - processed_paths: paths processed are appended to the list. """ arguments = parse_command_line(argv) if arguments.generate: generate_fixer_file(arguments.generate) paths = edit_files(arguments.patterns, expressions=arguments.expressions, functions=arguments.functions, executables=arguments.executables, start_dirs=arguments.start_dirs, max_depth=arguments.max_depth, dry_run=arguments.dry_run, output=arguments.output, encoding=arguments.encoding, newline=arguments.newline) # If the output is not sys.stdout, we need to close it because # argparse.FileType does not do it for us. is_sys = arguments.output in [sys.stdout, sys.stderr] if not is_sys and isinstance(arguments.output, io.IOBase): arguments.output.close() return paths
[ "def", "command_line", "(", "argv", ")", ":", "arguments", "=", "parse_command_line", "(", "argv", ")", "if", "arguments", ".", "generate", ":", "generate_fixer_file", "(", "arguments", ".", "generate", ")", "paths", "=", "edit_files", "(", "arguments", ".", ...
Instantiate an editor and process arguments. Optional argument: - processed_paths: paths processed are appended to the list.
[ "Instantiate", "an", "editor", "and", "process", "arguments", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L533-L558
train
23,390
elmotec/massedit
massedit.py
MassEdit.import_module
def import_module(module): # pylint: disable=R0201 """Import module that are needed for the code expr to compile. Argument: module (str or list): module(s) to import. """ if isinstance(module, list): all_modules = module else: all_modules = [module] for mod in all_modules: globals()[mod] = __import__(mod.strip())
python
def import_module(module): # pylint: disable=R0201 """Import module that are needed for the code expr to compile. Argument: module (str or list): module(s) to import. """ if isinstance(module, list): all_modules = module else: all_modules = [module] for mod in all_modules: globals()[mod] = __import__(mod.strip())
[ "def", "import_module", "(", "module", ")", ":", "# pylint: disable=R0201", "if", "isinstance", "(", "module", ",", "list", ")", ":", "all_modules", "=", "module", "else", ":", "all_modules", "=", "[", "module", "]", "for", "mod", "in", "all_modules", ":", ...
Import module that are needed for the code expr to compile. Argument: module (str or list): module(s) to import.
[ "Import", "module", "that", "are", "needed", "for", "the", "code", "expr", "to", "compile", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L131-L143
train
23,391
elmotec/massedit
massedit.py
MassEdit.__edit_line
def __edit_line(line, code, code_obj): # pylint: disable=R0201 """Edit a line with one code object built in the ctor.""" try: # pylint: disable=eval-used result = eval(code_obj, globals(), locals()) except TypeError as ex: log.error("failed to execute %s: %s", code, ex) raise if result is None: log.error("cannot process line '%s' with %s", line, code) raise RuntimeError('failed to process line') elif isinstance(result, list) or isinstance(result, tuple): line = unicode(' '.join([unicode(res_element) for res_element in result])) else: line = unicode(result) return line
python
def __edit_line(line, code, code_obj): # pylint: disable=R0201 """Edit a line with one code object built in the ctor.""" try: # pylint: disable=eval-used result = eval(code_obj, globals(), locals()) except TypeError as ex: log.error("failed to execute %s: %s", code, ex) raise if result is None: log.error("cannot process line '%s' with %s", line, code) raise RuntimeError('failed to process line') elif isinstance(result, list) or isinstance(result, tuple): line = unicode(' '.join([unicode(res_element) for res_element in result])) else: line = unicode(result) return line
[ "def", "__edit_line", "(", "line", ",", "code", ",", "code_obj", ")", ":", "# pylint: disable=R0201", "try", ":", "# pylint: disable=eval-used", "result", "=", "eval", "(", "code_obj", ",", "globals", "(", ")", ",", "locals", "(", ")", ")", "except", "TypeEr...
Edit a line with one code object built in the ctor.
[ "Edit", "a", "line", "with", "one", "code", "object", "built", "in", "the", "ctor", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L146-L162
train
23,392
elmotec/massedit
massedit.py
MassEdit.edit_line
def edit_line(self, line): """Edit a single line using the code expression.""" for code, code_obj in self.code_objs.items(): line = self.__edit_line(line, code, code_obj) return line
python
def edit_line(self, line): """Edit a single line using the code expression.""" for code, code_obj in self.code_objs.items(): line = self.__edit_line(line, code, code_obj) return line
[ "def", "edit_line", "(", "self", ",", "line", ")", ":", "for", "code", ",", "code_obj", "in", "self", ".", "code_objs", ".", "items", "(", ")", ":", "line", "=", "self", ".", "__edit_line", "(", "line", ",", "code", ",", "code_obj", ")", "return", ...
Edit a single line using the code expression.
[ "Edit", "a", "single", "line", "using", "the", "code", "expression", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L164-L168
train
23,393
elmotec/massedit
massedit.py
MassEdit.edit_content
def edit_content(self, original_lines, file_name): """Processes a file contents. First processes the contents line by line applying the registered expressions, then process the resulting contents using the registered functions. Arguments: original_lines (list of str): file content. file_name (str): name of the file. """ lines = [self.edit_line(line) for line in original_lines] for function in self._functions: try: lines = list(function(lines, file_name)) except UnicodeDecodeError as err: log.error('failed to process %s: %s', file_name, err) return lines except Exception as err: log.error("failed to process %s with code %s: %s", file_name, function, err) raise # Let the exception be handled at a higher level. return lines
python
def edit_content(self, original_lines, file_name): """Processes a file contents. First processes the contents line by line applying the registered expressions, then process the resulting contents using the registered functions. Arguments: original_lines (list of str): file content. file_name (str): name of the file. """ lines = [self.edit_line(line) for line in original_lines] for function in self._functions: try: lines = list(function(lines, file_name)) except UnicodeDecodeError as err: log.error('failed to process %s: %s', file_name, err) return lines except Exception as err: log.error("failed to process %s with code %s: %s", file_name, function, err) raise # Let the exception be handled at a higher level. return lines
[ "def", "edit_content", "(", "self", ",", "original_lines", ",", "file_name", ")", ":", "lines", "=", "[", "self", ".", "edit_line", "(", "line", ")", "for", "line", "in", "original_lines", "]", "for", "function", "in", "self", ".", "_functions", ":", "tr...
Processes a file contents. First processes the contents line by line applying the registered expressions, then process the resulting contents using the registered functions. Arguments: original_lines (list of str): file content. file_name (str): name of the file.
[ "Processes", "a", "file", "contents", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L170-L193
train
23,394
elmotec/massedit
massedit.py
MassEdit.append_code_expr
def append_code_expr(self, code): """Compile argument and adds it to the list of code objects.""" # expects a string. if isinstance(code, str) and not isinstance(code, unicode): code = unicode(code) if not isinstance(code, unicode): raise TypeError("string expected") log.debug("compiling code %s...", code) try: code_obj = compile(code, '<string>', 'eval') self.code_objs[code] = code_obj except SyntaxError as syntax_err: log.error("cannot compile %s: %s", code, syntax_err) raise log.debug("compiled code %s", code)
python
def append_code_expr(self, code): """Compile argument and adds it to the list of code objects.""" # expects a string. if isinstance(code, str) and not isinstance(code, unicode): code = unicode(code) if not isinstance(code, unicode): raise TypeError("string expected") log.debug("compiling code %s...", code) try: code_obj = compile(code, '<string>', 'eval') self.code_objs[code] = code_obj except SyntaxError as syntax_err: log.error("cannot compile %s: %s", code, syntax_err) raise log.debug("compiled code %s", code)
[ "def", "append_code_expr", "(", "self", ",", "code", ")", ":", "# expects a string.", "if", "isinstance", "(", "code", ",", "str", ")", "and", "not", "isinstance", "(", "code", ",", "unicode", ")", ":", "code", "=", "unicode", "(", "code", ")", "if", "...
Compile argument and adds it to the list of code objects.
[ "Compile", "argument", "and", "adds", "it", "to", "the", "list", "of", "code", "objects", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L262-L276
train
23,395
elmotec/massedit
massedit.py
MassEdit.append_function
def append_function(self, function): """Append the function to the list of functions to be called. If the function is already a callable, use it. If it's a type str try to interpret it as [module]:?<callable>, load the module if there is one and retrieve the callable. Argument: function (str or callable): function to call on input. """ if not hasattr(function, '__call__'): function = get_function(function) if not hasattr(function, '__call__'): raise ValueError("function is expected to be callable") self._functions.append(function) log.debug("registered %s", function.__name__)
python
def append_function(self, function): """Append the function to the list of functions to be called. If the function is already a callable, use it. If it's a type str try to interpret it as [module]:?<callable>, load the module if there is one and retrieve the callable. Argument: function (str or callable): function to call on input. """ if not hasattr(function, '__call__'): function = get_function(function) if not hasattr(function, '__call__'): raise ValueError("function is expected to be callable") self._functions.append(function) log.debug("registered %s", function.__name__)
[ "def", "append_function", "(", "self", ",", "function", ")", ":", "if", "not", "hasattr", "(", "function", ",", "'__call__'", ")", ":", "function", "=", "get_function", "(", "function", ")", "if", "not", "hasattr", "(", "function", ",", "'__call__'", ")", ...
Append the function to the list of functions to be called. If the function is already a callable, use it. If it's a type str try to interpret it as [module]:?<callable>, load the module if there is one and retrieve the callable. Argument: function (str or callable): function to call on input.
[ "Append", "the", "function", "to", "the", "list", "of", "functions", "to", "be", "called", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L278-L294
train
23,396
elmotec/massedit
massedit.py
MassEdit.append_executable
def append_executable(self, executable): """Append san executable os command to the list to be called. Argument: executable (str): os callable executable. """ if isinstance(executable, str) and not isinstance(executable, unicode): executable = unicode(executable) if not isinstance(executable, unicode): raise TypeError("expected executable name as str, not {}". format(executable.__class__.__name__)) self._executables.append(executable)
python
def append_executable(self, executable): """Append san executable os command to the list to be called. Argument: executable (str): os callable executable. """ if isinstance(executable, str) and not isinstance(executable, unicode): executable = unicode(executable) if not isinstance(executable, unicode): raise TypeError("expected executable name as str, not {}". format(executable.__class__.__name__)) self._executables.append(executable)
[ "def", "append_executable", "(", "self", ",", "executable", ")", ":", "if", "isinstance", "(", "executable", ",", "str", ")", "and", "not", "isinstance", "(", "executable", ",", "unicode", ")", ":", "executable", "=", "unicode", "(", "executable", ")", "if...
Append san executable os command to the list to be called. Argument: executable (str): os callable executable.
[ "Append", "san", "executable", "os", "command", "to", "the", "list", "to", "be", "called", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L296-L308
train
23,397
elmotec/massedit
massedit.py
MassEdit.set_functions
def set_functions(self, functions): """Check functions passed as argument and set them to be used.""" for func in functions: try: self.append_function(func) except (ValueError, AttributeError) as ex: log.error("'%s' is not a callable function: %s", func, ex) raise
python
def set_functions(self, functions): """Check functions passed as argument and set them to be used.""" for func in functions: try: self.append_function(func) except (ValueError, AttributeError) as ex: log.error("'%s' is not a callable function: %s", func, ex) raise
[ "def", "set_functions", "(", "self", ",", "functions", ")", ":", "for", "func", "in", "functions", ":", "try", ":", "self", ".", "append_function", "(", "func", ")", "except", "(", "ValueError", ",", "AttributeError", ")", "as", "ex", ":", "log", ".", ...
Check functions passed as argument and set them to be used.
[ "Check", "functions", "passed", "as", "argument", "and", "set", "them", "to", "be", "used", "." ]
57e22787354896d63a8850312314b19aa0308906
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L317-L324
train
23,398
wonambi-python/wonambi
wonambi/ioeeg/mnefiff.py
write_mnefiff
def write_mnefiff(data, filename): """Export data to MNE using FIFF format. Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (include '.mat') Notes ----- It cannot store data larger than 2 GB. The data is assumed to have only EEG electrodes. It overwrites a file if it exists. """ from mne import create_info, set_log_level from mne.io import RawArray set_log_level(WARNING) TRIAL = 0 info = create_info(list(data.axis['chan'][TRIAL]), data.s_freq, ['eeg', ] * data.number_of('chan')[TRIAL]) UNITS = 1e-6 # mne wants data in uV fiff = RawArray(data.data[0] * UNITS, info) if data.attr['chan']: fiff.set_channel_positions(data.attr['chan'].return_xyz(), data.attr['chan'].return_label()) fiff.save(filename, overwrite=True)
python
def write_mnefiff(data, filename): """Export data to MNE using FIFF format. Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (include '.mat') Notes ----- It cannot store data larger than 2 GB. The data is assumed to have only EEG electrodes. It overwrites a file if it exists. """ from mne import create_info, set_log_level from mne.io import RawArray set_log_level(WARNING) TRIAL = 0 info = create_info(list(data.axis['chan'][TRIAL]), data.s_freq, ['eeg', ] * data.number_of('chan')[TRIAL]) UNITS = 1e-6 # mne wants data in uV fiff = RawArray(data.data[0] * UNITS, info) if data.attr['chan']: fiff.set_channel_positions(data.attr['chan'].return_xyz(), data.attr['chan'].return_label()) fiff.save(filename, overwrite=True)
[ "def", "write_mnefiff", "(", "data", ",", "filename", ")", ":", "from", "mne", "import", "create_info", ",", "set_log_level", "from", "mne", ".", "io", "import", "RawArray", "set_log_level", "(", "WARNING", ")", "TRIAL", "=", "0", "info", "=", "create_info",...
Export data to MNE using FIFF format. Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (include '.mat') Notes ----- It cannot store data larger than 2 GB. The data is assumed to have only EEG electrodes. It overwrites a file if it exists.
[ "Export", "data", "to", "MNE", "using", "FIFF", "format", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/mnefiff.py#L5-L37
train
23,399