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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
kencochrane/django-defender | defender/connection.py | get_redis_connection | def get_redis_connection():
""" Get the redis connection if not using mock """
if config.MOCK_REDIS: # pragma: no cover
import mockredis
return mockredis.mock_strict_redis_client() # pragma: no cover
elif config.DEFENDER_REDIS_NAME: # pragma: no cover
try:
cache = cach... | python | def get_redis_connection():
""" Get the redis connection if not using mock """
if config.MOCK_REDIS: # pragma: no cover
import mockredis
return mockredis.mock_strict_redis_client() # pragma: no cover
elif config.DEFENDER_REDIS_NAME: # pragma: no cover
try:
cache = cach... | [
"def",
"get_redis_connection",
"(",
")",
":",
"if",
"config",
".",
"MOCK_REDIS",
":",
"import",
"mockredis",
"return",
"mockredis",
".",
"mock_strict_redis_client",
"(",
")",
"elif",
"config",
".",
"DEFENDER_REDIS_NAME",
":",
"try",
":",
"cache",
"=",
"caches",
... | Get the redis connection if not using mock | [
"Get",
"the",
"redis",
"connection",
"if",
"not",
"using",
"mock"
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/connection.py#L19-L44 | train |
kencochrane/django-defender | defender/connection.py | parse_redis_url | def parse_redis_url(url):
"""Parses a redis URL."""
# create config with some sane defaults
redis_config = {
"DB": 0,
"PASSWORD": None,
"HOST": "localhost",
"PORT": 6379,
"SSL": False
}
if not url:
return redis_config
url = urlparse.urlparse(url... | python | def parse_redis_url(url):
"""Parses a redis URL."""
# create config with some sane defaults
redis_config = {
"DB": 0,
"PASSWORD": None,
"HOST": "localhost",
"PORT": 6379,
"SSL": False
}
if not url:
return redis_config
url = urlparse.urlparse(url... | [
"def",
"parse_redis_url",
"(",
"url",
")",
":",
"redis_config",
"=",
"{",
"\"DB\"",
":",
"0",
",",
"\"PASSWORD\"",
":",
"None",
",",
"\"HOST\"",
":",
"\"localhost\"",
",",
"\"PORT\"",
":",
"6379",
",",
"\"SSL\"",
":",
"False",
"}",
"if",
"not",
"url",
... | Parses a redis URL. | [
"Parses",
"a",
"redis",
"URL",
"."
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/connection.py#L48-L79 | train |
kencochrane/django-defender | defender/management/commands/cleanup_django_defender.py | Command.handle | def handle(self, **options):
"""
Removes any entries in the AccessAttempt that are older
than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS.
"""
print("Starting clean up of django-defender table")
now = timezone.now()
cleanup_delta = timedelta(h... | python | def handle(self, **options):
"""
Removes any entries in the AccessAttempt that are older
than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS.
"""
print("Starting clean up of django-defender table")
now = timezone.now()
cleanup_delta = timedelta(h... | [
"def",
"handle",
"(",
"self",
",",
"**",
"options",
")",
":",
"print",
"(",
"\"Starting clean up of django-defender table\"",
")",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"cleanup_delta",
"=",
"timedelta",
"(",
"hours",
"=",
"config",
".",
"ACCESS_ATTEMP... | Removes any entries in the AccessAttempt that are older
than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS. | [
"Removes",
"any",
"entries",
"in",
"the",
"AccessAttempt",
"that",
"are",
"older",
"than",
"your",
"DEFENDER_ACCESS_ATTEMPT_EXPIRATION",
"config",
"default",
"24",
"HOURS",
"."
] | e3e547dbb83235e0d564a6d64652c7df00412ff2 | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/management/commands/cleanup_django_defender.py#L15-L35 | train |
Cito/DBUtils | DBUtils/PooledDB.py | PooledDB.connection | def connection(self, shareable=True):
"""Get a steady, cached DB-API 2 connection from the pool.
If shareable is set and the underlying DB-API 2 allows it,
then the connection may be shared with other threads.
"""
if shareable and self._maxshared:
self._lock.acquire... | python | def connection(self, shareable=True):
"""Get a steady, cached DB-API 2 connection from the pool.
If shareable is set and the underlying DB-API 2 allows it,
then the connection may be shared with other threads.
"""
if shareable and self._maxshared:
self._lock.acquire... | [
"def",
"connection",
"(",
"self",
",",
"shareable",
"=",
"True",
")",
":",
"if",
"shareable",
"and",
"self",
".",
"_maxshared",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"while",
"(",
"not",
"self",
".",
"_shared_cache",
"and",
... | Get a steady, cached DB-API 2 connection from the pool.
If shareable is set and the underlying DB-API 2 allows it,
then the connection may be shared with other threads. | [
"Get",
"a",
"steady",
"cached",
"DB",
"-",
"API",
"2",
"connection",
"from",
"the",
"pool",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledDB.py#L277-L334 | train |
Cito/DBUtils | DBUtils/PooledDB.py | PooledDB.unshare | def unshare(self, con):
"""Decrease the share of a connection in the shared cache."""
self._lock.acquire()
try:
con.unshare()
shared = con.shared
if not shared: # connection is idle,
try: # so try to remove it
self._shared... | python | def unshare(self, con):
"""Decrease the share of a connection in the shared cache."""
self._lock.acquire()
try:
con.unshare()
shared = con.shared
if not shared: # connection is idle,
try: # so try to remove it
self._shared... | [
"def",
"unshare",
"(",
"self",
",",
"con",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"con",
".",
"unshare",
"(",
")",
"shared",
"=",
"con",
".",
"shared",
"if",
"not",
"shared",
":",
"try",
":",
"self",
".",
"_shared_c... | Decrease the share of a connection in the shared cache. | [
"Decrease",
"the",
"share",
"of",
"a",
"connection",
"in",
"the",
"shared",
"cache",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledDB.py#L340-L354 | train |
Cito/DBUtils | DBUtils/PooledDB.py | PooledSharedDBConnection.close | def close(self):
"""Close the pooled shared connection."""
# Instead of actually closing the connection,
# unshare it and/or return it to the pool.
if self._con:
self._pool.unshare(self._shared_con)
self._shared_con = self._con = None | python | def close(self):
"""Close the pooled shared connection."""
# Instead of actually closing the connection,
# unshare it and/or return it to the pool.
if self._con:
self._pool.unshare(self._shared_con)
self._shared_con = self._con = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_con",
":",
"self",
".",
"_pool",
".",
"unshare",
"(",
"self",
".",
"_shared_con",
")",
"self",
".",
"_shared_con",
"=",
"self",
".",
"_con",
"=",
"None"
] | Close the pooled shared connection. | [
"Close",
"the",
"pooled",
"shared",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledDB.py#L516-L522 | train |
Cito/DBUtils | DBUtils/PersistentDB.py | PersistentDB.steady_connection | def steady_connection(self):
"""Get a steady, non-persistent DB-API 2 connection."""
return connect(
self._creator, self._maxusage, self._setsession,
self._failures, self._ping, self._closeable,
*self._args, **self._kwargs) | python | def steady_connection(self):
"""Get a steady, non-persistent DB-API 2 connection."""
return connect(
self._creator, self._maxusage, self._setsession,
self._failures, self._ping, self._closeable,
*self._args, **self._kwargs) | [
"def",
"steady_connection",
"(",
"self",
")",
":",
"return",
"connect",
"(",
"self",
".",
"_creator",
",",
"self",
".",
"_maxusage",
",",
"self",
".",
"_setsession",
",",
"self",
".",
"_failures",
",",
"self",
".",
"_ping",
",",
"self",
".",
"_closeable"... | Get a steady, non-persistent DB-API 2 connection. | [
"Get",
"a",
"steady",
"non",
"-",
"persistent",
"DB",
"-",
"API",
"2",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentDB.py#L201-L206 | train |
Cito/DBUtils | DBUtils/PersistentDB.py | PersistentDB.connection | def connection(self, shareable=False):
"""Get a steady, persistent DB-API 2 connection.
The shareable parameter exists only for compatibility with the
PooledDB connection method. In reality, persistent connections
are of course never shared with other threads.
"""
try:... | python | def connection(self, shareable=False):
"""Get a steady, persistent DB-API 2 connection.
The shareable parameter exists only for compatibility with the
PooledDB connection method. In reality, persistent connections
are of course never shared with other threads.
"""
try:... | [
"def",
"connection",
"(",
"self",
",",
"shareable",
"=",
"False",
")",
":",
"try",
":",
"con",
"=",
"self",
".",
"thread",
".",
"connection",
"except",
"AttributeError",
":",
"con",
"=",
"self",
".",
"steady_connection",
"(",
")",
"if",
"not",
"con",
"... | Get a steady, persistent DB-API 2 connection.
The shareable parameter exists only for compatibility with the
PooledDB connection method. In reality, persistent connections
are of course never shared with other threads. | [
"Get",
"a",
"steady",
"persistent",
"DB",
"-",
"API",
"2",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentDB.py#L208-L224 | train |
Cito/DBUtils | DBUtils/PersistentPg.py | PersistentPg.steady_connection | def steady_connection(self):
"""Get a steady, non-persistent PyGreSQL connection."""
return SteadyPgConnection(
self._maxusage, self._setsession, self._closeable,
*self._args, **self._kwargs) | python | def steady_connection(self):
"""Get a steady, non-persistent PyGreSQL connection."""
return SteadyPgConnection(
self._maxusage, self._setsession, self._closeable,
*self._args, **self._kwargs) | [
"def",
"steady_connection",
"(",
"self",
")",
":",
"return",
"SteadyPgConnection",
"(",
"self",
".",
"_maxusage",
",",
"self",
".",
"_setsession",
",",
"self",
".",
"_closeable",
",",
"*",
"self",
".",
"_args",
",",
"**",
"self",
".",
"_kwargs",
")"
] | Get a steady, non-persistent PyGreSQL connection. | [
"Get",
"a",
"steady",
"non",
"-",
"persistent",
"PyGreSQL",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentPg.py#L160-L164 | train |
Cito/DBUtils | DBUtils/PersistentPg.py | PersistentPg.connection | def connection(self):
"""Get a steady, persistent PyGreSQL connection."""
try:
con = self.thread.connection
except AttributeError:
con = self.steady_connection()
self.thread.connection = con
return con | python | def connection(self):
"""Get a steady, persistent PyGreSQL connection."""
try:
con = self.thread.connection
except AttributeError:
con = self.steady_connection()
self.thread.connection = con
return con | [
"def",
"connection",
"(",
"self",
")",
":",
"try",
":",
"con",
"=",
"self",
".",
"thread",
".",
"connection",
"except",
"AttributeError",
":",
"con",
"=",
"self",
".",
"steady_connection",
"(",
")",
"self",
".",
"thread",
".",
"connection",
"=",
"con",
... | Get a steady, persistent PyGreSQL connection. | [
"Get",
"a",
"steady",
"persistent",
"PyGreSQL",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PersistentPg.py#L166-L173 | train |
Cito/DBUtils | setversion.py | versionString | def versionString(version):
"""Create version string.
For a sequence containing version information such as (2, 0, 0, 'pre'),
this returns a printable string such as '2.0pre'.
The micro version number is only excluded from the string if it is zero.
"""
ver = list(map(str, version))
numbers... | python | def versionString(version):
"""Create version string.
For a sequence containing version information such as (2, 0, 0, 'pre'),
this returns a printable string such as '2.0pre'.
The micro version number is only excluded from the string if it is zero.
"""
ver = list(map(str, version))
numbers... | [
"def",
"versionString",
"(",
"version",
")",
":",
"ver",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"version",
")",
")",
"numbers",
",",
"rest",
"=",
"ver",
"[",
":",
"2",
"if",
"ver",
"[",
"2",
"]",
"==",
"'0'",
"else",
"3",
"]",
",",
"ver",
... | Create version string.
For a sequence containing version information such as (2, 0, 0, 'pre'),
this returns a printable string such as '2.0pre'.
The micro version number is only excluded from the string if it is zero. | [
"Create",
"version",
"string",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/setversion.py#L37-L47 | train |
Cito/DBUtils | DBUtils/PooledPg.py | PooledPg.steady_connection | def steady_connection(self):
"""Get a steady, unpooled PostgreSQL connection."""
return SteadyPgConnection(self._maxusage, self._setsession, True,
*self._args, **self._kwargs) | python | def steady_connection(self):
"""Get a steady, unpooled PostgreSQL connection."""
return SteadyPgConnection(self._maxusage, self._setsession, True,
*self._args, **self._kwargs) | [
"def",
"steady_connection",
"(",
"self",
")",
":",
"return",
"SteadyPgConnection",
"(",
"self",
".",
"_maxusage",
",",
"self",
".",
"_setsession",
",",
"True",
",",
"*",
"self",
".",
"_args",
",",
"**",
"self",
".",
"_kwargs",
")"
] | Get a steady, unpooled PostgreSQL connection. | [
"Get",
"a",
"steady",
"unpooled",
"PostgreSQL",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L200-L203 | train |
Cito/DBUtils | DBUtils/PooledPg.py | PooledPg.connection | def connection(self):
"""Get a steady, cached PostgreSQL connection from the pool."""
if self._connections:
if not self._connections.acquire(self._blocking):
raise TooManyConnections
try:
con = self._cache.get(0)
except Empty:
con = sel... | python | def connection(self):
"""Get a steady, cached PostgreSQL connection from the pool."""
if self._connections:
if not self._connections.acquire(self._blocking):
raise TooManyConnections
try:
con = self._cache.get(0)
except Empty:
con = sel... | [
"def",
"connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connections",
":",
"if",
"not",
"self",
".",
"_connections",
".",
"acquire",
"(",
"self",
".",
"_blocking",
")",
":",
"raise",
"TooManyConnections",
"try",
":",
"con",
"=",
"self",
".",
"... | Get a steady, cached PostgreSQL connection from the pool. | [
"Get",
"a",
"steady",
"cached",
"PostgreSQL",
"connection",
"from",
"the",
"pool",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L205-L214 | train |
Cito/DBUtils | DBUtils/PooledPg.py | PooledPg.cache | def cache(self, con):
"""Put a connection back into the pool cache."""
try:
if self._reset == 2:
con.reset() # reset the connection completely
else:
if self._reset or con._transaction:
try:
con.rollback(... | python | def cache(self, con):
"""Put a connection back into the pool cache."""
try:
if self._reset == 2:
con.reset() # reset the connection completely
else:
if self._reset or con._transaction:
try:
con.rollback(... | [
"def",
"cache",
"(",
"self",
",",
"con",
")",
":",
"try",
":",
"if",
"self",
".",
"_reset",
"==",
"2",
":",
"con",
".",
"reset",
"(",
")",
"else",
":",
"if",
"self",
".",
"_reset",
"or",
"con",
".",
"_transaction",
":",
"try",
":",
"con",
".",
... | Put a connection back into the pool cache. | [
"Put",
"a",
"connection",
"back",
"into",
"the",
"pool",
"cache",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L216-L231 | train |
Cito/DBUtils | DBUtils/PooledPg.py | PooledPgConnection.reopen | def reopen(self):
"""Reopen the pooled connection."""
# If the connection is already back in the pool,
# get another connection from the pool,
# otherwise reopen the underlying connection.
if self._con:
self._con.reopen()
else:
self._con = self._po... | python | def reopen(self):
"""Reopen the pooled connection."""
# If the connection is already back in the pool,
# get another connection from the pool,
# otherwise reopen the underlying connection.
if self._con:
self._con.reopen()
else:
self._con = self._po... | [
"def",
"reopen",
"(",
"self",
")",
":",
"if",
"self",
".",
"_con",
":",
"self",
".",
"_con",
".",
"reopen",
"(",
")",
"else",
":",
"self",
".",
"_con",
"=",
"self",
".",
"_pool",
".",
"connection",
"(",
")"
] | Reopen the pooled connection. | [
"Reopen",
"the",
"pooled",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/PooledPg.py#L278-L286 | train |
Cito/DBUtils | DBUtils/SteadyPg.py | SteadyPgConnection.reopen | def reopen(self):
"""Reopen the tough connection.
It will not complain if the connection cannot be reopened.
"""
try:
self._con.reopen()
except Exception:
if self._transcation:
self._transaction = False
try:
... | python | def reopen(self):
"""Reopen the tough connection.
It will not complain if the connection cannot be reopened.
"""
try:
self._con.reopen()
except Exception:
if self._transcation:
self._transaction = False
try:
... | [
"def",
"reopen",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_con",
".",
"reopen",
"(",
")",
"except",
"Exception",
":",
"if",
"self",
".",
"_transcation",
":",
"self",
".",
"_transaction",
"=",
"False",
"try",
":",
"self",
".",
"_con",
".",
"... | Reopen the tough connection.
It will not complain if the connection cannot be reopened. | [
"Reopen",
"the",
"tough",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L188-L207 | train |
Cito/DBUtils | DBUtils/SteadyPg.py | SteadyPgConnection.reset | def reset(self):
"""Reset the tough connection.
If a reset is not possible, tries to reopen the connection.
It will not complain if the connection is already closed.
"""
try:
self._con.reset()
self._transaction = False
self._setsession()
... | python | def reset(self):
"""Reset the tough connection.
If a reset is not possible, tries to reopen the connection.
It will not complain if the connection is already closed.
"""
try:
self._con.reset()
self._transaction = False
self._setsession()
... | [
"def",
"reset",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_con",
".",
"reset",
"(",
")",
"self",
".",
"_transaction",
"=",
"False",
"self",
".",
"_setsession",
"(",
")",
"self",
".",
"_usage",
"=",
"0",
"except",
"Exception",
":",
"try",
":"... | Reset the tough connection.
If a reset is not possible, tries to reopen the connection.
It will not complain if the connection is already closed. | [
"Reset",
"the",
"tough",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L209-L228 | train |
Cito/DBUtils | DBUtils/SteadyPg.py | SteadyPgConnection._get_tough_method | def _get_tough_method(self, method):
"""Return a "tough" version of a connection class method.
The tough version checks whether the connection is bad (lost)
and automatically and transparently tries to reset the connection
if this is the case (for instance, the database has been restart... | python | def _get_tough_method(self, method):
"""Return a "tough" version of a connection class method.
The tough version checks whether the connection is bad (lost)
and automatically and transparently tries to reset the connection
if this is the case (for instance, the database has been restart... | [
"def",
"_get_tough_method",
"(",
"self",
",",
"method",
")",
":",
"def",
"tough_method",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"transaction",
"=",
"self",
".",
"_transaction",
"if",
"not",
"transaction",
":",
"try",
":",
"if",
"not",
"self",
... | Return a "tough" version of a connection class method.
The tough version checks whether the connection is bad (lost)
and automatically and transparently tries to reset the connection
if this is the case (for instance, the database has been restarted). | [
"Return",
"a",
"tough",
"version",
"of",
"a",
"connection",
"class",
"method",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyPg.py#L283-L315 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | connect | def connect(
creator, maxusage=None, setsession=None,
failures=None, ping=1, closeable=True, *args, **kwargs):
"""A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 c... | python | def connect(
creator, maxusage=None, setsession=None,
failures=None, ping=1, closeable=True, *args, **kwargs):
"""A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 c... | [
"def",
"connect",
"(",
"creator",
",",
"maxusage",
"=",
"None",
",",
"setsession",
"=",
"None",
",",
"failures",
"=",
"None",
",",
"ping",
"=",
"1",
",",
"closeable",
"=",
"True",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"SteadyDBCo... | A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 compliant database module
maxusage: maximum usage limit for the underlying DB-API 2 connection
(number of database operatio... | [
"A",
"tough",
"version",
"of",
"the",
"connection",
"constructor",
"of",
"a",
"DB",
"-",
"API",
"2",
"module",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L111-L139 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection._create | def _create(self):
"""Create a new connection using the creator function."""
con = self._creator(*self._args, **self._kwargs)
try:
try:
if self._dbapi.connect != self._creator:
raise AttributeError
except AttributeError:
... | python | def _create(self):
"""Create a new connection using the creator function."""
con = self._creator(*self._args, **self._kwargs)
try:
try:
if self._dbapi.connect != self._creator:
raise AttributeError
except AttributeError:
... | [
"def",
"_create",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"_creator",
"(",
"*",
"self",
".",
"_args",
",",
"**",
"self",
".",
"_kwargs",
")",
"try",
":",
"try",
":",
"if",
"self",
".",
"_dbapi",
".",
"connect",
"!=",
"self",
".",
"_creato... | Create a new connection using the creator function. | [
"Create",
"a",
"new",
"connection",
"using",
"the",
"creator",
"function",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L209-L296 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection._store | def _store(self, con):
"""Store a database connection for subsequent use."""
self._con = con
self._transaction = False
self._closed = False
self._usage = 0 | python | def _store(self, con):
"""Store a database connection for subsequent use."""
self._con = con
self._transaction = False
self._closed = False
self._usage = 0 | [
"def",
"_store",
"(",
"self",
",",
"con",
")",
":",
"self",
".",
"_con",
"=",
"con",
"self",
".",
"_transaction",
"=",
"False",
"self",
".",
"_closed",
"=",
"False",
"self",
".",
"_usage",
"=",
"0"
] | Store a database connection for subsequent use. | [
"Store",
"a",
"database",
"connection",
"for",
"subsequent",
"use",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L308-L313 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection._reset | def _reset(self, force=False):
"""Reset a tough connection.
Rollback if forced or the connection was in a transaction.
"""
if not self._closed and (force or self._transaction):
try:
self.rollback()
except Exception:
pass | python | def _reset(self, force=False):
"""Reset a tough connection.
Rollback if forced or the connection was in a transaction.
"""
if not self._closed and (force or self._transaction):
try:
self.rollback()
except Exception:
pass | [
"def",
"_reset",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_closed",
"and",
"(",
"force",
"or",
"self",
".",
"_transaction",
")",
":",
"try",
":",
"self",
".",
"rollback",
"(",
")",
"except",
"Exception",
":",
"p... | Reset a tough connection.
Rollback if forced or the connection was in a transaction. | [
"Reset",
"a",
"tough",
"connection",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L330-L340 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection.begin | def begin(self, *args, **kwargs):
"""Indicate the beginning of a transaction.
During a transaction, connections won't be transparently
replaced, and all errors will be raised to the application.
If the underlying driver supports this method, it will be called
with the given par... | python | def begin(self, *args, **kwargs):
"""Indicate the beginning of a transaction.
During a transaction, connections won't be transparently
replaced, and all errors will be raised to the application.
If the underlying driver supports this method, it will be called
with the given par... | [
"def",
"begin",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"_transaction",
"=",
"True",
"try",
":",
"begin",
"=",
"self",
".",
"_con",
".",
"begin",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"begin",
"(",
... | Indicate the beginning of a transaction.
During a transaction, connections won't be transparently
replaced, and all errors will be raised to the application.
If the underlying driver supports this method, it will be called
with the given parameters (e.g. for distributed transactions). | [
"Indicate",
"the",
"beginning",
"of",
"a",
"transaction",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L409-L425 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection.commit | def commit(self):
"""Commit any pending transaction."""
self._transaction = False
try:
self._con.commit()
except self._failures as error: # cannot commit
try: # try to reopen the connection
con = self._create()
except Exception:
... | python | def commit(self):
"""Commit any pending transaction."""
self._transaction = False
try:
self._con.commit()
except self._failures as error: # cannot commit
try: # try to reopen the connection
con = self._create()
except Exception:
... | [
"def",
"commit",
"(",
"self",
")",
":",
"self",
".",
"_transaction",
"=",
"False",
"try",
":",
"self",
".",
"_con",
".",
"commit",
"(",
")",
"except",
"self",
".",
"_failures",
"as",
"error",
":",
"try",
":",
"con",
"=",
"self",
".",
"_create",
"("... | Commit any pending transaction. | [
"Commit",
"any",
"pending",
"transaction",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L427-L440 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBConnection.cancel | def cancel(self):
"""Cancel a long-running transaction.
If the underlying driver supports this method, it will be called.
"""
self._transaction = False
try:
cancel = self._con.cancel
except AttributeError:
pass
else:
cancel() | python | def cancel(self):
"""Cancel a long-running transaction.
If the underlying driver supports this method, it will be called.
"""
self._transaction = False
try:
cancel = self._con.cancel
except AttributeError:
pass
else:
cancel() | [
"def",
"cancel",
"(",
"self",
")",
":",
"self",
".",
"_transaction",
"=",
"False",
"try",
":",
"cancel",
"=",
"self",
".",
"_con",
".",
"cancel",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"cancel",
"(",
")"
] | Cancel a long-running transaction.
If the underlying driver supports this method, it will be called. | [
"Cancel",
"a",
"long",
"-",
"running",
"transaction",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L457-L469 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBCursor._setsizes | def _setsizes(self, cursor=None):
"""Set stored input and output sizes for cursor execution."""
if cursor is None:
cursor = self._cursor
if self._inputsizes:
cursor.setinputsizes(self._inputsizes)
for column, size in self._outputsizes.items():
if colum... | python | def _setsizes(self, cursor=None):
"""Set stored input and output sizes for cursor execution."""
if cursor is None:
cursor = self._cursor
if self._inputsizes:
cursor.setinputsizes(self._inputsizes)
for column, size in self._outputsizes.items():
if colum... | [
"def",
"_setsizes",
"(",
"self",
",",
"cursor",
"=",
"None",
")",
":",
"if",
"cursor",
"is",
"None",
":",
"cursor",
"=",
"self",
".",
"_cursor",
"if",
"self",
".",
"_inputsizes",
":",
"cursor",
".",
"setinputsizes",
"(",
"self",
".",
"_inputsizes",
")"... | Set stored input and output sizes for cursor execution. | [
"Set",
"stored",
"input",
"and",
"output",
"sizes",
"for",
"cursor",
"execution",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L564-L574 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBCursor.close | def close(self):
"""Close the tough cursor.
It will not complain if you close it more than once.
"""
if not self._closed:
try:
self._cursor.close()
except Exception:
pass
self._closed = True | python | def close(self):
"""Close the tough cursor.
It will not complain if you close it more than once.
"""
if not self._closed:
try:
self._cursor.close()
except Exception:
pass
self._closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"try",
":",
"self",
".",
"_cursor",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"_closed",
"=",
"True"
] | Close the tough cursor.
It will not complain if you close it more than once. | [
"Close",
"the",
"tough",
"cursor",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L576-L587 | train |
Cito/DBUtils | DBUtils/SteadyDB.py | SteadyDBCursor._get_tough_method | def _get_tough_method(self, name):
"""Return a "tough" version of the given cursor method."""
def tough_method(*args, **kwargs):
execute = name.startswith('execute')
con = self._con
transaction = con._transaction
if not transaction:
con._pi... | python | def _get_tough_method(self, name):
"""Return a "tough" version of the given cursor method."""
def tough_method(*args, **kwargs):
execute = name.startswith('execute')
con = self._con
transaction = con._transaction
if not transaction:
con._pi... | [
"def",
"_get_tough_method",
"(",
"self",
",",
"name",
")",
":",
"def",
"tough_method",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"execute",
"=",
"name",
".",
"startswith",
"(",
"'execute'",
")",
"con",
"=",
"self",
".",
"_con",
"transaction",
"=... | Return a "tough" version of the given cursor method. | [
"Return",
"a",
"tough",
"version",
"of",
"the",
"given",
"cursor",
"method",
"."
] | 90e8825e038f08c82044b8e50831480175fa026a | https://github.com/Cito/DBUtils/blob/90e8825e038f08c82044b8e50831480175fa026a/DBUtils/SteadyDB.py#L589-L690 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/tokenize.py | train_punkt | def train_punkt(ctx, input, output, abbr, colloc):
"""Train Punkt sentence splitter using sentences in input."""
click.echo('chemdataextractor.tokenize.train_punkt')
import pickle
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktTrainer
punkt = PunktTrainer()
# Set these to true to i... | python | def train_punkt(ctx, input, output, abbr, colloc):
"""Train Punkt sentence splitter using sentences in input."""
click.echo('chemdataextractor.tokenize.train_punkt')
import pickle
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktTrainer
punkt = PunktTrainer()
# Set these to true to i... | [
"def",
"train_punkt",
"(",
"ctx",
",",
"input",
",",
"output",
",",
"abbr",
",",
"colloc",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.tokenize.train_punkt'",
")",
"import",
"pickle",
"from",
"nltk",
".",
"tokenize",
".",
"punkt",
"import",
"Pun... | Train Punkt sentence splitter using sentences in input. | [
"Train",
"Punkt",
"sentence",
"splitter",
"using",
"sentences",
"in",
"input",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/tokenize.py#L36-L61 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/tokenize.py | sentences | def sentences(ctx, input, output):
"""Read input document, and output sentences."""
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for raw_sentence in eleme... | python | def sentences(ctx, input, output):
"""Read input document, and output sentences."""
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for raw_sentence in eleme... | [
"def",
"sentences",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"info",
"(",
"'chemdataextractor.read.elements'",
")",
"log",
".",
"info",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"doc",
"=",
"Document",
".",
"from_file",
"... | Read input document, and output sentences. | [
"Read",
"input",
"document",
"and",
"output",
"sentences",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/tokenize.py#L68-L77 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/tokenize.py | words | def words(ctx, input, output):
"""Read input document, and output words."""
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for sentence in element.sentences... | python | def words(ctx, input, output):
"""Read input document, and output words."""
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for sentence in element.sentences... | [
"def",
"words",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"info",
"(",
"'chemdataextractor.read.elements'",
")",
"log",
".",
"info",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"doc",
"=",
"Document",
".",
"from_file",
"(",
... | Read input document, and output words. | [
"Read",
"input",
"document",
"and",
"output",
"words",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/tokenize.py#L84-L93 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/cem.py | CemTagger._in_stoplist | def _in_stoplist(self, entity):
"""Return True if the entity is in the stoplist."""
start = 0
end = len(entity)
# Adjust boundaries to exclude disallowed prefixes/suffixes
for prefix in IGNORE_PREFIX:
if entity.startswith(prefix):
# print('%s removing ... | python | def _in_stoplist(self, entity):
"""Return True if the entity is in the stoplist."""
start = 0
end = len(entity)
# Adjust boundaries to exclude disallowed prefixes/suffixes
for prefix in IGNORE_PREFIX:
if entity.startswith(prefix):
# print('%s removing ... | [
"def",
"_in_stoplist",
"(",
"self",
",",
"entity",
")",
":",
"start",
"=",
"0",
"end",
"=",
"len",
"(",
"entity",
")",
"for",
"prefix",
"in",
"IGNORE_PREFIX",
":",
"if",
"entity",
".",
"startswith",
"(",
"prefix",
")",
":",
"start",
"+=",
"len",
"(",... | Return True if the entity is in the stoplist. | [
"Return",
"True",
"if",
"the",
"entity",
"is",
"in",
"the",
"stoplist",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/cem.py#L518-L544 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | _process_name | def _process_name(name):
"""Fix issues with Jochem names."""
# Unescape HTML entities
name = unescape(name)
# Remove bracketed stuff on the end
name = NG_RE.sub('', name).strip() # Nomenclature groups
name = END_RE.sub('', name).strip(', ') # Words
name = RATIO_RE.sub('', name).strip(', ... | python | def _process_name(name):
"""Fix issues with Jochem names."""
# Unescape HTML entities
name = unescape(name)
# Remove bracketed stuff on the end
name = NG_RE.sub('', name).strip() # Nomenclature groups
name = END_RE.sub('', name).strip(', ') # Words
name = RATIO_RE.sub('', name).strip(', ... | [
"def",
"_process_name",
"(",
"name",
")",
":",
"name",
"=",
"unescape",
"(",
"name",
")",
"name",
"=",
"NG_RE",
".",
"sub",
"(",
"''",
",",
"name",
")",
".",
"strip",
"(",
")",
"name",
"=",
"END_RE",
".",
"sub",
"(",
"''",
",",
"name",
")",
"."... | Fix issues with Jochem names. | [
"Fix",
"issues",
"with",
"Jochem",
"names",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L124-L154 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | _get_variants | def _get_variants(name):
"""Return variants of chemical name."""
names = [name]
oldname = name
# Map greek words to unicode characters
if DOT_GREEK_RE.search(name):
wordname = name
while True:
m = DOT_GREEK_RE.search(wordname)
if m:
wordname = ... | python | def _get_variants(name):
"""Return variants of chemical name."""
names = [name]
oldname = name
# Map greek words to unicode characters
if DOT_GREEK_RE.search(name):
wordname = name
while True:
m = DOT_GREEK_RE.search(wordname)
if m:
wordname = ... | [
"def",
"_get_variants",
"(",
"name",
")",
":",
"names",
"=",
"[",
"name",
"]",
"oldname",
"=",
"name",
"if",
"DOT_GREEK_RE",
".",
"search",
"(",
"name",
")",
":",
"wordname",
"=",
"name",
"while",
"True",
":",
"m",
"=",
"DOT_GREEK_RE",
".",
"search",
... | Return variants of chemical name. | [
"Return",
"variants",
"of",
"chemical",
"name",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L206-L252 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | prepare_jochem | def prepare_jochem(ctx, jochem, output, csoutput):
"""Process and filter jochem file to produce list of names for dictionary."""
click.echo('chemdataextractor.dict.prepare_jochem')
for i, line in enumerate(jochem):
print('JC%s' % i)
if line.startswith('TM '):
if line.endswith(' @... | python | def prepare_jochem(ctx, jochem, output, csoutput):
"""Process and filter jochem file to produce list of names for dictionary."""
click.echo('chemdataextractor.dict.prepare_jochem')
for i, line in enumerate(jochem):
print('JC%s' % i)
if line.startswith('TM '):
if line.endswith(' @... | [
"def",
"prepare_jochem",
"(",
"ctx",
",",
"jochem",
",",
"output",
",",
"csoutput",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.dict.prepare_jochem'",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"jochem",
")",
":",
"print",
"(",
"'JC... | Process and filter jochem file to produce list of names for dictionary. | [
"Process",
"and",
"filter",
"jochem",
"file",
"to",
"produce",
"list",
"of",
"names",
"for",
"dictionary",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L277-L290 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | prepare_include | def prepare_include(ctx, include, output):
"""Process and filter include file to produce list of names for dictionary."""
click.echo('chemdataextractor.dict.prepare_include')
for i, line in enumerate(include):
print('IN%s' % i)
for tokens in _make_tokens(line.strip()):
output.wri... | python | def prepare_include(ctx, include, output):
"""Process and filter include file to produce list of names for dictionary."""
click.echo('chemdataextractor.dict.prepare_include')
for i, line in enumerate(include):
print('IN%s' % i)
for tokens in _make_tokens(line.strip()):
output.wri... | [
"def",
"prepare_include",
"(",
"ctx",
",",
"include",
",",
"output",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.dict.prepare_include'",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"include",
")",
":",
"print",
"(",
"'IN%s'",
"%",
"i... | Process and filter include file to produce list of names for dictionary. | [
"Process",
"and",
"filter",
"include",
"file",
"to",
"produce",
"list",
"of",
"names",
"for",
"dictionary",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L297-L304 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | build | def build(ctx, inputs, output, cs):
"""Build chemical name dictionary."""
click.echo('chemdataextractor.dict.build')
dt = DictionaryTagger(lexicon=ChemLexicon(), case_sensitive=cs)
names = []
for input in inputs:
for line in input:
tokens = line.split()
names.append(t... | python | def build(ctx, inputs, output, cs):
"""Build chemical name dictionary."""
click.echo('chemdataextractor.dict.build')
dt = DictionaryTagger(lexicon=ChemLexicon(), case_sensitive=cs)
names = []
for input in inputs:
for line in input:
tokens = line.split()
names.append(t... | [
"def",
"build",
"(",
"ctx",
",",
"inputs",
",",
"output",
",",
"cs",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.dict.build'",
")",
"dt",
"=",
"DictionaryTagger",
"(",
"lexicon",
"=",
"ChemLexicon",
"(",
")",
",",
"case_sensitive",
"=",
"cs",
... | Build chemical name dictionary. | [
"Build",
"chemical",
"name",
"dictionary",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L312-L322 | train |
mcs07/ChemDataExtractor | chemdataextractor/reader/rsc.py | RscHtmlReader._parse_table_footnotes | def _parse_table_footnotes(self, fns, refs, specials):
"""Override to account for awkward RSC table footnotes."""
footnotes = []
for fn in fns:
footnote = self._parse_text(fn, refs=refs, specials=specials, element_cls=Footnote)[0]
footnote += Footnote('', id=fn.getpreviou... | python | def _parse_table_footnotes(self, fns, refs, specials):
"""Override to account for awkward RSC table footnotes."""
footnotes = []
for fn in fns:
footnote = self._parse_text(fn, refs=refs, specials=specials, element_cls=Footnote)[0]
footnote += Footnote('', id=fn.getpreviou... | [
"def",
"_parse_table_footnotes",
"(",
"self",
",",
"fns",
",",
"refs",
",",
"specials",
")",
":",
"footnotes",
"=",
"[",
"]",
"for",
"fn",
"in",
"fns",
":",
"footnote",
"=",
"self",
".",
"_parse_text",
"(",
"fn",
",",
"refs",
"=",
"refs",
",",
"speci... | Override to account for awkward RSC table footnotes. | [
"Override",
"to",
"account",
"for",
"awkward",
"RSC",
"table",
"footnotes",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/rsc.py#L44-L51 | train |
mcs07/ChemDataExtractor | scripts/melting_points.py | extract | def extract():
"""Extract melting points from patents."""
Paragraph.parsers = [CompoundParser(), ChemicalLabelParser(), MpParser()]
Table.parsers = []
patents = []
for root, dirs, files in os.walk('../examples/mp/grants'):
for filename in files:
if not filename.endswith('.xml'):
... | python | def extract():
"""Extract melting points from patents."""
Paragraph.parsers = [CompoundParser(), ChemicalLabelParser(), MpParser()]
Table.parsers = []
patents = []
for root, dirs, files in os.walk('../examples/mp/grants'):
for filename in files:
if not filename.endswith('.xml'):
... | [
"def",
"extract",
"(",
")",
":",
"Paragraph",
".",
"parsers",
"=",
"[",
"CompoundParser",
"(",
")",
",",
"ChemicalLabelParser",
"(",
")",
",",
"MpParser",
"(",
")",
"]",
"Table",
".",
"parsers",
"=",
"[",
"]",
"patents",
"=",
"[",
"]",
"for",
"root",... | Extract melting points from patents. | [
"Extract",
"melting",
"points",
"from",
"patents",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/scripts/melting_points.py#L40-L64 | train |
mcs07/ChemDataExtractor | scripts/melting_points.py | make_sdf | def make_sdf():
"""Produce SDF of ChemDataExtractor and Tetko sample melting points."""
# import numpy as np
# my_results_by_inchikey = defaultdict(list)
# result_dir = '../examples/mp/standardized_results'
# fout = open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'w')
# writer = ... | python | def make_sdf():
"""Produce SDF of ChemDataExtractor and Tetko sample melting points."""
# import numpy as np
# my_results_by_inchikey = defaultdict(list)
# result_dir = '../examples/mp/standardized_results'
# fout = open('../examples/mp/sdf/chemdataextractor-melting-points.sdf', 'w')
# writer = ... | [
"def",
"make_sdf",
"(",
")",
":",
"with",
"open",
"(",
"'../examples/mp/sdf/chemdataextractor-melting-points.sdf'",
",",
"'rb'",
")",
"as",
"f_in",
",",
"gzip",
".",
"open",
"(",
"'../examples/mp/sdf/chemdataextractor-melting-points.sdf.gz'",
",",
"'wb'",
")",
"as",
"... | Produce SDF of ChemDataExtractor and Tetko sample melting points. | [
"Produce",
"SDF",
"of",
"ChemDataExtractor",
"and",
"Tetko",
"sample",
"melting",
"points",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/scripts/melting_points.py#L555-L620 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/__init__.py | cli | def cli(ctx, verbose):
"""ChemDataExtractor command line interface."""
log.debug('ChemDataExtractor v%s' % __version__)
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
logging.getLogger('requests').setLevel(logging.WARN)
ctx.obj = {} | python | def cli(ctx, verbose):
"""ChemDataExtractor command line interface."""
log.debug('ChemDataExtractor v%s' % __version__)
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
logging.getLogger('requests').setLevel(logging.WARN)
ctx.obj = {} | [
"def",
"cli",
"(",
"ctx",
",",
"verbose",
")",
":",
"log",
".",
"debug",
"(",
"'ChemDataExtractor v%s'",
"%",
"__version__",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"verbose",
"else",
"logging",
".",
"INFO",
... | ChemDataExtractor command line interface. | [
"ChemDataExtractor",
"command",
"line",
"interface",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L34-L39 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/__init__.py | extract | def extract(ctx, input, output):
"""Run ChemDataExtractor on a document."""
log.info('chemdataextractor.extract')
log.info('Reading %s' % input.name)
doc = Document.from_file(input, fname=input.name)
records = [record.serialize(primitive=True) for record in doc.records]
jsonstring = json.dumps(r... | python | def extract(ctx, input, output):
"""Run ChemDataExtractor on a document."""
log.info('chemdataextractor.extract')
log.info('Reading %s' % input.name)
doc = Document.from_file(input, fname=input.name)
records = [record.serialize(primitive=True) for record in doc.records]
jsonstring = json.dumps(r... | [
"def",
"extract",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"info",
"(",
"'chemdataextractor.extract'",
")",
"log",
".",
"info",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"doc",
"=",
"Document",
".",
"from_file",
"(",
"i... | Run ChemDataExtractor on a document. | [
"Run",
"ChemDataExtractor",
"on",
"a",
"document",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L46-L53 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/__init__.py | read | def read(ctx, input, output):
"""Output processed document elements."""
log.info('chemdataextractor.read')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
output.write(u'%s : %s\n=====\n' % (element.__class__.__name__, six.text_type(element))) | python | def read(ctx, input, output):
"""Output processed document elements."""
log.info('chemdataextractor.read')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
output.write(u'%s : %s\n=====\n' % (element.__class__.__name__, six.text_type(element))) | [
"def",
"read",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"info",
"(",
"'chemdataextractor.read'",
")",
"log",
".",
"info",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"doc",
"=",
"Document",
".",
"from_file",
"(",
"input",... | Output processed document elements. | [
"Output",
"processed",
"document",
"elements",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/__init__.py#L60-L66 | train |
mcs07/ChemDataExtractor | chemdataextractor/text/chem.py | extract_smiles | def extract_smiles(s):
"""Return a list of SMILES identifiers extracted from the string."""
# TODO: This still gets a lot of false positives.
smiles = []
for t in s.split():
if len(t) > 2 and SMILES_RE.match(t) and not t.endswith('.') and bracket_level(t) == 0:
smiles.append(t)
r... | python | def extract_smiles(s):
"""Return a list of SMILES identifiers extracted from the string."""
# TODO: This still gets a lot of false positives.
smiles = []
for t in s.split():
if len(t) > 2 and SMILES_RE.match(t) and not t.endswith('.') and bracket_level(t) == 0:
smiles.append(t)
r... | [
"def",
"extract_smiles",
"(",
"s",
")",
":",
"smiles",
"=",
"[",
"]",
"for",
"t",
"in",
"s",
".",
"split",
"(",
")",
":",
"if",
"len",
"(",
"t",
")",
">",
"2",
"and",
"SMILES_RE",
".",
"match",
"(",
"t",
")",
"and",
"not",
"t",
".",
"endswith... | Return a list of SMILES identifiers extracted from the string. | [
"Return",
"a",
"list",
"of",
"SMILES",
"identifiers",
"extracted",
"from",
"the",
"string",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/chem.py#L155-L162 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName.could_be | def could_be(self, other):
"""Return True if the other PersonName is not explicitly inconsistent."""
# TODO: Some suffix and title differences should be allowed
if type(other) is not type(self):
return NotImplemented
if self == other:
return True
for attr ... | python | def could_be(self, other):
"""Return True if the other PersonName is not explicitly inconsistent."""
# TODO: Some suffix and title differences should be allowed
if type(other) is not type(self):
return NotImplemented
if self == other:
return True
for attr ... | [
"def",
"could_be",
"(",
"self",
",",
"other",
")",
":",
"if",
"type",
"(",
"other",
")",
"is",
"not",
"type",
"(",
"self",
")",
":",
"return",
"NotImplemented",
"if",
"self",
"==",
"other",
":",
"return",
"True",
"for",
"attr",
"in",
"[",
"'title'",
... | Return True if the other PersonName is not explicitly inconsistent. | [
"Return",
"True",
"if",
"the",
"other",
"PersonName",
"is",
"not",
"explicitly",
"inconsistent",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L125-L145 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName._is_suffix | def _is_suffix(self, t):
"""Return true if t is a suffix."""
return t not in NOT_SUFFIX and (t.replace('.', '') in SUFFIXES or t.replace('.', '') in SUFFIXES_LOWER) | python | def _is_suffix(self, t):
"""Return true if t is a suffix."""
return t not in NOT_SUFFIX and (t.replace('.', '') in SUFFIXES or t.replace('.', '') in SUFFIXES_LOWER) | [
"def",
"_is_suffix",
"(",
"self",
",",
"t",
")",
":",
"return",
"t",
"not",
"in",
"NOT_SUFFIX",
"and",
"(",
"t",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"in",
"SUFFIXES",
"or",
"t",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"in",
"SUFFIXES_... | Return true if t is a suffix. | [
"Return",
"true",
"if",
"t",
"is",
"a",
"suffix",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L170-L172 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName._tokenize | def _tokenize(self, comps):
"""Split name on spaces, unless inside curly brackets or quotes."""
ps = []
for comp in comps:
ps.extend([c.strip(' ,') for c in re.split(r'\s+(?=[^{}]*(?:\{|$))', comp)])
return [p for p in ps if p] | python | def _tokenize(self, comps):
"""Split name on spaces, unless inside curly brackets or quotes."""
ps = []
for comp in comps:
ps.extend([c.strip(' ,') for c in re.split(r'\s+(?=[^{}]*(?:\{|$))', comp)])
return [p for p in ps if p] | [
"def",
"_tokenize",
"(",
"self",
",",
"comps",
")",
":",
"ps",
"=",
"[",
"]",
"for",
"comp",
"in",
"comps",
":",
"ps",
".",
"extend",
"(",
"[",
"c",
".",
"strip",
"(",
"' ,'",
")",
"for",
"c",
"in",
"re",
".",
"split",
"(",
"r'\\s+(?=[^{}]*(?:\\{... | Split name on spaces, unless inside curly brackets or quotes. | [
"Split",
"name",
"on",
"spaces",
"unless",
"inside",
"curly",
"brackets",
"or",
"quotes",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L174-L179 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName._clean | def _clean(self, t, capitalize=None):
"""Convert to normalized unicode and strip trailing full stops."""
if self._from_bibtex:
t = latex_to_unicode(t, capitalize=capitalize)
t = ' '.join([el.rstrip('.') if el.count('.') == 1 else el for el in t.split()])
return t | python | def _clean(self, t, capitalize=None):
"""Convert to normalized unicode and strip trailing full stops."""
if self._from_bibtex:
t = latex_to_unicode(t, capitalize=capitalize)
t = ' '.join([el.rstrip('.') if el.count('.') == 1 else el for el in t.split()])
return t | [
"def",
"_clean",
"(",
"self",
",",
"t",
",",
"capitalize",
"=",
"None",
")",
":",
"if",
"self",
".",
"_from_bibtex",
":",
"t",
"=",
"latex_to_unicode",
"(",
"t",
",",
"capitalize",
"=",
"capitalize",
")",
"t",
"=",
"' '",
".",
"join",
"(",
"[",
"el... | Convert to normalized unicode and strip trailing full stops. | [
"Convert",
"to",
"normalized",
"unicode",
"and",
"strip",
"trailing",
"full",
"stops",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L181-L186 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/person.py | PersonName._strip | def _strip(self, tokens, criteria, prop, rev=False):
"""Strip off contiguous tokens from the start or end of the list that meet the criteria."""
num = len(tokens)
res = []
for i, token in enumerate(reversed(tokens) if rev else tokens):
if criteria(token) and num > i + 1:
... | python | def _strip(self, tokens, criteria, prop, rev=False):
"""Strip off contiguous tokens from the start or end of the list that meet the criteria."""
num = len(tokens)
res = []
for i, token in enumerate(reversed(tokens) if rev else tokens):
if criteria(token) and num > i + 1:
... | [
"def",
"_strip",
"(",
"self",
",",
"tokens",
",",
"criteria",
",",
"prop",
",",
"rev",
"=",
"False",
")",
":",
"num",
"=",
"len",
"(",
"tokens",
")",
"res",
"=",
"[",
"]",
"for",
"i",
",",
"token",
"in",
"enumerate",
"(",
"reversed",
"(",
"tokens... | Strip off contiguous tokens from the start or end of the list that meet the criteria. | [
"Strip",
"off",
"contiguous",
"tokens",
"from",
"the",
"start",
"or",
"end",
"of",
"the",
"list",
"that",
"meet",
"the",
"criteria",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/person.py#L188-L199 | train |
mcs07/ChemDataExtractor | chemdataextractor/reader/markup.py | LxmlReader._parse_text | def _parse_text(self, el, refs=None, specials=None, element_cls=Paragraph):
"""Like _parse_element but ensure a single element."""
if specials is None:
specials = {}
if refs is None:
refs = {}
elements = self._parse_element_r(el, specials=specials, refs=refs, ele... | python | def _parse_text(self, el, refs=None, specials=None, element_cls=Paragraph):
"""Like _parse_element but ensure a single element."""
if specials is None:
specials = {}
if refs is None:
refs = {}
elements = self._parse_element_r(el, specials=specials, refs=refs, ele... | [
"def",
"_parse_text",
"(",
"self",
",",
"el",
",",
"refs",
"=",
"None",
",",
"specials",
"=",
"None",
",",
"element_cls",
"=",
"Paragraph",
")",
":",
"if",
"specials",
"is",
"None",
":",
"specials",
"=",
"{",
"}",
"if",
"refs",
"is",
"None",
":",
"... | Like _parse_element but ensure a single element. | [
"Like",
"_parse_element",
"but",
"ensure",
"a",
"single",
"element",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L112-L125 | train |
mcs07/ChemDataExtractor | chemdataextractor/reader/markup.py | LxmlReader._parse_reference | def _parse_reference(self, el):
"""Return reference ID from href or text content."""
if '#' in el.get('href', ''):
return [el.get('href').split('#', 1)[1]]
elif 'rid' in el.attrib:
return [el.attrib['rid']]
elif 'idref' in el.attrib:
return [el.attrib[... | python | def _parse_reference(self, el):
"""Return reference ID from href or text content."""
if '#' in el.get('href', ''):
return [el.get('href').split('#', 1)[1]]
elif 'rid' in el.attrib:
return [el.attrib['rid']]
elif 'idref' in el.attrib:
return [el.attrib[... | [
"def",
"_parse_reference",
"(",
"self",
",",
"el",
")",
":",
"if",
"'#'",
"in",
"el",
".",
"get",
"(",
"'href'",
",",
"''",
")",
":",
"return",
"[",
"el",
".",
"get",
"(",
"'href'",
")",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"[",
"1",
"]",... | Return reference ID from href or text content. | [
"Return",
"reference",
"ID",
"from",
"href",
"or",
"text",
"content",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L163-L172 | train |
mcs07/ChemDataExtractor | chemdataextractor/reader/markup.py | LxmlReader._is_inline | def _is_inline(self, element):
"""Return True if an element is inline."""
if element.tag not in {etree.Comment, etree.ProcessingInstruction} and element.tag.lower() in self.inline_elements:
return True
return False | python | def _is_inline(self, element):
"""Return True if an element is inline."""
if element.tag not in {etree.Comment, etree.ProcessingInstruction} and element.tag.lower() in self.inline_elements:
return True
return False | [
"def",
"_is_inline",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
".",
"tag",
"not",
"in",
"{",
"etree",
".",
"Comment",
",",
"etree",
".",
"ProcessingInstruction",
"}",
"and",
"element",
".",
"tag",
".",
"lower",
"(",
")",
"in",
"self",
"... | Return True if an element is inline. | [
"Return",
"True",
"if",
"an",
"element",
"is",
"inline",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/markup.py#L193-L197 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._next_token | def _next_token(self, skipws=True):
"""Increment _token to the next token and return it."""
self._token = next(self._tokens).group(0)
return self._next_token() if skipws and self._token.isspace() else self._token | python | def _next_token(self, skipws=True):
"""Increment _token to the next token and return it."""
self._token = next(self._tokens).group(0)
return self._next_token() if skipws and self._token.isspace() else self._token | [
"def",
"_next_token",
"(",
"self",
",",
"skipws",
"=",
"True",
")",
":",
"self",
".",
"_token",
"=",
"next",
"(",
"self",
".",
"_tokens",
")",
".",
"group",
"(",
"0",
")",
"return",
"self",
".",
"_next_token",
"(",
")",
"if",
"skipws",
"and",
"self... | Increment _token to the next token and return it. | [
"Increment",
"_token",
"to",
"the",
"next",
"token",
"and",
"return",
"it",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L65-L68 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_entry | def _parse_entry(self):
"""Parse an entry."""
entry_type = self._next_token().lower()
if entry_type == 'string':
self._parse_string()
elif entry_type not in ['comment', 'preamble']:
self._parse_record(entry_type) | python | def _parse_entry(self):
"""Parse an entry."""
entry_type = self._next_token().lower()
if entry_type == 'string':
self._parse_string()
elif entry_type not in ['comment', 'preamble']:
self._parse_record(entry_type) | [
"def",
"_parse_entry",
"(",
"self",
")",
":",
"entry_type",
"=",
"self",
".",
"_next_token",
"(",
")",
".",
"lower",
"(",
")",
"if",
"entry_type",
"==",
"'string'",
":",
"self",
".",
"_parse_string",
"(",
")",
"elif",
"entry_type",
"not",
"in",
"[",
"'... | Parse an entry. | [
"Parse",
"an",
"entry",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L80-L86 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_string | def _parse_string(self):
"""Parse a string entry and store the definition."""
if self._next_token() in ['{', '(']:
field = self._parse_field()
if field:
self.definitions[field[0]] = field[1] | python | def _parse_string(self):
"""Parse a string entry and store the definition."""
if self._next_token() in ['{', '(']:
field = self._parse_field()
if field:
self.definitions[field[0]] = field[1] | [
"def",
"_parse_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"_next_token",
"(",
")",
"in",
"[",
"'{'",
",",
"'('",
"]",
":",
"field",
"=",
"self",
".",
"_parse_field",
"(",
")",
"if",
"field",
":",
"self",
".",
"definitions",
"[",
"field",
"[... | Parse a string entry and store the definition. | [
"Parse",
"a",
"string",
"entry",
"and",
"store",
"the",
"definition",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L88-L93 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_record | def _parse_record(self, record_type):
"""Parse a record."""
if self._next_token() in ['{', '(']:
key = self._next_token()
self.records[key] = {
u'id': key,
u'type': record_type.lower()
}
if self._next_token() == ',':
... | python | def _parse_record(self, record_type):
"""Parse a record."""
if self._next_token() in ['{', '(']:
key = self._next_token()
self.records[key] = {
u'id': key,
u'type': record_type.lower()
}
if self._next_token() == ',':
... | [
"def",
"_parse_record",
"(",
"self",
",",
"record_type",
")",
":",
"if",
"self",
".",
"_next_token",
"(",
")",
"in",
"[",
"'{'",
",",
"'('",
"]",
":",
"key",
"=",
"self",
".",
"_next_token",
"(",
")",
"self",
".",
"records",
"[",
"key",
"]",
"=",
... | Parse a record. | [
"Parse",
"a",
"record",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L95-L121 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_field | def _parse_field(self):
"""Parse a Field."""
name = self._next_token()
if self._next_token() == '=':
value = self._parse_value()
return name, value | python | def _parse_field(self):
"""Parse a Field."""
name = self._next_token()
if self._next_token() == '=':
value = self._parse_value()
return name, value | [
"def",
"_parse_field",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"_next_token",
"(",
")",
"if",
"self",
".",
"_next_token",
"(",
")",
"==",
"'='",
":",
"value",
"=",
"self",
".",
"_parse_value",
"(",
")",
"return",
"name",
",",
"value"
] | Parse a Field. | [
"Parse",
"a",
"Field",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L123-L128 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser._parse_value | def _parse_value(self):
"""Parse a value. Digits, definitions, and the contents of double quotes or curly brackets."""
val = []
while True:
t = self._next_token()
if t == '"':
brac_counter = 0
while True:
t = self._next_... | python | def _parse_value(self):
"""Parse a value. Digits, definitions, and the contents of double quotes or curly brackets."""
val = []
while True:
t = self._next_token()
if t == '"':
brac_counter = 0
while True:
t = self._next_... | [
"def",
"_parse_value",
"(",
"self",
")",
":",
"val",
"=",
"[",
"]",
"while",
"True",
":",
"t",
"=",
"self",
".",
"_next_token",
"(",
")",
"if",
"t",
"==",
"'\"'",
":",
"brac_counter",
"=",
"0",
"while",
"True",
":",
"t",
"=",
"self",
".",
"_next_... | Parse a value. Digits, definitions, and the contents of double quotes or curly brackets. | [
"Parse",
"a",
"value",
".",
"Digits",
"definitions",
"and",
"the",
"contents",
"of",
"double",
"quotes",
"or",
"curly",
"brackets",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L130-L169 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser.parse_names | def parse_names(cls, names):
"""Parse a string of names separated by "and" like in a BibTeX authors field."""
names = [latex_to_unicode(n) for n in re.split(r'\sand\s(?=[^{}]*(?:\{|$))', names) if n]
return names | python | def parse_names(cls, names):
"""Parse a string of names separated by "and" like in a BibTeX authors field."""
names = [latex_to_unicode(n) for n in re.split(r'\sand\s(?=[^{}]*(?:\{|$))', names) if n]
return names | [
"def",
"parse_names",
"(",
"cls",
",",
"names",
")",
":",
"names",
"=",
"[",
"latex_to_unicode",
"(",
"n",
")",
"for",
"n",
"in",
"re",
".",
"split",
"(",
"r'\\sand\\s(?=[^{}]*(?:\\{|$))'",
",",
"names",
")",
"if",
"n",
"]",
"return",
"names"
] | Parse a string of names separated by "and" like in a BibTeX authors field. | [
"Parse",
"a",
"string",
"of",
"names",
"separated",
"by",
"and",
"like",
"in",
"a",
"BibTeX",
"authors",
"field",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L172-L175 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser.metadata | def metadata(self):
"""Return metadata for the parsed collection of records."""
auto = {u'records': self.size}
auto.update(self.meta)
return auto | python | def metadata(self):
"""Return metadata for the parsed collection of records."""
auto = {u'records': self.size}
auto.update(self.meta)
return auto | [
"def",
"metadata",
"(",
"self",
")",
":",
"auto",
"=",
"{",
"u'records'",
":",
"self",
".",
"size",
"}",
"auto",
".",
"update",
"(",
"self",
".",
"meta",
")",
"return",
"auto"
] | Return metadata for the parsed collection of records. | [
"Return",
"metadata",
"for",
"the",
"parsed",
"collection",
"of",
"records",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L188-L192 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/bibtex.py | BibtexParser.json | def json(self):
"""Return a list of records as a JSON string. Follows the BibJSON convention."""
return json.dumps(OrderedDict([('metadata', self.metadata), ('records', self.records.values())])) | python | def json(self):
"""Return a list of records as a JSON string. Follows the BibJSON convention."""
return json.dumps(OrderedDict([('metadata', self.metadata), ('records', self.records.values())])) | [
"def",
"json",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"OrderedDict",
"(",
"[",
"(",
"'metadata'",
",",
"self",
".",
"metadata",
")",
",",
"(",
"'records'",
",",
"self",
".",
"records",
".",
"values",
"(",
")",
")",
"]",
")",
... | Return a list of records as a JSON string. Follows the BibJSON convention. | [
"Return",
"a",
"list",
"of",
"records",
"as",
"a",
"JSON",
"string",
".",
"Follows",
"the",
"BibJSON",
"convention",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/bibtex.py#L195-L197 | train |
mcs07/ChemDataExtractor | chemdataextractor/config.py | Config._flush | def _flush(self):
"""Save the contents of data to the file on disk. You should not need to call this manually."""
d = os.path.dirname(self.path)
if not os.path.isdir(d):
os.makedirs(d)
with io.open(self.path, 'w', encoding='utf8') as f:
yaml.safe_dump(self._data, ... | python | def _flush(self):
"""Save the contents of data to the file on disk. You should not need to call this manually."""
d = os.path.dirname(self.path)
if not os.path.isdir(d):
os.makedirs(d)
with io.open(self.path, 'w', encoding='utf8') as f:
yaml.safe_dump(self._data, ... | [
"def",
"_flush",
"(",
"self",
")",
":",
"d",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"d",
")",
":",
"os",
".",
"makedirs",
"(",
"d",
")",
"with",
"io",
".",
"... | Save the contents of data to the file on disk. You should not need to call this manually. | [
"Save",
"the",
"contents",
"of",
"data",
"to",
"the",
"file",
"on",
"disk",
".",
"You",
"should",
"not",
"need",
"to",
"call",
"this",
"manually",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/config.py#L79-L85 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/abbrev.py | AbbreviationDetector._is_allowed_abbr | def _is_allowed_abbr(self, tokens):
"""Return True if text is an allowed abbreviation."""
if len(tokens) <= 2:
abbr_text = ''.join(tokens)
if self.abbr_min <= len(abbr_text) <= self.abbr_max and bracket_level(abbr_text) == 0:
if abbr_text[0].isalnum() and any(c.is... | python | def _is_allowed_abbr(self, tokens):
"""Return True if text is an allowed abbreviation."""
if len(tokens) <= 2:
abbr_text = ''.join(tokens)
if self.abbr_min <= len(abbr_text) <= self.abbr_max and bracket_level(abbr_text) == 0:
if abbr_text[0].isalnum() and any(c.is... | [
"def",
"_is_allowed_abbr",
"(",
"self",
",",
"tokens",
")",
":",
"if",
"len",
"(",
"tokens",
")",
"<=",
"2",
":",
"abbr_text",
"=",
"''",
".",
"join",
"(",
"tokens",
")",
"if",
"self",
".",
"abbr_min",
"<=",
"len",
"(",
"abbr_text",
")",
"<=",
"sel... | Return True if text is an allowed abbreviation. | [
"Return",
"True",
"if",
"text",
"is",
"an",
"allowed",
"abbreviation",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/abbrev.py#L43-L53 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/base.py | BaseScraper.name | def name(self):
"""A unique name for this scraper."""
return ''.join('_%s' % c if c.isupper() else c for c in self.__class__.__name__).strip('_').lower() | python | def name(self):
"""A unique name for this scraper."""
return ''.join('_%s' % c if c.isupper() else c for c in self.__class__.__name__).strip('_').lower() | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"''",
".",
"join",
"(",
"'_%s'",
"%",
"c",
"if",
"c",
".",
"isupper",
"(",
")",
"else",
"c",
"for",
"c",
"in",
"self",
".",
"__class__",
".",
"__name__",
")",
".",
"strip",
"(",
"'_'",
")",
".",
... | A unique name for this scraper. | [
"A",
"unique",
"name",
"for",
"this",
"scraper",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/base.py#L41-L43 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/base.py | BaseField._post_scrape | def _post_scrape(self, value, processor=None):
"""Apply processing to the scraped value."""
# Pass each value through the field's clean method
value = [self.process(v) for v in value]
# Filter None values
value = [v for v in value if v is not None]
# Pass each value throu... | python | def _post_scrape(self, value, processor=None):
"""Apply processing to the scraped value."""
# Pass each value through the field's clean method
value = [self.process(v) for v in value]
# Filter None values
value = [v for v in value if v is not None]
# Pass each value throu... | [
"def",
"_post_scrape",
"(",
"self",
",",
"value",
",",
"processor",
"=",
"None",
")",
":",
"value",
"=",
"[",
"self",
".",
"process",
"(",
"v",
")",
"for",
"v",
"in",
"value",
"]",
"value",
"=",
"[",
"v",
"for",
"v",
"in",
"value",
"if",
"v",
"... | Apply processing to the scraped value. | [
"Apply",
"processing",
"to",
"the",
"scraped",
"value",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/base.py#L197-L211 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/entity.py | Entity.scrape | def scrape(cls, selector, root, xpath=False):
"""Return EntityList for the given selector."""
log.debug('Called scrape classmethod with root: %s' % root)
roots = selector.xpath(root) if xpath else selector.css(root)
results = [cls(r) for r in roots]
return EntityList(*results) | python | def scrape(cls, selector, root, xpath=False):
"""Return EntityList for the given selector."""
log.debug('Called scrape classmethod with root: %s' % root)
roots = selector.xpath(root) if xpath else selector.css(root)
results = [cls(r) for r in roots]
return EntityList(*results) | [
"def",
"scrape",
"(",
"cls",
",",
"selector",
",",
"root",
",",
"xpath",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"'Called scrape classmethod with root: %s'",
"%",
"root",
")",
"roots",
"=",
"selector",
".",
"xpath",
"(",
"root",
")",
"if",
"xpa... | Return EntityList for the given selector. | [
"Return",
"EntityList",
"for",
"the",
"given",
"selector",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/entity.py#L95-L100 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/entity.py | Entity.serialize | def serialize(self):
"""Convert Entity to python dictionary."""
# Serialize fields to a dict
data = {}
for field_name in self:
value = self._values.get(field_name)
field = self.fields.get(field_name)
if value is not None:
if field.all:
... | python | def serialize(self):
"""Convert Entity to python dictionary."""
# Serialize fields to a dict
data = {}
for field_name in self:
value = self._values.get(field_name)
field = self.fields.get(field_name)
if value is not None:
if field.all:
... | [
"def",
"serialize",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"for",
"field_name",
"in",
"self",
":",
"value",
"=",
"self",
".",
"_values",
".",
"get",
"(",
"field_name",
")",
"field",
"=",
"self",
".",
"fields",
".",
"get",
"(",
"field_name",
... | Convert Entity to python dictionary. | [
"Convert",
"Entity",
"to",
"python",
"dictionary",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/entity.py#L102-L118 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/entity.py | Entity.to_json | def to_json(self, *args, **kwargs):
"""Convert Entity to JSON."""
return json.dumps(self.serialize(), *args, **kwargs) | python | def to_json(self, *args, **kwargs):
"""Convert Entity to JSON."""
return json.dumps(self.serialize(), *args, **kwargs) | [
"def",
"to_json",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"serialize",
"(",
")",
",",
"*",
"args",
",",
"**",
"kwargs",
")"
] | Convert Entity to JSON. | [
"Convert",
"Entity",
"to",
"JSON",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/entity.py#L120-L122 | train |
mcs07/ChemDataExtractor | chemdataextractor/doc/document.py | Document.from_file | def from_file(cls, f, fname=None, readers=None):
"""Create a Document from a file.
Usage::
with open('paper.html', 'rb') as f:
doc = Document.from_file(f)
.. note::
Always open files in binary mode by using the 'rb' parameter.
:param file|stri... | python | def from_file(cls, f, fname=None, readers=None):
"""Create a Document from a file.
Usage::
with open('paper.html', 'rb') as f:
doc = Document.from_file(f)
.. note::
Always open files in binary mode by using the 'rb' parameter.
:param file|stri... | [
"def",
"from_file",
"(",
"cls",
",",
"f",
",",
"fname",
"=",
"None",
",",
"readers",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"six",
".",
"string_types",
")",
":",
"f",
"=",
"io",
".",
"open",
"(",
"f",
",",
"'rb'",
")",
"if",
... | Create a Document from a file.
Usage::
with open('paper.html', 'rb') as f:
doc = Document.from_file(f)
.. note::
Always open files in binary mode by using the 'rb' parameter.
:param file|string f: A file-like object or path to a file.
:param s... | [
"Create",
"a",
"Document",
"from",
"a",
"file",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/document.py#L87-L107 | train |
mcs07/ChemDataExtractor | chemdataextractor/doc/document.py | Document.from_string | def from_string(cls, fstring, fname=None, readers=None):
"""Create a Document from a byte string containing the contents of a file.
Usage::
contents = open('paper.html', 'rb').read()
doc = Document.from_string(contents)
.. note::
This method expects a byte... | python | def from_string(cls, fstring, fname=None, readers=None):
"""Create a Document from a byte string containing the contents of a file.
Usage::
contents = open('paper.html', 'rb').read()
doc = Document.from_string(contents)
.. note::
This method expects a byte... | [
"def",
"from_string",
"(",
"cls",
",",
"fstring",
",",
"fname",
"=",
"None",
",",
"readers",
"=",
"None",
")",
":",
"if",
"readers",
"is",
"None",
":",
"from",
".",
".",
"reader",
"import",
"DEFAULT_READERS",
"readers",
"=",
"DEFAULT_READERS",
"if",
"isi... | Create a Document from a byte string containing the contents of a file.
Usage::
contents = open('paper.html', 'rb').read()
doc = Document.from_string(contents)
.. note::
This method expects a byte string, not a unicode string (in contrast to most methods in ChemDa... | [
"Create",
"a",
"Document",
"from",
"a",
"byte",
"string",
"containing",
"the",
"contents",
"of",
"a",
"file",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/document.py#L110-L143 | train |
mcs07/ChemDataExtractor | chemdataextractor/doc/document.py | Document.get_element_with_id | def get_element_with_id(self, id):
"""Return the element with the specified ID."""
# Should we maintain a hashmap of ids to make this more efficient? Probably overkill.
# TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)
return next((el for el in self.el... | python | def get_element_with_id(self, id):
"""Return the element with the specified ID."""
# Should we maintain a hashmap of ids to make this more efficient? Probably overkill.
# TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)
return next((el for el in self.el... | [
"def",
"get_element_with_id",
"(",
"self",
",",
"id",
")",
":",
"return",
"next",
"(",
"(",
"el",
"for",
"el",
"in",
"self",
".",
"elements",
"if",
"el",
".",
"id",
"==",
"id",
")",
",",
"None",
")"
] | Return the element with the specified ID. | [
"Return",
"the",
"element",
"with",
"the",
"specified",
"ID",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/document.py#L300-L304 | train |
mcs07/ChemDataExtractor | chemdataextractor/doc/document.py | Document.serialize | def serialize(self):
"""Convert Document to python dictionary."""
# Serialize fields to a dict
elements = []
for element in self.elements:
elements.append(element.serialize())
data = {'type': 'document', 'elements': elements}
return data | python | def serialize(self):
"""Convert Document to python dictionary."""
# Serialize fields to a dict
elements = []
for element in self.elements:
elements.append(element.serialize())
data = {'type': 'document', 'elements': elements}
return data | [
"def",
"serialize",
"(",
"self",
")",
":",
"elements",
"=",
"[",
"]",
"for",
"element",
"in",
"self",
".",
"elements",
":",
"elements",
".",
"append",
"(",
"element",
".",
"serialize",
"(",
")",
")",
"data",
"=",
"{",
"'type'",
":",
"'document'",
","... | Convert Document to python dictionary. | [
"Convert",
"Document",
"to",
"python",
"dictionary",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/document.py#L357-L364 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/xmp.py | XmpParser.parse | def parse(self, xmp):
"""Run parser and return a dictionary of all the parsed metadata."""
tree = etree.fromstring(xmp)
rdf_tree = tree.find(RDF_NS + 'RDF')
meta = defaultdict(dict)
for desc in rdf_tree.findall(RDF_NS + 'Description'):
for el in desc.getchildren():
... | python | def parse(self, xmp):
"""Run parser and return a dictionary of all the parsed metadata."""
tree = etree.fromstring(xmp)
rdf_tree = tree.find(RDF_NS + 'RDF')
meta = defaultdict(dict)
for desc in rdf_tree.findall(RDF_NS + 'Description'):
for el in desc.getchildren():
... | [
"def",
"parse",
"(",
"self",
",",
"xmp",
")",
":",
"tree",
"=",
"etree",
".",
"fromstring",
"(",
"xmp",
")",
"rdf_tree",
"=",
"tree",
".",
"find",
"(",
"RDF_NS",
"+",
"'RDF'",
")",
"meta",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"desc",
"in",
... | Run parser and return a dictionary of all the parsed metadata. | [
"Run",
"parser",
"and",
"return",
"a",
"dictionary",
"of",
"all",
"the",
"parsed",
"metadata",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/xmp.py#L60-L70 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/xmp.py | XmpParser._parse_tag | def _parse_tag(self, el):
"""Extract the namespace and tag from an element."""
ns = None
tag = el.tag
if tag[0] == '{':
ns, tag = tag[1:].split('}', 1)
if self.ns_map and ns in self.ns_map:
ns = self.ns_map[ns]
return ns, tag | python | def _parse_tag(self, el):
"""Extract the namespace and tag from an element."""
ns = None
tag = el.tag
if tag[0] == '{':
ns, tag = tag[1:].split('}', 1)
if self.ns_map and ns in self.ns_map:
ns = self.ns_map[ns]
return ns, tag | [
"def",
"_parse_tag",
"(",
"self",
",",
"el",
")",
":",
"ns",
"=",
"None",
"tag",
"=",
"el",
".",
"tag",
"if",
"tag",
"[",
"0",
"]",
"==",
"'{'",
":",
"ns",
",",
"tag",
"=",
"tag",
"[",
"1",
":",
"]",
".",
"split",
"(",
"'}'",
",",
"1",
")... | Extract the namespace and tag from an element. | [
"Extract",
"the",
"namespace",
"and",
"tag",
"from",
"an",
"element",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/xmp.py#L72-L80 | train |
mcs07/ChemDataExtractor | chemdataextractor/biblio/xmp.py | XmpParser._parse_value | def _parse_value(self, el):
"""Extract the metadata value from an element."""
if el.find(RDF_NS + 'Bag') is not None:
value = []
for li in el.findall(RDF_NS + 'Bag/' + RDF_NS + 'li'):
value.append(li.text)
elif el.find(RDF_NS + 'Seq') is not None:
... | python | def _parse_value(self, el):
"""Extract the metadata value from an element."""
if el.find(RDF_NS + 'Bag') is not None:
value = []
for li in el.findall(RDF_NS + 'Bag/' + RDF_NS + 'li'):
value.append(li.text)
elif el.find(RDF_NS + 'Seq') is not None:
... | [
"def",
"_parse_value",
"(",
"self",
",",
"el",
")",
":",
"if",
"el",
".",
"find",
"(",
"RDF_NS",
"+",
"'Bag'",
")",
"is",
"not",
"None",
":",
"value",
"=",
"[",
"]",
"for",
"li",
"in",
"el",
".",
"findall",
"(",
"RDF_NS",
"+",
"'Bag/'",
"+",
"R... | Extract the metadata value from an element. | [
"Extract",
"the",
"metadata",
"value",
"from",
"an",
"element",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/biblio/xmp.py#L82-L98 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/pub/rsc.py | parse_rsc_html | def parse_rsc_html(htmlstring):
"""Messy RSC HTML needs this special parser to fix problems before creating selector."""
converted = UnicodeDammit(htmlstring)
if not converted.unicode_markup:
raise UnicodeDecodeError('Failed to detect encoding, tried [%s]')
root = fromstring(htmlstring, parser=H... | python | def parse_rsc_html(htmlstring):
"""Messy RSC HTML needs this special parser to fix problems before creating selector."""
converted = UnicodeDammit(htmlstring)
if not converted.unicode_markup:
raise UnicodeDecodeError('Failed to detect encoding, tried [%s]')
root = fromstring(htmlstring, parser=H... | [
"def",
"parse_rsc_html",
"(",
"htmlstring",
")",
":",
"converted",
"=",
"UnicodeDammit",
"(",
"htmlstring",
")",
"if",
"not",
"converted",
".",
"unicode_markup",
":",
"raise",
"UnicodeDecodeError",
"(",
"'Failed to detect encoding, tried [%s]'",
")",
"root",
"=",
"f... | Messy RSC HTML needs this special parser to fix problems before creating selector. | [
"Messy",
"RSC",
"HTML",
"needs",
"this",
"special",
"parser",
"to",
"fix",
"problems",
"before",
"creating",
"selector",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/rsc.py#L242-L261 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/pub/rsc.py | replace_rsc_img_chars | def replace_rsc_img_chars(document):
"""Replace image characters with unicode equivalents."""
image_re = re.compile('http://www.rsc.org/images/entities/(?:h[23]+_)?(?:[ib]+_)?char_([0-9a-f]{4})(?:_([0-9a-f]{4}))?\.gif')
for img in document.xpath('.//img[starts-with(@src, "http://www.rsc.org/images/entities/... | python | def replace_rsc_img_chars(document):
"""Replace image characters with unicode equivalents."""
image_re = re.compile('http://www.rsc.org/images/entities/(?:h[23]+_)?(?:[ib]+_)?char_([0-9a-f]{4})(?:_([0-9a-f]{4}))?\.gif')
for img in document.xpath('.//img[starts-with(@src, "http://www.rsc.org/images/entities/... | [
"def",
"replace_rsc_img_chars",
"(",
"document",
")",
":",
"image_re",
"=",
"re",
".",
"compile",
"(",
"'http://www.rsc.org/images/entities/(?:h[23]+_)?(?:[ib]+_)?char_([0-9a-f]{4})(?:_([0-9a-f]{4}))?\\.gif'",
")",
"for",
"img",
"in",
"document",
".",
"xpath",
"(",
"'.//img... | Replace image characters with unicode equivalents. | [
"Replace",
"image",
"characters",
"with",
"unicode",
"equivalents",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/rsc.py#L264-L287 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/pub/rsc.py | space_references | def space_references(document):
"""Ensure a space around reference links, so there's a gap when they are removed."""
for ref in document.xpath('.//a/sup/span[@class="sup_ref"]'):
a = ref.getparent().getparent()
if a is not None:
atail = a.tail or ''
if not atail.startswit... | python | def space_references(document):
"""Ensure a space around reference links, so there's a gap when they are removed."""
for ref in document.xpath('.//a/sup/span[@class="sup_ref"]'):
a = ref.getparent().getparent()
if a is not None:
atail = a.tail or ''
if not atail.startswit... | [
"def",
"space_references",
"(",
"document",
")",
":",
"for",
"ref",
"in",
"document",
".",
"xpath",
"(",
"'.//a/sup/span[@class=\"sup_ref\"]'",
")",
":",
"a",
"=",
"ref",
".",
"getparent",
"(",
")",
".",
"getparent",
"(",
")",
"if",
"a",
"is",
"not",
"No... | Ensure a space around reference links, so there's a gap when they are removed. | [
"Ensure",
"a",
"space",
"around",
"reference",
"links",
"so",
"there",
"s",
"a",
"gap",
"when",
"they",
"are",
"removed",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/rsc.py#L290-L298 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/cluster.py | load | def load(ctx, input, output):
"""Read clusters from file and save to model file."""
log.debug('chemdataextractor.cluster.load')
import pickle
click.echo('Reading %s' % input.name)
clusters = {}
for line in input.readlines():
cluster, word, freq = line.split()
clusters[word] = clu... | python | def load(ctx, input, output):
"""Read clusters from file and save to model file."""
log.debug('chemdataextractor.cluster.load')
import pickle
click.echo('Reading %s' % input.name)
clusters = {}
for line in input.readlines():
cluster, word, freq = line.split()
clusters[word] = clu... | [
"def",
"load",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"debug",
"(",
"'chemdataextractor.cluster.load'",
")",
"import",
"pickle",
"click",
".",
"echo",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"clusters",
"=",
"{",
"}",... | Read clusters from file and save to model file. | [
"Read",
"clusters",
"from",
"file",
"and",
"save",
"to",
"model",
"file",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/cluster.py#L32-L41 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/pub/nlm.py | space_labels | def space_labels(document):
"""Ensure space around bold compound labels."""
for label in document.xpath('.//bold'):
# TODO: Make this more permissive to match chemical_label in parser
if not label.text or not re.match('^\(L?\d\d?[a-z]?\):?$', label.text, re.I):
continue
paren... | python | def space_labels(document):
"""Ensure space around bold compound labels."""
for label in document.xpath('.//bold'):
# TODO: Make this more permissive to match chemical_label in parser
if not label.text or not re.match('^\(L?\d\d?[a-z]?\):?$', label.text, re.I):
continue
paren... | [
"def",
"space_labels",
"(",
"document",
")",
":",
"for",
"label",
"in",
"document",
".",
"xpath",
"(",
"'.//bold'",
")",
":",
"if",
"not",
"label",
".",
"text",
"or",
"not",
"re",
".",
"match",
"(",
"'^\\(L?\\d\\d?[a-z]?\\):?$'",
",",
"label",
".",
"text... | Ensure space around bold compound labels. | [
"Ensure",
"space",
"around",
"bold",
"compound",
"labels",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/nlm.py#L34-L53 | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/pub/nlm.py | tidy_nlm_references | def tidy_nlm_references(document):
"""Remove punctuation around references like brackets, commas, hyphens."""
def strip_preceding(text):
stext = text.rstrip()
if stext.endswith('[') or stext.endswith('('):
#log.debug('%s -> %s' % (text, stext[:-1]))
return stext[:-1]
... | python | def tidy_nlm_references(document):
"""Remove punctuation around references like brackets, commas, hyphens."""
def strip_preceding(text):
stext = text.rstrip()
if stext.endswith('[') or stext.endswith('('):
#log.debug('%s -> %s' % (text, stext[:-1]))
return stext[:-1]
... | [
"def",
"tidy_nlm_references",
"(",
"document",
")",
":",
"def",
"strip_preceding",
"(",
"text",
")",
":",
"stext",
"=",
"text",
".",
"rstrip",
"(",
")",
"if",
"stext",
".",
"endswith",
"(",
"'['",
")",
"or",
"stext",
".",
"endswith",
"(",
"'('",
")",
... | Remove punctuation around references like brackets, commas, hyphens. | [
"Remove",
"punctuation",
"around",
"references",
"like",
"brackets",
"commas",
"hyphens",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/pub/nlm.py#L56-L91 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tokenize.py | regex_span_tokenize | def regex_span_tokenize(s, regex):
"""Return spans that identify tokens in s split using regex."""
left = 0
for m in re.finditer(regex, s, re.U):
right, next = m.span()
if right != 0:
yield left, right
left = next
yield left, len(s) | python | def regex_span_tokenize(s, regex):
"""Return spans that identify tokens in s split using regex."""
left = 0
for m in re.finditer(regex, s, re.U):
right, next = m.span()
if right != 0:
yield left, right
left = next
yield left, len(s) | [
"def",
"regex_span_tokenize",
"(",
"s",
",",
"regex",
")",
":",
"left",
"=",
"0",
"for",
"m",
"in",
"re",
".",
"finditer",
"(",
"regex",
",",
"s",
",",
"re",
".",
"U",
")",
":",
"right",
",",
"next",
"=",
"m",
".",
"span",
"(",
")",
"if",
"ri... | Return spans that identify tokens in s split using regex. | [
"Return",
"spans",
"that",
"identify",
"tokens",
"in",
"s",
"split",
"using",
"regex",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L70-L78 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tokenize.py | BaseTokenizer.tokenize | def tokenize(self, s):
"""Return a list of token strings from the given sentence.
:param string s: The sentence string to tokenize.
:rtype: iter(str)
"""
return [s[start:end] for start, end in self.span_tokenize(s)] | python | def tokenize(self, s):
"""Return a list of token strings from the given sentence.
:param string s: The sentence string to tokenize.
:rtype: iter(str)
"""
return [s[start:end] for start, end in self.span_tokenize(s)] | [
"def",
"tokenize",
"(",
"self",
",",
"s",
")",
":",
"return",
"[",
"s",
"[",
"start",
":",
"end",
"]",
"for",
"start",
",",
"end",
"in",
"self",
".",
"span_tokenize",
"(",
"s",
")",
"]"
] | Return a list of token strings from the given sentence.
:param string s: The sentence string to tokenize.
:rtype: iter(str) | [
"Return",
"a",
"list",
"of",
"token",
"strings",
"from",
"the",
"given",
"sentence",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L35-L41 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tokenize.py | SentenceTokenizer.span_tokenize | def span_tokenize(self, s):
"""Return a list of integer offsets that identify sentences in the given text.
:param string s: The text to tokenize into sentences.
:rtype: iter(tuple(int, int))
"""
if self._tokenizer is None:
self._tokenizer = load_model(self.model)
... | python | def span_tokenize(self, s):
"""Return a list of integer offsets that identify sentences in the given text.
:param string s: The text to tokenize into sentences.
:rtype: iter(tuple(int, int))
"""
if self._tokenizer is None:
self._tokenizer = load_model(self.model)
... | [
"def",
"span_tokenize",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"_tokenizer",
"is",
"None",
":",
"self",
".",
"_tokenizer",
"=",
"load_model",
"(",
"self",
".",
"model",
")",
"return",
"self",
".",
"_tokenizer",
".",
"span_tokenize",
"(",
"... | Return a list of integer offsets that identify sentences in the given text.
:param string s: The text to tokenize into sentences.
:rtype: iter(tuple(int, int)) | [
"Return",
"a",
"list",
"of",
"integer",
"offsets",
"that",
"identify",
"sentences",
"in",
"the",
"given",
"text",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L91-L101 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tokenize.py | WordTokenizer._split_span | def _split_span(self, span, index, length=0):
"""Split a span into two or three separate spans at certain indices."""
offset = span[1] + index if index < 0 else span[0] + index
# log.debug([(span[0], offset), (offset, offset + length), (offset + length, span[1])])
return [(span[0], offse... | python | def _split_span(self, span, index, length=0):
"""Split a span into two or three separate spans at certain indices."""
offset = span[1] + index if index < 0 else span[0] + index
# log.debug([(span[0], offset), (offset, offset + length), (offset + length, span[1])])
return [(span[0], offse... | [
"def",
"_split_span",
"(",
"self",
",",
"span",
",",
"index",
",",
"length",
"=",
"0",
")",
":",
"offset",
"=",
"span",
"[",
"1",
"]",
"+",
"index",
"if",
"index",
"<",
"0",
"else",
"span",
"[",
"0",
"]",
"+",
"index",
"return",
"[",
"(",
"span... | Split a span into two or three separate spans at certain indices. | [
"Split",
"a",
"span",
"into",
"two",
"or",
"three",
"separate",
"spans",
"at",
"certain",
"indices",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L247-L251 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tokenize.py | ChemWordTokenizer._closing_bracket_index | def _closing_bracket_index(self, text, bpair=('(', ')')):
"""Return the index of the closing bracket that matches the opening bracket at the start of the text."""
level = 1
for i, char in enumerate(text[1:]):
if char == bpair[0]:
level += 1
elif char == bp... | python | def _closing_bracket_index(self, text, bpair=('(', ')')):
"""Return the index of the closing bracket that matches the opening bracket at the start of the text."""
level = 1
for i, char in enumerate(text[1:]):
if char == bpair[0]:
level += 1
elif char == bp... | [
"def",
"_closing_bracket_index",
"(",
"self",
",",
"text",
",",
"bpair",
"=",
"(",
"'('",
",",
"')'",
")",
")",
":",
"level",
"=",
"1",
"for",
"i",
",",
"char",
"in",
"enumerate",
"(",
"text",
"[",
"1",
":",
"]",
")",
":",
"if",
"char",
"==",
"... | Return the index of the closing bracket that matches the opening bracket at the start of the text. | [
"Return",
"the",
"index",
"of",
"the",
"closing",
"bracket",
"that",
"matches",
"the",
"opening",
"bracket",
"at",
"the",
"start",
"of",
"the",
"text",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L535-L544 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tokenize.py | ChemWordTokenizer._opening_bracket_index | def _opening_bracket_index(self, text, bpair=('(', ')')):
"""Return the index of the opening bracket that matches the closing bracket at the end of the text."""
level = 1
for i, char in enumerate(reversed(text[:-1])):
if char == bpair[1]:
level += 1
elif c... | python | def _opening_bracket_index(self, text, bpair=('(', ')')):
"""Return the index of the opening bracket that matches the closing bracket at the end of the text."""
level = 1
for i, char in enumerate(reversed(text[:-1])):
if char == bpair[1]:
level += 1
elif c... | [
"def",
"_opening_bracket_index",
"(",
"self",
",",
"text",
",",
"bpair",
"=",
"(",
"'('",
",",
"')'",
")",
")",
":",
"level",
"=",
"1",
"for",
"i",
",",
"char",
"in",
"enumerate",
"(",
"reversed",
"(",
"text",
"[",
":",
"-",
"1",
"]",
")",
")",
... | Return the index of the opening bracket that matches the closing bracket at the end of the text. | [
"Return",
"the",
"index",
"of",
"the",
"opening",
"bracket",
"that",
"matches",
"the",
"closing",
"bracket",
"at",
"the",
"end",
"of",
"the",
"text",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L546-L555 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tokenize.py | ChemWordTokenizer._is_saccharide_arrow | def _is_saccharide_arrow(self, before, after):
"""Return True if the arrow is in a chemical name."""
if (before and after and before[-1].isdigit() and after[0].isdigit() and
before.rstrip('0123456789').endswith('(') and after.lstrip('0123456789').startswith(')-')):
return True
... | python | def _is_saccharide_arrow(self, before, after):
"""Return True if the arrow is in a chemical name."""
if (before and after and before[-1].isdigit() and after[0].isdigit() and
before.rstrip('0123456789').endswith('(') and after.lstrip('0123456789').startswith(')-')):
return True
... | [
"def",
"_is_saccharide_arrow",
"(",
"self",
",",
"before",
",",
"after",
")",
":",
"if",
"(",
"before",
"and",
"after",
"and",
"before",
"[",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
"and",
"after",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
"and",
... | Return True if the arrow is in a chemical name. | [
"Return",
"True",
"if",
"the",
"arrow",
"is",
"in",
"a",
"chemical",
"name",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L565-L571 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/evaluate.py | get_names | def get_names(cs):
"""Return list of every name."""
records = []
for c in cs:
records.extend(c.get('names', []))
return records | python | def get_names(cs):
"""Return list of every name."""
records = []
for c in cs:
records.extend(c.get('names', []))
return records | [
"def",
"get_names",
"(",
"cs",
")",
":",
"records",
"=",
"[",
"]",
"for",
"c",
"in",
"cs",
":",
"records",
".",
"extend",
"(",
"c",
".",
"get",
"(",
"'names'",
",",
"[",
"]",
")",
")",
"return",
"records"
] | Return list of every name. | [
"Return",
"list",
"of",
"every",
"name",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/evaluate.py#L75-L80 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/evaluate.py | get_labels | def get_labels(cs):
"""Return list of every label."""
records = []
for c in cs:
records.extend(c.get('labels', []))
return records | python | def get_labels(cs):
"""Return list of every label."""
records = []
for c in cs:
records.extend(c.get('labels', []))
return records | [
"def",
"get_labels",
"(",
"cs",
")",
":",
"records",
"=",
"[",
"]",
"for",
"c",
"in",
"cs",
":",
"records",
".",
"extend",
"(",
"c",
".",
"get",
"(",
"'labels'",
",",
"[",
"]",
")",
")",
"return",
"records"
] | Return list of every label. | [
"Return",
"list",
"of",
"every",
"label",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/evaluate.py#L83-L88 | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/evaluate.py | get_ids | def get_ids(cs):
"""Return chemical identifier records."""
records = []
for c in cs:
records.append({k: c[k] for k in c if k in {'names', 'labels'}})
return records | python | def get_ids(cs):
"""Return chemical identifier records."""
records = []
for c in cs:
records.append({k: c[k] for k in c if k in {'names', 'labels'}})
return records | [
"def",
"get_ids",
"(",
"cs",
")",
":",
"records",
"=",
"[",
"]",
"for",
"c",
"in",
"cs",
":",
"records",
".",
"append",
"(",
"{",
"k",
":",
"c",
"[",
"k",
"]",
"for",
"k",
"in",
"c",
"if",
"k",
"in",
"{",
"'names'",
",",
"'labels'",
"}",
"}... | Return chemical identifier records. | [
"Return",
"chemical",
"identifier",
"records",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/evaluate.py#L91-L96 | train |
mcs07/ChemDataExtractor | chemdataextractor/utils.py | memoized_property | def memoized_property(fget):
"""Decorator to create memoized properties."""
attr_name = '_{}'.format(fget.__name__)
@functools.wraps(fget)
def fget_memoized(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fget(self))
return getattr(self, attr_name)
retur... | python | def memoized_property(fget):
"""Decorator to create memoized properties."""
attr_name = '_{}'.format(fget.__name__)
@functools.wraps(fget)
def fget_memoized(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fget(self))
return getattr(self, attr_name)
retur... | [
"def",
"memoized_property",
"(",
"fget",
")",
":",
"attr_name",
"=",
"'_{}'",
".",
"format",
"(",
"fget",
".",
"__name__",
")",
"@",
"functools",
".",
"wraps",
"(",
"fget",
")",
"def",
"fget_memoized",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"("... | Decorator to create memoized properties. | [
"Decorator",
"to",
"create",
"memoized",
"properties",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/utils.py#L25-L34 | train |
mcs07/ChemDataExtractor | chemdataextractor/utils.py | memoize | def memoize(obj):
"""Decorator to create memoized functions, methods or classes."""
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
if args not in cache:
cache[args] = obj(*args, **kwargs)
return cache[args]
return memoizer | python | def memoize(obj):
"""Decorator to create memoized functions, methods or classes."""
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
if args not in cache:
cache[args] = obj(*args, **kwargs)
return cache[args]
return memoizer | [
"def",
"memoize",
"(",
"obj",
")",
":",
"cache",
"=",
"obj",
".",
"cache",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"obj",
")",
"def",
"memoizer",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"args",
"not",
"in",
"cache",
"... | Decorator to create memoized functions, methods or classes. | [
"Decorator",
"to",
"create",
"memoized",
"functions",
"methods",
"or",
"classes",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/utils.py#L37-L46 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tag.py | BaseTagger.evaluate | def evaluate(self, gold):
"""Evaluate the accuracy of this tagger using a gold standard corpus.
:param list(list(tuple(str, str))) gold: The list of tagged sentences to score the tagger on.
:returns: Tagger accuracy value.
:rtype: float
"""
tagged_sents = self.tag_sents(... | python | def evaluate(self, gold):
"""Evaluate the accuracy of this tagger using a gold standard corpus.
:param list(list(tuple(str, str))) gold: The list of tagged sentences to score the tagger on.
:returns: Tagger accuracy value.
:rtype: float
"""
tagged_sents = self.tag_sents(... | [
"def",
"evaluate",
"(",
"self",
",",
"gold",
")",
":",
"tagged_sents",
"=",
"self",
".",
"tag_sents",
"(",
"[",
"w",
"for",
"(",
"w",
",",
"t",
")",
"in",
"sent",
"]",
"for",
"sent",
"in",
"gold",
")",
"gold_tokens",
"=",
"sum",
"(",
"gold",
",",... | Evaluate the accuracy of this tagger using a gold standard corpus.
:param list(list(tuple(str, str))) gold: The list of tagged sentences to score the tagger on.
:returns: Tagger accuracy value.
:rtype: float | [
"Evaluate",
"the",
"accuracy",
"of",
"this",
"tagger",
"using",
"a",
"gold",
"standard",
"corpus",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L51-L62 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tag.py | AveragedPerceptron.predict | def predict(self, features):
"""Dot-product the features and current weights and return the best label."""
scores = defaultdict(float)
for feat in features:
if feat not in self.weights:
continue
weights = self.weights[feat]
for label, weight in... | python | def predict(self, features):
"""Dot-product the features and current weights and return the best label."""
scores = defaultdict(float)
for feat in features:
if feat not in self.weights:
continue
weights = self.weights[feat]
for label, weight in... | [
"def",
"predict",
"(",
"self",
",",
"features",
")",
":",
"scores",
"=",
"defaultdict",
"(",
"float",
")",
"for",
"feat",
"in",
"features",
":",
"if",
"feat",
"not",
"in",
"self",
".",
"weights",
":",
"continue",
"weights",
"=",
"self",
".",
"weights",... | Dot-product the features and current weights and return the best label. | [
"Dot",
"-",
"product",
"the",
"features",
"and",
"current",
"weights",
"and",
"return",
"the",
"best",
"label",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L141-L151 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tag.py | AveragedPerceptron.update | def update(self, truth, guess, features):
"""Update the feature weights."""
def upd_feat(c, f, w, v):
param = (f, c)
self._totals[param] += (self.i - self._tstamps[param]) * w
self._tstamps[param] = self.i
self.weights[f][c] = w + v
self.i += 1
... | python | def update(self, truth, guess, features):
"""Update the feature weights."""
def upd_feat(c, f, w, v):
param = (f, c)
self._totals[param] += (self.i - self._tstamps[param]) * w
self._tstamps[param] = self.i
self.weights[f][c] = w + v
self.i += 1
... | [
"def",
"update",
"(",
"self",
",",
"truth",
",",
"guess",
",",
"features",
")",
":",
"def",
"upd_feat",
"(",
"c",
",",
"f",
",",
"w",
",",
"v",
")",
":",
"param",
"=",
"(",
"f",
",",
"c",
")",
"self",
".",
"_totals",
"[",
"param",
"]",
"+=",
... | Update the feature weights. | [
"Update",
"the",
"feature",
"weights",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L153-L168 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tag.py | AveragedPerceptron.average_weights | def average_weights(self):
"""Average weights from all iterations."""
for feat, weights in self.weights.items():
new_feat_weights = {}
for clas, weight in weights.items():
param = (feat, clas)
total = self._totals[param]
total += (s... | python | def average_weights(self):
"""Average weights from all iterations."""
for feat, weights in self.weights.items():
new_feat_weights = {}
for clas, weight in weights.items():
param = (feat, clas)
total = self._totals[param]
total += (s... | [
"def",
"average_weights",
"(",
"self",
")",
":",
"for",
"feat",
",",
"weights",
"in",
"self",
".",
"weights",
".",
"items",
"(",
")",
":",
"new_feat_weights",
"=",
"{",
"}",
"for",
"clas",
",",
"weight",
"in",
"weights",
".",
"items",
"(",
")",
":",
... | Average weights from all iterations. | [
"Average",
"weights",
"from",
"all",
"iterations",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L170-L182 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tag.py | AveragedPerceptron.save | def save(self, path):
"""Save the pickled model weights."""
with io.open(path, 'wb') as fout:
return pickle.dump(dict(self.weights), fout) | python | def save(self, path):
"""Save the pickled model weights."""
with io.open(path, 'wb') as fout:
return pickle.dump(dict(self.weights), fout) | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"fout",
":",
"return",
"pickle",
".",
"dump",
"(",
"dict",
"(",
"self",
".",
"weights",
")",
",",
"fout",
")"
] | Save the pickled model weights. | [
"Save",
"the",
"pickled",
"model",
"weights",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L184-L187 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tag.py | AveragedPerceptron.load | def load(self, path):
"""Load the pickled model weights."""
with io.open(path, 'rb') as fin:
self.weights = pickle.load(fin) | python | def load(self, path):
"""Load the pickled model weights."""
with io.open(path, 'rb') as fin:
self.weights = pickle.load(fin) | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"fin",
":",
"self",
".",
"weights",
"=",
"pickle",
".",
"load",
"(",
"fin",
")"
] | Load the pickled model weights. | [
"Load",
"the",
"pickled",
"model",
"weights",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L189-L192 | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tag.py | ApTagger.train | def train(self, sentences, nr_iter=5):
"""Train a model from sentences.
:param sentences: A list of sentences, each of which is a list of (token, tag) tuples.
:param nr_iter: Number of training iterations.
"""
self._make_tagdict(sentences)
self.perceptron.classes = self.... | python | def train(self, sentences, nr_iter=5):
"""Train a model from sentences.
:param sentences: A list of sentences, each of which is a list of (token, tag) tuples.
:param nr_iter: Number of training iterations.
"""
self._make_tagdict(sentences)
self.perceptron.classes = self.... | [
"def",
"train",
"(",
"self",
",",
"sentences",
",",
"nr_iter",
"=",
"5",
")",
":",
"self",
".",
"_make_tagdict",
"(",
"sentences",
")",
"self",
".",
"perceptron",
".",
"classes",
"=",
"self",
".",
"classes",
"for",
"iter_",
"in",
"range",
"(",
"nr_iter... | Train a model from sentences.
:param sentences: A list of sentences, each of which is a list of (token, tag) tuples.
:param nr_iter: Number of training iterations. | [
"Train",
"a",
"model",
"from",
"sentences",
"."
] | 349a3bea965f2073141d62043b89319222e46af1 | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L235-L261 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.