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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.mode_readable | def mode_readable(self):
"""Return a readable representation of the mode.."""
ret = ""
mode = self._raw_mode
if mode.MANUAL:
ret = "manual"
if self.target_temperature < self.min_temp:
ret += " off"
elif self.target_temperature >= self.... | python | def mode_readable(self):
"""Return a readable representation of the mode.."""
ret = ""
mode = self._raw_mode
if mode.MANUAL:
ret = "manual"
if self.target_temperature < self.min_temp:
ret += " off"
elif self.target_temperature >= self.... | [
"def",
"mode_readable",
"(",
"self",
")",
":",
"ret",
"=",
"\"\"",
"mode",
"=",
"self",
".",
"_raw_mode",
"if",
"mode",
".",
"MANUAL",
":",
"ret",
"=",
"\"manual\"",
"if",
"self",
".",
"target_temperature",
"<",
"self",
".",
"min_temp",
":",
"ret",
"+=... | Return a readable representation of the mode.. | [
"Return",
"a",
"readable",
"representation",
"of",
"the",
"mode",
".."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L260-L289 | train |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.boost | def boost(self, boost):
"""Sets boost mode."""
_LOGGER.debug("Setting boost mode: %s", boost)
value = struct.pack('BB', PROP_BOOST, bool(boost))
self._conn.make_request(PROP_WRITE_HANDLE, value) | python | def boost(self, boost):
"""Sets boost mode."""
_LOGGER.debug("Setting boost mode: %s", boost)
value = struct.pack('BB', PROP_BOOST, bool(boost))
self._conn.make_request(PROP_WRITE_HANDLE, value) | [
"def",
"boost",
"(",
"self",
",",
"boost",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting boost mode: %s\"",
",",
"boost",
")",
"value",
"=",
"struct",
".",
"pack",
"(",
"'BB'",
",",
"PROP_BOOST",
",",
"bool",
"(",
"boost",
")",
")",
"self",
".",
... | Sets boost mode. | [
"Sets",
"boost",
"mode",
"."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L297-L301 | train |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.window_open_config | def window_open_config(self, temperature, duration):
"""Configures the window open behavior. The duration is specified in
5 minute increments."""
_LOGGER.debug("Window open config, temperature: %s duration: %s", temperature, duration)
self._verify_temperature(temperature)
if dura... | python | def window_open_config(self, temperature, duration):
"""Configures the window open behavior. The duration is specified in
5 minute increments."""
_LOGGER.debug("Window open config, temperature: %s duration: %s", temperature, duration)
self._verify_temperature(temperature)
if dura... | [
"def",
"window_open_config",
"(",
"self",
",",
"temperature",
",",
"duration",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Window open config, temperature: %s duration: %s\"",
",",
"temperature",
",",
"duration",
")",
"self",
".",
"_verify_temperature",
"(",
"temperatu... | Configures the window open behavior. The duration is specified in
5 minute increments. | [
"Configures",
"the",
"window",
"open",
"behavior",
".",
"The",
"duration",
"is",
"specified",
"in",
"5",
"minute",
"increments",
"."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L314-L324 | train |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.locked | def locked(self, lock):
"""Locks or unlocks the thermostat."""
_LOGGER.debug("Setting the lock: %s", lock)
value = struct.pack('BB', PROP_LOCK, bool(lock))
self._conn.make_request(PROP_WRITE_HANDLE, value) | python | def locked(self, lock):
"""Locks or unlocks the thermostat."""
_LOGGER.debug("Setting the lock: %s", lock)
value = struct.pack('BB', PROP_LOCK, bool(lock))
self._conn.make_request(PROP_WRITE_HANDLE, value) | [
"def",
"locked",
"(",
"self",
",",
"lock",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting the lock: %s\"",
",",
"lock",
")",
"value",
"=",
"struct",
".",
"pack",
"(",
"'BB'",
",",
"PROP_LOCK",
",",
"bool",
"(",
"lock",
")",
")",
"self",
".",
"_co... | Locks or unlocks the thermostat. | [
"Locks",
"or",
"unlocks",
"the",
"thermostat",
"."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L332-L336 | train |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.temperature_offset | def temperature_offset(self, offset):
"""Sets the thermostat's temperature offset."""
_LOGGER.debug("Setting offset: %s", offset)
# [-3,5 .. 0 .. 3,5 ]
# [00 .. 07 .. 0e ]
if offset < -3.5 or offset > 3.5:
raise TemperatureException("Invalid value: %s" % offset)
... | python | def temperature_offset(self, offset):
"""Sets the thermostat's temperature offset."""
_LOGGER.debug("Setting offset: %s", offset)
# [-3,5 .. 0 .. 3,5 ]
# [00 .. 07 .. 0e ]
if offset < -3.5 or offset > 3.5:
raise TemperatureException("Invalid value: %s" % offset)
... | [
"def",
"temperature_offset",
"(",
"self",
",",
"offset",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting offset: %s\"",
",",
"offset",
")",
"if",
"offset",
"<",
"-",
"3.5",
"or",
"offset",
">",
"3.5",
":",
"raise",
"TemperatureException",
"(",
"\"Invalid ... | Sets the thermostat's temperature offset. | [
"Sets",
"the",
"thermostat",
"s",
"temperature",
"offset",
"."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L353-L368 | train |
exxeleron/qPython | qpython/qconnection.py | QConnection._init_socket | def _init_socket(self):
'''Initialises the socket used for communicating with a q service,'''
try:
self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._connection.connect((self.host, self.port))
self._connection.settimeout(self.timeout)
... | python | def _init_socket(self):
'''Initialises the socket used for communicating with a q service,'''
try:
self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._connection.connect((self.host, self.port))
self._connection.settimeout(self.timeout)
... | [
"def",
"_init_socket",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_connection",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"_connection",
".",
"connect",
"(",
"(",
"self",
"."... | Initialises the socket used for communicating with a q service, | [
"Initialises",
"the",
"socket",
"used",
"for",
"communicating",
"with",
"a",
"q",
"service"
] | 7e64a28b1e8814a8d6b9217ce79bb8de546e62f3 | https://github.com/exxeleron/qPython/blob/7e64a28b1e8814a8d6b9217ce79bb8de546e62f3/qpython/qconnection.py#L150-L160 | train |
exxeleron/qPython | qpython/qconnection.py | QConnection.close | def close(self):
'''Closes connection with the q service.'''
if self._connection:
self._connection_file.close()
self._connection_file = None
self._connection.close()
self._connection = None | python | def close(self):
'''Closes connection with the q service.'''
if self._connection:
self._connection_file.close()
self._connection_file = None
self._connection.close()
self._connection = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
":",
"self",
".",
"_connection_file",
".",
"close",
"(",
")",
"self",
".",
"_connection_file",
"=",
"None",
"self",
".",
"_connection",
".",
"close",
"(",
")",
"self",
".",
"_conn... | Closes connection with the q service. | [
"Closes",
"connection",
"with",
"the",
"q",
"service",
"."
] | 7e64a28b1e8814a8d6b9217ce79bb8de546e62f3 | https://github.com/exxeleron/qPython/blob/7e64a28b1e8814a8d6b9217ce79bb8de546e62f3/qpython/qconnection.py#L163-L169 | train |
exxeleron/qPython | qpython/qconnection.py | QConnection._initialize | def _initialize(self):
'''Performs a IPC protocol handshake.'''
credentials = (self.username if self.username else '') + ':' + (self.password if self.password else '')
credentials = credentials.encode(self._encoding)
self._connection.send(credentials + b'\3\0')
response = self._c... | python | def _initialize(self):
'''Performs a IPC protocol handshake.'''
credentials = (self.username if self.username else '') + ':' + (self.password if self.password else '')
credentials = credentials.encode(self._encoding)
self._connection.send(credentials + b'\3\0')
response = self._c... | [
"def",
"_initialize",
"(",
"self",
")",
":",
"credentials",
"=",
"(",
"self",
".",
"username",
"if",
"self",
".",
"username",
"else",
"''",
")",
"+",
"':'",
"+",
"(",
"self",
".",
"password",
"if",
"self",
".",
"password",
"else",
"''",
")",
"credent... | Performs a IPC protocol handshake. | [
"Performs",
"a",
"IPC",
"protocol",
"handshake",
"."
] | 7e64a28b1e8814a8d6b9217ce79bb8de546e62f3 | https://github.com/exxeleron/qPython/blob/7e64a28b1e8814a8d6b9217ce79bb8de546e62f3/qpython/qconnection.py#L185-L202 | train |
exxeleron/qPython | qpython/qcollection.py | qlist | def qlist(array, adjust_dtype = True, **meta):
'''Converts an input array to q vector and enriches object instance with
meta data.
Returns a :class:`.QList` instance for non-datetime vectors. For datetime
vectors :class:`.QTemporalList` is returned instead.
If parameter `adjust_dtype` is `True` ... | python | def qlist(array, adjust_dtype = True, **meta):
'''Converts an input array to q vector and enriches object instance with
meta data.
Returns a :class:`.QList` instance for non-datetime vectors. For datetime
vectors :class:`.QTemporalList` is returned instead.
If parameter `adjust_dtype` is `True` ... | [
"def",
"qlist",
"(",
"array",
",",
"adjust_dtype",
"=",
"True",
",",
"**",
"meta",
")",
":",
"if",
"type",
"(",
"array",
")",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"if",
"meta",
"and",
"'qtype'",
"in",
"meta",
"and",
"meta",
"[",
"'qtype'",
... | Converts an input array to q vector and enriches object instance with
meta data.
Returns a :class:`.QList` instance for non-datetime vectors. For datetime
vectors :class:`.QTemporalList` is returned instead.
If parameter `adjust_dtype` is `True` and q type retrieved via
:func:`.get_list_qtype` ... | [
"Converts",
"an",
"input",
"array",
"to",
"q",
"vector",
"and",
"enriches",
"object",
"instance",
"with",
"meta",
"data",
"."
] | 7e64a28b1e8814a8d6b9217ce79bb8de546e62f3 | https://github.com/exxeleron/qPython/blob/7e64a28b1e8814a8d6b9217ce79bb8de546e62f3/qpython/qcollection.py#L105-L196 | train |
wkentaro/gdown | gdown/parse_url.py | parse_url | def parse_url(url, warning=True):
"""Parse URLs especially for Google Drive links.
file_id: ID of file on Google Drive.
is_download_link: Flag if it is download link of Google Drive.
"""
parsed = urllib_parse.urlparse(url)
query = urllib_parse.parse_qs(parsed.query)
is_gdrive = parsed.hostn... | python | def parse_url(url, warning=True):
"""Parse URLs especially for Google Drive links.
file_id: ID of file on Google Drive.
is_download_link: Flag if it is download link of Google Drive.
"""
parsed = urllib_parse.urlparse(url)
query = urllib_parse.parse_qs(parsed.query)
is_gdrive = parsed.hostn... | [
"def",
"parse_url",
"(",
"url",
",",
"warning",
"=",
"True",
")",
":",
"parsed",
"=",
"urllib_parse",
".",
"urlparse",
"(",
"url",
")",
"query",
"=",
"urllib_parse",
".",
"parse_qs",
"(",
"parsed",
".",
"query",
")",
"is_gdrive",
"=",
"parsed",
".",
"h... | Parse URLs especially for Google Drive links.
file_id: ID of file on Google Drive.
is_download_link: Flag if it is download link of Google Drive. | [
"Parse",
"URLs",
"especially",
"for",
"Google",
"Drive",
"links",
"."
] | d2952b56f7da3dddceb096e27569b5375a76d267 | https://github.com/wkentaro/gdown/blob/d2952b56f7da3dddceb096e27569b5375a76d267/gdown/parse_url.py#L7-L34 | train |
wkentaro/gdown | gdown/extractall.py | extractall | def extractall(path, to=None):
"""Extract archive file.
Parameters
----------
path: str
Path of archive file to be extracted.
to: str, optional
Directory to which the archive file will be extracted.
If None, it will be set to the parent directory of the archive file.
"""... | python | def extractall(path, to=None):
"""Extract archive file.
Parameters
----------
path: str
Path of archive file to be extracted.
to: str, optional
Directory to which the archive file will be extracted.
If None, it will be set to the parent directory of the archive file.
"""... | [
"def",
"extractall",
"(",
"path",
",",
"to",
"=",
"None",
")",
":",
"if",
"to",
"is",
"None",
":",
"to",
"=",
"osp",
".",
"dirname",
"(",
"path",
")",
"if",
"path",
".",
"endswith",
"(",
"'.zip'",
")",
":",
"opener",
",",
"mode",
"=",
"zipfile",
... | Extract archive file.
Parameters
----------
path: str
Path of archive file to be extracted.
to: str, optional
Directory to which the archive file will be extracted.
If None, it will be set to the parent directory of the archive file. | [
"Extract",
"archive",
"file",
"."
] | d2952b56f7da3dddceb096e27569b5375a76d267 | https://github.com/wkentaro/gdown/blob/d2952b56f7da3dddceb096e27569b5375a76d267/gdown/extractall.py#L6-L47 | train |
benhoff/vexbot | vexbot/adapters/shell/interfaces.py | _add_word | def _add_word(completer):
"""
Used to add words to the completors
"""
def inner(word: str):
completer.words.add(word)
return inner | python | def _add_word(completer):
"""
Used to add words to the completors
"""
def inner(word: str):
completer.words.add(word)
return inner | [
"def",
"_add_word",
"(",
"completer",
")",
":",
"def",
"inner",
"(",
"word",
":",
"str",
")",
":",
"completer",
".",
"words",
".",
"add",
"(",
"word",
")",
"return",
"inner"
] | Used to add words to the completors | [
"Used",
"to",
"add",
"words",
"to",
"the",
"completors"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/interfaces.py#L8-L14 | train |
benhoff/vexbot | vexbot/adapters/shell/interfaces.py | _remove_word | def _remove_word(completer):
"""
Used to remove words from the completors
"""
def inner(word: str):
try:
completer.words.remove(word)
except Exception:
pass
return inner | python | def _remove_word(completer):
"""
Used to remove words from the completors
"""
def inner(word: str):
try:
completer.words.remove(word)
except Exception:
pass
return inner | [
"def",
"_remove_word",
"(",
"completer",
")",
":",
"def",
"inner",
"(",
"word",
":",
"str",
")",
":",
"try",
":",
"completer",
".",
"words",
".",
"remove",
"(",
"word",
")",
"except",
"Exception",
":",
"pass",
"return",
"inner"
] | Used to remove words from the completors | [
"Used",
"to",
"remove",
"words",
"from",
"the",
"completors"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/interfaces.py#L17-L26 | train |
benhoff/vexbot | vexbot/extensions/log.py | set_info | def set_info(self, *args, **kwargs) -> None:
"""
Sets the log level to `INFO`
"""
self.root_logger.setLevel(logging.INFO)
try:
self.messaging.pub_handler.setLevel(logging.INFO)
except Exception:
pass | python | def set_info(self, *args, **kwargs) -> None:
"""
Sets the log level to `INFO`
"""
self.root_logger.setLevel(logging.INFO)
try:
self.messaging.pub_handler.setLevel(logging.INFO)
except Exception:
pass | [
"def",
"set_info",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"root_logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"try",
":",
"self",
".",
"messaging",
".",
"pub_handler",
".",
"setLevel",
"... | Sets the log level to `INFO` | [
"Sets",
"the",
"log",
"level",
"to",
"INFO"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/extensions/log.py#L36-L44 | train |
benhoff/vexbot | vexbot/command_observer.py | CommandObserver.do_REMOTE | def do_REMOTE(self,
target: str,
remote_command: str,
source: list,
*args,
**kwargs) -> None:
"""
Send a remote command to a service. Used
Args:
target: The service that the command gets set t... | python | def do_REMOTE(self,
target: str,
remote_command: str,
source: list,
*args,
**kwargs) -> None:
"""
Send a remote command to a service. Used
Args:
target: The service that the command gets set t... | [
"def",
"do_REMOTE",
"(",
"self",
",",
"target",
":",
"str",
",",
"remote_command",
":",
"str",
",",
"source",
":",
"list",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"->",
"None",
":",
"if",
"target",
"==",
"self",
".",
"messaging",
".",
"_service_n... | Send a remote command to a service. Used
Args:
target: The service that the command gets set to
remote_command: The command to do remotely.
source: the binary source of the zmq_socket. Packed to send to the | [
"Send",
"a",
"remote",
"command",
"to",
"a",
"service",
".",
"Used"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/command_observer.py#L125-L161 | train |
benhoff/vexbot | vexbot/command_observer.py | CommandObserver.do_IDENT | def do_IDENT(self, service_name: str, source: list, *args, **kwargs) -> None:
"""
Perform identification of a service to a binary representation.
Args:
service_name: human readable name for service
source: zmq representation for the socket source
"""
self... | python | def do_IDENT(self, service_name: str, source: list, *args, **kwargs) -> None:
"""
Perform identification of a service to a binary representation.
Args:
service_name: human readable name for service
source: zmq representation for the socket source
"""
self... | [
"def",
"do_IDENT",
"(",
"self",
",",
"service_name",
":",
"str",
",",
"source",
":",
"list",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"logger",
".",
"info",
"(",
"' IDENT %s as %s'",
",",
"service_name",
",",
"source"... | Perform identification of a service to a binary representation.
Args:
service_name: human readable name for service
source: zmq representation for the socket source | [
"Perform",
"identification",
"of",
"a",
"service",
"to",
"a",
"binary",
"representation",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/command_observer.py#L192-L201 | train |
benhoff/vexbot | vexbot/subprocess_manager.py | _name_helper | def _name_helper(name: str):
"""
default to returning a name with `.service`
"""
name = name.rstrip()
if name.endswith(('.service', '.socket', '.target')):
return name
return name + '.service' | python | def _name_helper(name: str):
"""
default to returning a name with `.service`
"""
name = name.rstrip()
if name.endswith(('.service', '.socket', '.target')):
return name
return name + '.service' | [
"def",
"_name_helper",
"(",
"name",
":",
"str",
")",
":",
"name",
"=",
"name",
".",
"rstrip",
"(",
")",
"if",
"name",
".",
"endswith",
"(",
"(",
"'.service'",
",",
"'.socket'",
",",
"'.target'",
")",
")",
":",
"return",
"name",
"return",
"name",
"+",... | default to returning a name with `.service` | [
"default",
"to",
"returning",
"a",
"name",
"with",
".",
"service"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/subprocess_manager.py#L12-L19 | train |
benhoff/vexbot | vexbot/util/get_certificate_filepath.py | get_vexbot_certificate_filepath | def get_vexbot_certificate_filepath() -> (str, bool):
"""
Returns the vexbot certificate filepath and the whether it is the private
filepath or not
"""
public_filepath, secret_filepath = _certificate_helper('vexbot.key','vexbot.key_secret')
if path.isfile(secret_filepath):
return secret_... | python | def get_vexbot_certificate_filepath() -> (str, bool):
"""
Returns the vexbot certificate filepath and the whether it is the private
filepath or not
"""
public_filepath, secret_filepath = _certificate_helper('vexbot.key','vexbot.key_secret')
if path.isfile(secret_filepath):
return secret_... | [
"def",
"get_vexbot_certificate_filepath",
"(",
")",
"->",
"(",
"str",
",",
"bool",
")",
":",
"public_filepath",
",",
"secret_filepath",
"=",
"_certificate_helper",
"(",
"'vexbot.key'",
",",
"'vexbot.key_secret'",
")",
"if",
"path",
".",
"isfile",
"(",
"secret_file... | Returns the vexbot certificate filepath and the whether it is the private
filepath or not | [
"Returns",
"the",
"vexbot",
"certificate",
"filepath",
"and",
"the",
"whether",
"it",
"is",
"the",
"private",
"filepath",
"or",
"not"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/util/get_certificate_filepath.py#L28-L40 | train |
benhoff/vexbot | vexbot/extensions/develop.py | get_code | def get_code(self, *args, **kwargs):
"""
get the python source code from callback
"""
# FIXME: Honestly should allow multiple commands
callback = self._commands[args[0]]
# TODO: syntax color would be nice
source = _inspect.getsourcelines(callback)[0]
"""
source_len = len(source)
... | python | def get_code(self, *args, **kwargs):
"""
get the python source code from callback
"""
# FIXME: Honestly should allow multiple commands
callback = self._commands[args[0]]
# TODO: syntax color would be nice
source = _inspect.getsourcelines(callback)[0]
"""
source_len = len(source)
... | [
"def",
"get_code",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"callback",
"=",
"self",
".",
"_commands",
"[",
"args",
"[",
"0",
"]",
"]",
"source",
"=",
"_inspect",
".",
"getsourcelines",
"(",
"callback",
")",
"[",
"0",
"]",
"ret... | get the python source code from callback | [
"get",
"the",
"python",
"source",
"code",
"from",
"callback"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/extensions/develop.py#L4-L17 | train |
benhoff/vexbot | vexbot/adapters/messaging.py | _HeartbeatReciever._get_state | def _get_state(self) -> None:
"""
Internal method that accomplishes checking to make sure that the UUID
has not changed
"""
# Don't need to go any further if we don't have a message
if self.last_message is None:
return
# get the latest message UUID
... | python | def _get_state(self) -> None:
"""
Internal method that accomplishes checking to make sure that the UUID
has not changed
"""
# Don't need to go any further if we don't have a message
if self.last_message is None:
return
# get the latest message UUID
... | [
"def",
"_get_state",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"last_message",
"is",
"None",
":",
"return",
"uuid",
"=",
"self",
".",
"last_message",
".",
"uuid",
"if",
"uuid",
"!=",
"self",
".",
"_last_bot_uuid",
":",
"self",
".",
"logge... | Internal method that accomplishes checking to make sure that the UUID
has not changed | [
"Internal",
"method",
"that",
"accomplishes",
"checking",
"to",
"make",
"sure",
"that",
"the",
"UUID",
"has",
"not",
"changed"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L80-L100 | train |
benhoff/vexbot | vexbot/adapters/messaging.py | _HeartbeatReciever.send_identity | def send_identity(self):
"""
Send the identity of the service.
"""
service_name = {'service_name': self.messaging._service_name}
service_name = _json.dumps(service_name).encode('utf8')
identify_frame = (b'',
b'IDENT',
_... | python | def send_identity(self):
"""
Send the identity of the service.
"""
service_name = {'service_name': self.messaging._service_name}
service_name = _json.dumps(service_name).encode('utf8')
identify_frame = (b'',
b'IDENT',
_... | [
"def",
"send_identity",
"(",
"self",
")",
":",
"service_name",
"=",
"{",
"'service_name'",
":",
"self",
".",
"messaging",
".",
"_service_name",
"}",
"service_name",
"=",
"_json",
".",
"dumps",
"(",
"service_name",
")",
".",
"encode",
"(",
"'utf8'",
")",
"i... | Send the identity of the service. | [
"Send",
"the",
"identity",
"of",
"the",
"service",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L102-L126 | train |
benhoff/vexbot | vexbot/adapters/messaging.py | Messaging._config_convert_to_address_helper | def _config_convert_to_address_helper(self) -> None:
"""
converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address`
"""
to_address = self._socket_factory.to_address
for k, v in self.config.items():
if k... | python | def _config_convert_to_address_helper(self) -> None:
"""
converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address`
"""
to_address = self._socket_factory.to_address
for k, v in self.config.items():
if k... | [
"def",
"_config_convert_to_address_helper",
"(",
"self",
")",
"->",
"None",
":",
"to_address",
"=",
"self",
".",
"_socket_factory",
".",
"to_address",
"for",
"k",
",",
"v",
"in",
"self",
".",
"config",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'chat... | converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address` | [
"converts",
"the",
"config",
"from",
"ports",
"to",
"zmq",
"ip",
"addresses",
"Operates",
"on",
"self",
".",
"config",
"using",
"self",
".",
"_socket_factory",
".",
"to_address"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L239-L249 | train |
benhoff/vexbot | vexbot/adapters/messaging.py | Messaging.add_callback | def add_callback(self, callback: _Callable, *args, **kwargs) -> None:
"""
Add a callback to the event loop
"""
self.loop.add_callback(callback, *args, **kwargs) | python | def add_callback(self, callback: _Callable, *args, **kwargs) -> None:
"""
Add a callback to the event loop
"""
self.loop.add_callback(callback, *args, **kwargs) | [
"def",
"add_callback",
"(",
"self",
",",
"callback",
":",
"_Callable",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"loop",
".",
"add_callback",
"(",
"callback",
",",
"*",
"args",
",",
"**",
"kwargs",
")"
] | Add a callback to the event loop | [
"Add",
"a",
"callback",
"to",
"the",
"event",
"loop"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L251-L255 | train |
benhoff/vexbot | vexbot/adapters/messaging.py | Messaging.start | def start(self) -> None:
"""
Start the internal control loop. Potentially blocking, depending on
the value of `_run_control_loop` set by the initializer.
"""
self._setup()
if self._run_control_loop:
asyncio.set_event_loop(asyncio.new_event_loop())
... | python | def start(self) -> None:
"""
Start the internal control loop. Potentially blocking, depending on
the value of `_run_control_loop` set by the initializer.
"""
self._setup()
if self._run_control_loop:
asyncio.set_event_loop(asyncio.new_event_loop())
... | [
"def",
"start",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_setup",
"(",
")",
"if",
"self",
".",
"_run_control_loop",
":",
"asyncio",
".",
"set_event_loop",
"(",
"asyncio",
".",
"new_event_loop",
"(",
")",
")",
"self",
".",
"_heartbeat_reciever",
... | Start the internal control loop. Potentially blocking, depending on
the value of `_run_control_loop` set by the initializer. | [
"Start",
"the",
"internal",
"control",
"loop",
".",
"Potentially",
"blocking",
"depending",
"on",
"the",
"value",
"of",
"_run_control_loop",
"set",
"by",
"the",
"initializer",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L257-L270 | train |
benhoff/vexbot | vexbot/adapters/messaging.py | Messaging.send_command | def send_command(self, command: str, *args, **kwargs):
"""
For request bot to perform some action
"""
info = 'send command `%s` to bot. Args: %s | Kwargs: %s'
self._messaging_logger.command.info(info, command, args, kwargs)
command = command.encode('utf8')
# targ... | python | def send_command(self, command: str, *args, **kwargs):
"""
For request bot to perform some action
"""
info = 'send command `%s` to bot. Args: %s | Kwargs: %s'
self._messaging_logger.command.info(info, command, args, kwargs)
command = command.encode('utf8')
# targ... | [
"def",
"send_command",
"(",
"self",
",",
"command",
":",
"str",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"info",
"=",
"'send command `%s` to bot. Args: %s | Kwargs: %s'",
"self",
".",
"_messaging_logger",
".",
"command",
".",
"info",
"(",
"info",
",",
... | For request bot to perform some action | [
"For",
"request",
"bot",
"to",
"perform",
"some",
"action"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L403-L421 | train |
benhoff/vexbot | vexbot/util/socket_factory.py | SocketFactory.to_address | def to_address(self, port: str):
"""
transforms the ports into addresses.
Will fall through if the port looks like an address
"""
# check to see if user passed in a string
# if they did, they want to use that instead
if isinstance(port, str) and len(port) > 6:
... | python | def to_address(self, port: str):
"""
transforms the ports into addresses.
Will fall through if the port looks like an address
"""
# check to see if user passed in a string
# if they did, they want to use that instead
if isinstance(port, str) and len(port) > 6:
... | [
"def",
"to_address",
"(",
"self",
",",
"port",
":",
"str",
")",
":",
"if",
"isinstance",
"(",
"port",
",",
"str",
")",
"and",
"len",
"(",
"port",
")",
">",
"6",
":",
"return",
"port",
"zmq_address",
"=",
"'{}://{}:{}'",
"return",
"zmq_address",
".",
... | transforms the ports into addresses.
Will fall through if the port looks like an address | [
"transforms",
"the",
"ports",
"into",
"addresses",
".",
"Will",
"fall",
"through",
"if",
"the",
"port",
"looks",
"like",
"an",
"address"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/util/socket_factory.py#L148-L161 | train |
benhoff/vexbot | vexbot/util/socket_factory.py | SocketFactory.iterate_multiple_addresses | def iterate_multiple_addresses(self, ports: (str, list, tuple)):
"""
transforms an iterable, or the expectation of an iterable
into zmq addresses
"""
if isinstance(ports, (str, int)):
# TODO: verify this works.
ports = tuple(ports,)
result = []
... | python | def iterate_multiple_addresses(self, ports: (str, list, tuple)):
"""
transforms an iterable, or the expectation of an iterable
into zmq addresses
"""
if isinstance(ports, (str, int)):
# TODO: verify this works.
ports = tuple(ports,)
result = []
... | [
"def",
"iterate_multiple_addresses",
"(",
"self",
",",
"ports",
":",
"(",
"str",
",",
"list",
",",
"tuple",
")",
")",
":",
"if",
"isinstance",
"(",
"ports",
",",
"(",
"str",
",",
"int",
")",
")",
":",
"ports",
"=",
"tuple",
"(",
"ports",
",",
")",
... | transforms an iterable, or the expectation of an iterable
into zmq addresses | [
"transforms",
"an",
"iterable",
"or",
"the",
"expectation",
"of",
"an",
"iterable",
"into",
"zmq",
"addresses"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/util/socket_factory.py#L163-L176 | train |
benhoff/vexbot | vexbot/adapters/shell/shell.py | Shell.is_command | def is_command(self, text: str) -> bool:
"""
checks for presence of shebang in the first character of the text
"""
if text[0] in self.shebangs:
return True
return False | python | def is_command(self, text: str) -> bool:
"""
checks for presence of shebang in the first character of the text
"""
if text[0] in self.shebangs:
return True
return False | [
"def",
"is_command",
"(",
"self",
",",
"text",
":",
"str",
")",
"->",
"bool",
":",
"if",
"text",
"[",
"0",
"]",
"in",
"self",
".",
"shebangs",
":",
"return",
"True",
"return",
"False"
] | checks for presence of shebang in the first character of the text | [
"checks",
"for",
"presence",
"of",
"shebang",
"in",
"the",
"first",
"character",
"of",
"the",
"text"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/shell.py#L147-L154 | train |
benhoff/vexbot | vexbot/adapters/shell/shell.py | Shell._handle_text | def _handle_text(self, text: str):
"""
Check to see if text is a command. Otherwise, check to see if the
second word is a command.
Commands get handeled by the `_handle_command` method
If not command, check to see if first word is a service or an author.
Default program... | python | def _handle_text(self, text: str):
"""
Check to see if text is a command. Otherwise, check to see if the
second word is a command.
Commands get handeled by the `_handle_command` method
If not command, check to see if first word is a service or an author.
Default program... | [
"def",
"_handle_text",
"(",
"self",
",",
"text",
":",
"str",
")",
":",
"if",
"self",
".",
"is_command",
"(",
"text",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"' first word is a command'",
")",
"command",
",",
"args",
",",
"kwargs",
"=",
"_g... | Check to see if text is a command. Otherwise, check to see if the
second word is a command.
Commands get handeled by the `_handle_command` method
If not command, check to see if first word is a service or an author.
Default program is to send message replies. However, we will also
... | [
"Check",
"to",
"see",
"if",
"text",
"is",
"a",
"command",
".",
"Otherwise",
"check",
"to",
"see",
"if",
"the",
"second",
"word",
"is",
"a",
"command",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/shell.py#L185-L239 | train |
benhoff/vexbot | vexbot/adapters/shell/shell.py | Shell._first_word_not_cmd | def _first_word_not_cmd(self,
first_word: str,
command: str,
args: tuple,
kwargs: dict) -> None:
"""
check to see if this is an author or service.
This method does high level control h... | python | def _first_word_not_cmd(self,
first_word: str,
command: str,
args: tuple,
kwargs: dict) -> None:
"""
check to see if this is an author or service.
This method does high level control h... | [
"def",
"_first_word_not_cmd",
"(",
"self",
",",
"first_word",
":",
"str",
",",
"command",
":",
"str",
",",
"args",
":",
"tuple",
",",
"kwargs",
":",
"dict",
")",
"->",
"None",
":",
"if",
"self",
".",
"service_interface",
".",
"is_service",
"(",
"first_wo... | check to see if this is an author or service.
This method does high level control handling | [
"check",
"to",
"see",
"if",
"this",
"is",
"an",
"author",
"or",
"service",
".",
"This",
"method",
"does",
"high",
"level",
"control",
"handling"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/shell.py#L263-L286 | train |
benhoff/vexbot | vexbot/entity_extraction.py | EntityExtraction._sentence_to_features | def _sentence_to_features(self, sentence: list):
# type: (List[Tuple[Text, Text, Text, Text]]) -> List[Dict[Text, Any]]
"""Convert a word into discrete features in self.crf_features,
including word before and word after."""
sentence_features = []
prefixes = ('-1', '0', '+1')
... | python | def _sentence_to_features(self, sentence: list):
# type: (List[Tuple[Text, Text, Text, Text]]) -> List[Dict[Text, Any]]
"""Convert a word into discrete features in self.crf_features,
including word before and word after."""
sentence_features = []
prefixes = ('-1', '0', '+1')
... | [
"def",
"_sentence_to_features",
"(",
"self",
",",
"sentence",
":",
"list",
")",
":",
"sentence_features",
"=",
"[",
"]",
"prefixes",
"=",
"(",
"'-1'",
",",
"'0'",
",",
"'+1'",
")",
"for",
"word_idx",
"in",
"range",
"(",
"len",
"(",
"sentence",
")",
")"... | Convert a word into discrete features in self.crf_features,
including word before and word after. | [
"Convert",
"a",
"word",
"into",
"discrete",
"features",
"in",
"self",
".",
"crf_features",
"including",
"word",
"before",
"and",
"word",
"after",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/entity_extraction.py#L70-L97 | train |
kblomqvist/yasha | yasha/yasha.py | find_template_companion | def find_template_companion(template, extension='', check=True):
"""
Returns the first found template companion file
"""
if check and not os.path.isfile(template):
yield ''
return # May be '<stdin>' (click)
template = os.path.abspath(template)
template_dirname = os.path.dirname... | python | def find_template_companion(template, extension='', check=True):
"""
Returns the first found template companion file
"""
if check and not os.path.isfile(template):
yield ''
return # May be '<stdin>' (click)
template = os.path.abspath(template)
template_dirname = os.path.dirname... | [
"def",
"find_template_companion",
"(",
"template",
",",
"extension",
"=",
"''",
",",
"check",
"=",
"True",
")",
":",
"if",
"check",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"template",
")",
":",
"yield",
"''",
"return",
"template",
"=",
"os... | Returns the first found template companion file | [
"Returns",
"the",
"first",
"found",
"template",
"companion",
"file"
] | aebda08f45458611a59497fb7505f0881b73fbd5 | https://github.com/kblomqvist/yasha/blob/aebda08f45458611a59497fb7505f0881b73fbd5/yasha/yasha.py#L35-L76 | train |
kblomqvist/yasha | yasha/cmsis.py | SvdElement.from_element | def from_element(self, element, defaults={}):
"""Populate object variables from SVD element"""
if isinstance(defaults, SvdElement):
defaults = vars(defaults)
for key in self.props:
try:
value = element.find(key).text
except AttributeError: # M... | python | def from_element(self, element, defaults={}):
"""Populate object variables from SVD element"""
if isinstance(defaults, SvdElement):
defaults = vars(defaults)
for key in self.props:
try:
value = element.find(key).text
except AttributeError: # M... | [
"def",
"from_element",
"(",
"self",
",",
"element",
",",
"defaults",
"=",
"{",
"}",
")",
":",
"if",
"isinstance",
"(",
"defaults",
",",
"SvdElement",
")",
":",
"defaults",
"=",
"vars",
"(",
"defaults",
")",
"for",
"key",
"in",
"self",
".",
"props",
"... | Populate object variables from SVD element | [
"Populate",
"object",
"variables",
"from",
"SVD",
"element"
] | aebda08f45458611a59497fb7505f0881b73fbd5 | https://github.com/kblomqvist/yasha/blob/aebda08f45458611a59497fb7505f0881b73fbd5/yasha/cmsis.py#L75-L94 | train |
kblomqvist/yasha | yasha/cmsis.py | SvdRegister.fold | def fold(self):
"""Folds the Register in accordance with it's dimensions.
If the register is dimensionless, the returned list just
contains the register itself unchanged. In case the register
name looks like a C array, the returned list contains the register
itself, where nothin... | python | def fold(self):
"""Folds the Register in accordance with it's dimensions.
If the register is dimensionless, the returned list just
contains the register itself unchanged. In case the register
name looks like a C array, the returned list contains the register
itself, where nothin... | [
"def",
"fold",
"(",
"self",
")",
":",
"if",
"self",
".",
"dim",
"is",
"None",
":",
"return",
"[",
"self",
"]",
"if",
"self",
".",
"name",
".",
"endswith",
"(",
"\"[%s]\"",
")",
":",
"self",
".",
"name",
"=",
"self",
".",
"name",
".",
"replace",
... | Folds the Register in accordance with it's dimensions.
If the register is dimensionless, the returned list just
contains the register itself unchanged. In case the register
name looks like a C array, the returned list contains the register
itself, where nothing else than the '%s' placeh... | [
"Folds",
"the",
"Register",
"in",
"accordance",
"with",
"it",
"s",
"dimensions",
"."
] | aebda08f45458611a59497fb7505f0881b73fbd5 | https://github.com/kblomqvist/yasha/blob/aebda08f45458611a59497fb7505f0881b73fbd5/yasha/cmsis.py#L240-L268 | train |
thombashi/tcconfig | tcconfig/traffic_control.py | TrafficControl.get_tc_device | def get_tc_device(self):
"""
Return a device name that associated network communication direction.
"""
if self.direction == TrafficDirection.OUTGOING:
return self.device
if self.direction == TrafficDirection.INCOMING:
return self.ifb_device
rais... | python | def get_tc_device(self):
"""
Return a device name that associated network communication direction.
"""
if self.direction == TrafficDirection.OUTGOING:
return self.device
if self.direction == TrafficDirection.INCOMING:
return self.ifb_device
rais... | [
"def",
"get_tc_device",
"(",
"self",
")",
":",
"if",
"self",
".",
"direction",
"==",
"TrafficDirection",
".",
"OUTGOING",
":",
"return",
"self",
".",
"device",
"if",
"self",
".",
"direction",
"==",
"TrafficDirection",
".",
"INCOMING",
":",
"return",
"self",
... | Return a device name that associated network communication direction. | [
"Return",
"a",
"device",
"name",
"that",
"associated",
"network",
"communication",
"direction",
"."
] | 9612dcd6ac9c072e7aa9eb702a225c559936bad3 | https://github.com/thombashi/tcconfig/blob/9612dcd6ac9c072e7aa9eb702a225c559936bad3/tcconfig/traffic_control.py#L213-L226 | train |
thombashi/tcconfig | tcconfig/traffic_control.py | TrafficControl.delete_tc | def delete_tc(self):
"""
Delete a specific shaping rule.
"""
rule_finder = TcShapingRuleFinder(logger=logger, tc=self)
filter_param = rule_finder.find_filter_param()
if not filter_param:
message = "shaping rule not found ({}).".format(rule_finder.get_filter_... | python | def delete_tc(self):
"""
Delete a specific shaping rule.
"""
rule_finder = TcShapingRuleFinder(logger=logger, tc=self)
filter_param = rule_finder.find_filter_param()
if not filter_param:
message = "shaping rule not found ({}).".format(rule_finder.get_filter_... | [
"def",
"delete_tc",
"(",
"self",
")",
":",
"rule_finder",
"=",
"TcShapingRuleFinder",
"(",
"logger",
"=",
"logger",
",",
"tc",
"=",
"self",
")",
"filter_param",
"=",
"rule_finder",
".",
"find_filter_param",
"(",
")",
"if",
"not",
"filter_param",
":",
"messag... | Delete a specific shaping rule. | [
"Delete",
"a",
"specific",
"shaping",
"rule",
"."
] | 9612dcd6ac9c072e7aa9eb702a225c559936bad3 | https://github.com/thombashi/tcconfig/blob/9612dcd6ac9c072e7aa9eb702a225c559936bad3/tcconfig/traffic_control.py#L308-L347 | train |
mcs07/PubChemPy | pubchempy.py | request | def request(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
"""
Construct API request from parameters and return the response.
Full specification at http://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html
"""
if not identifier:
raise... | python | def request(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
"""
Construct API request from parameters and return the response.
Full specification at http://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html
"""
if not identifier:
raise... | [
"def",
"request",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"domain",
"=",
"'compound'",
",",
"operation",
"=",
"None",
",",
"output",
"=",
"'JSON'",
",",
"searchtype",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"not",
"identifier",
... | Construct API request from parameters and return the response.
Full specification at http://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html | [
"Construct",
"API",
"request",
"from",
"parameters",
"and",
"return",
"the",
"response",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L238-L274 | train |
mcs07/PubChemPy | pubchempy.py | get | def get(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
"""Request wrapper that automatically handles async requests."""
if (searchtype and searchtype != 'xref') or namespace in ['formula']:
response = request(identifier, namespace, domain, None... | python | def get(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
"""Request wrapper that automatically handles async requests."""
if (searchtype and searchtype != 'xref') or namespace in ['formula']:
response = request(identifier, namespace, domain, None... | [
"def",
"get",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"domain",
"=",
"'compound'",
",",
"operation",
"=",
"None",
",",
"output",
"=",
"'JSON'",
",",
"searchtype",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"searchtype",
"and... | Request wrapper that automatically handles async requests. | [
"Request",
"wrapper",
"that",
"automatically",
"handles",
"async",
"requests",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L277-L293 | train |
mcs07/PubChemPy | pubchempy.py | get_json | def get_json(identifier, namespace='cid', domain='compound', operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically parses JSON response and supresses NotFoundError."""
try:
return json.loads(get(identifier, namespace, domain, operation, 'JSON', searchtype, **kwargs).decode())... | python | def get_json(identifier, namespace='cid', domain='compound', operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically parses JSON response and supresses NotFoundError."""
try:
return json.loads(get(identifier, namespace, domain, operation, 'JSON', searchtype, **kwargs).decode())... | [
"def",
"get_json",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"domain",
"=",
"'compound'",
",",
"operation",
"=",
"None",
",",
"searchtype",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"get"... | Request wrapper that automatically parses JSON response and supresses NotFoundError. | [
"Request",
"wrapper",
"that",
"automatically",
"parses",
"JSON",
"response",
"and",
"supresses",
"NotFoundError",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L296-L302 | train |
mcs07/PubChemPy | pubchempy.py | get_sdf | def get_sdf(identifier, namespace='cid', domain='compound',operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically parses SDF response and supresses NotFoundError."""
try:
return get(identifier, namespace, domain, operation, 'SDF', searchtype, **kwargs).decode()
except NotF... | python | def get_sdf(identifier, namespace='cid', domain='compound',operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically parses SDF response and supresses NotFoundError."""
try:
return get(identifier, namespace, domain, operation, 'SDF', searchtype, **kwargs).decode()
except NotF... | [
"def",
"get_sdf",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"domain",
"=",
"'compound'",
",",
"operation",
"=",
"None",
",",
"searchtype",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"get",
"(",
"identifier",
",",
"n... | Request wrapper that automatically parses SDF response and supresses NotFoundError. | [
"Request",
"wrapper",
"that",
"automatically",
"parses",
"SDF",
"response",
"and",
"supresses",
"NotFoundError",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L304-L310 | train |
mcs07/PubChemPy | pubchempy.py | get_compounds | def get_compounds(identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs):
"""Retrieve the specified compound records from PubChem.
:param identifier: The compound identifier to use as a search query.
:param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi... | python | def get_compounds(identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs):
"""Retrieve the specified compound records from PubChem.
:param identifier: The compound identifier to use as a search query.
:param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi... | [
"def",
"get_compounds",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"searchtype",
"=",
"None",
",",
"as_dataframe",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"results",
"=",
"get_json",
"(",
"identifier",
",",
"namespace",
",",
"searchtype",
... | Retrieve the specified compound records from PubChem.
:param identifier: The compound identifier to use as a search query.
:param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi, inchikey or formula.
:param searchtype: (optional) The advanced search type, one of substructure... | [
"Retrieve",
"the",
"specified",
"compound",
"records",
"from",
"PubChem",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L312-L325 | train |
mcs07/PubChemPy | pubchempy.py | get_substances | def get_substances(identifier, namespace='sid', as_dataframe=False, **kwargs):
"""Retrieve the specified substance records from PubChem.
:param identifier: The substance identifier to use as a search query.
:param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>.
:p... | python | def get_substances(identifier, namespace='sid', as_dataframe=False, **kwargs):
"""Retrieve the specified substance records from PubChem.
:param identifier: The substance identifier to use as a search query.
:param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>.
:p... | [
"def",
"get_substances",
"(",
"identifier",
",",
"namespace",
"=",
"'sid'",
",",
"as_dataframe",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"results",
"=",
"get_json",
"(",
"identifier",
",",
"namespace",
",",
"'substance'",
",",
"**",
"kwargs",
")",
"su... | Retrieve the specified substance records from PubChem.
:param identifier: The substance identifier to use as a search query.
:param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>.
:param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Substance` ... | [
"Retrieve",
"the",
"specified",
"substance",
"records",
"from",
"PubChem",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L328-L340 | train |
mcs07/PubChemPy | pubchempy.py | get_assays | def get_assays(identifier, namespace='aid', **kwargs):
"""Retrieve the specified assay records from PubChem.
:param identifier: The assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
"""
results = get_json(identifier, namespace, 'assay', 'description', **kw... | python | def get_assays(identifier, namespace='aid', **kwargs):
"""Retrieve the specified assay records from PubChem.
:param identifier: The assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
"""
results = get_json(identifier, namespace, 'assay', 'description', **kw... | [
"def",
"get_assays",
"(",
"identifier",
",",
"namespace",
"=",
"'aid'",
",",
"**",
"kwargs",
")",
":",
"results",
"=",
"get_json",
"(",
"identifier",
",",
"namespace",
",",
"'assay'",
",",
"'description'",
",",
"**",
"kwargs",
")",
"return",
"[",
"Assay",
... | Retrieve the specified assay records from PubChem.
:param identifier: The assay identifier to use as a search query.
:param namespace: (optional) The identifier type. | [
"Retrieve",
"the",
"specified",
"assay",
"records",
"from",
"PubChem",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L343-L350 | train |
mcs07/PubChemPy | pubchempy.py | get_properties | def get_properties(properties, identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs):
"""Retrieve the specified properties from PubChem.
:param identifier: The compound, substance or assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
:para... | python | def get_properties(properties, identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs):
"""Retrieve the specified properties from PubChem.
:param identifier: The compound, substance or assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
:para... | [
"def",
"get_properties",
"(",
"properties",
",",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"searchtype",
"=",
"None",
",",
"as_dataframe",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"properties",
",",
"text_types",
")",
... | Retrieve the specified properties from PubChem.
:param identifier: The compound, substance or assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
:param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity.
:param as... | [
"Retrieve",
"the",
"specified",
"properties",
"from",
"PubChem",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L398-L415 | train |
mcs07/PubChemPy | pubchempy.py | deprecated | def deprecated(message=None):
"""Decorator to mark functions as deprecated. A warning will be emitted when the function is used."""
def deco(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
warnings.warn(
message or 'Call to deprecated function {}'.format(f... | python | def deprecated(message=None):
"""Decorator to mark functions as deprecated. A warning will be emitted when the function is used."""
def deco(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
warnings.warn(
message or 'Call to deprecated function {}'.format(f... | [
"def",
"deprecated",
"(",
"message",
"=",
"None",
")",
":",
"def",
"deco",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"... | Decorator to mark functions as deprecated. A warning will be emitted when the function is used. | [
"Decorator",
"to",
"mark",
"functions",
"as",
"deprecated",
".",
"A",
"warning",
"will",
"be",
"emitted",
"when",
"the",
"function",
"is",
"used",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L485-L497 | train |
mcs07/PubChemPy | pubchempy.py | _parse_prop | def _parse_prop(search, proplist):
"""Extract property value from record using the given urn search filter."""
props = [i for i in proplist if all(item in i['urn'].items() for item in search.items())]
if len(props) > 0:
return props[0]['value'][list(props[0]['value'].keys())[0]] | python | def _parse_prop(search, proplist):
"""Extract property value from record using the given urn search filter."""
props = [i for i in proplist if all(item in i['urn'].items() for item in search.items())]
if len(props) > 0:
return props[0]['value'][list(props[0]['value'].keys())[0]] | [
"def",
"_parse_prop",
"(",
"search",
",",
"proplist",
")",
":",
"props",
"=",
"[",
"i",
"for",
"i",
"in",
"proplist",
"if",
"all",
"(",
"item",
"in",
"i",
"[",
"'urn'",
"]",
".",
"items",
"(",
")",
"for",
"item",
"in",
"search",
".",
"items",
"("... | Extract property value from record using the given urn search filter. | [
"Extract",
"property",
"value",
"from",
"record",
"using",
"the",
"given",
"urn",
"search",
"filter",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1027-L1031 | train |
mcs07/PubChemPy | pubchempy.py | Atom.to_dict | def to_dict(self):
"""Return a dictionary containing Atom data."""
data = {'aid': self.aid, 'number': self.number, 'element': self.element}
for coord in {'x', 'y', 'z'}:
if getattr(self, coord) is not None:
data[coord] = getattr(self, coord)
if self.charge is ... | python | def to_dict(self):
"""Return a dictionary containing Atom data."""
data = {'aid': self.aid, 'number': self.number, 'element': self.element}
for coord in {'x', 'y', 'z'}:
if getattr(self, coord) is not None:
data[coord] = getattr(self, coord)
if self.charge is ... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'aid'",
":",
"self",
".",
"aid",
",",
"'number'",
":",
"self",
".",
"number",
",",
"'element'",
":",
"self",
".",
"element",
"}",
"for",
"coord",
"in",
"{",
"'x'",
",",
"'y'",
",",
"'z'"... | Return a dictionary containing Atom data. | [
"Return",
"a",
"dictionary",
"containing",
"Atom",
"data",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L557-L565 | train |
mcs07/PubChemPy | pubchempy.py | Atom.set_coordinates | def set_coordinates(self, x, y, z=None):
"""Set all coordinate dimensions at once."""
self.x = x
self.y = y
self.z = z | python | def set_coordinates(self, x, y, z=None):
"""Set all coordinate dimensions at once."""
self.x = x
self.y = y
self.z = z | [
"def",
"set_coordinates",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
"=",
"None",
")",
":",
"self",
".",
"x",
"=",
"x",
"self",
".",
"y",
"=",
"y",
"self",
".",
"z",
"=",
"z"
] | Set all coordinate dimensions at once. | [
"Set",
"all",
"coordinate",
"dimensions",
"at",
"once",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L567-L571 | train |
mcs07/PubChemPy | pubchempy.py | Bond.to_dict | def to_dict(self):
"""Return a dictionary containing Bond data."""
data = {'aid1': self.aid1, 'aid2': self.aid2, 'order': self.order}
if self.style is not None:
data['style'] = self.style
return data | python | def to_dict(self):
"""Return a dictionary containing Bond data."""
data = {'aid1': self.aid1, 'aid2': self.aid2, 'order': self.order}
if self.style is not None:
data['style'] = self.style
return data | [
"def",
"to_dict",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'aid1'",
":",
"self",
".",
"aid1",
",",
"'aid2'",
":",
"self",
".",
"aid2",
",",
"'order'",
":",
"self",
".",
"order",
"}",
"if",
"self",
".",
"style",
"is",
"not",
"None",
":",
"data",
... | Return a dictionary containing Bond data. | [
"Return",
"a",
"dictionary",
"containing",
"Bond",
"data",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L631-L636 | train |
mcs07/PubChemPy | pubchempy.py | Compound._setup_atoms | def _setup_atoms(self):
"""Derive Atom objects from the record."""
# Delete existing atoms
self._atoms = {}
# Create atoms
aids = self.record['atoms']['aid']
elements = self.record['atoms']['element']
if not len(aids) == len(elements):
raise ResponsePa... | python | def _setup_atoms(self):
"""Derive Atom objects from the record."""
# Delete existing atoms
self._atoms = {}
# Create atoms
aids = self.record['atoms']['aid']
elements = self.record['atoms']['element']
if not len(aids) == len(elements):
raise ResponsePa... | [
"def",
"_setup_atoms",
"(",
"self",
")",
":",
"self",
".",
"_atoms",
"=",
"{",
"}",
"aids",
"=",
"self",
".",
"record",
"[",
"'atoms'",
"]",
"[",
"'aid'",
"]",
"elements",
"=",
"self",
".",
"record",
"[",
"'atoms'",
"]",
"[",
"'element'",
"]",
"if"... | Derive Atom objects from the record. | [
"Derive",
"Atom",
"objects",
"from",
"the",
"record",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L669-L693 | train |
mcs07/PubChemPy | pubchempy.py | Compound._setup_bonds | def _setup_bonds(self):
"""Derive Bond objects from the record."""
self._bonds = {}
if 'bonds' not in self.record:
return
# Create bonds
aid1s = self.record['bonds']['aid1']
aid2s = self.record['bonds']['aid2']
orders = self.record['bonds']['order']
... | python | def _setup_bonds(self):
"""Derive Bond objects from the record."""
self._bonds = {}
if 'bonds' not in self.record:
return
# Create bonds
aid1s = self.record['bonds']['aid1']
aid2s = self.record['bonds']['aid2']
orders = self.record['bonds']['order']
... | [
"def",
"_setup_bonds",
"(",
"self",
")",
":",
"self",
".",
"_bonds",
"=",
"{",
"}",
"if",
"'bonds'",
"not",
"in",
"self",
".",
"record",
":",
"return",
"aid1s",
"=",
"self",
".",
"record",
"[",
"'bonds'",
"]",
"[",
"'aid1'",
"]",
"aid2s",
"=",
"sel... | Derive Bond objects from the record. | [
"Derive",
"Bond",
"objects",
"from",
"the",
"record",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L695-L714 | train |
mcs07/PubChemPy | pubchempy.py | Compound.from_cid | def from_cid(cls, cid, **kwargs):
"""Retrieve the Compound record for the specified CID.
Usage::
c = Compound.from_cid(6819)
:param int cid: The PubChem Compound Identifier (CID).
"""
record = json.loads(request(cid, **kwargs).read().decode())['PC_Compounds'][0]
... | python | def from_cid(cls, cid, **kwargs):
"""Retrieve the Compound record for the specified CID.
Usage::
c = Compound.from_cid(6819)
:param int cid: The PubChem Compound Identifier (CID).
"""
record = json.loads(request(cid, **kwargs).read().decode())['PC_Compounds'][0]
... | [
"def",
"from_cid",
"(",
"cls",
",",
"cid",
",",
"**",
"kwargs",
")",
":",
"record",
"=",
"json",
".",
"loads",
"(",
"request",
"(",
"cid",
",",
"**",
"kwargs",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
")",
"[",
"'PC_Compounds'",
"]",
... | Retrieve the Compound record for the specified CID.
Usage::
c = Compound.from_cid(6819)
:param int cid: The PubChem Compound Identifier (CID). | [
"Retrieve",
"the",
"Compound",
"record",
"for",
"the",
"specified",
"CID",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L717-L727 | train |
mcs07/PubChemPy | pubchempy.py | Compound.to_dict | def to_dict(self, properties=None):
"""Return a dictionary containing Compound data. Optionally specify a list of the desired properties.
synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is
because they each require an extra request.
... | python | def to_dict(self, properties=None):
"""Return a dictionary containing Compound data. Optionally specify a list of the desired properties.
synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is
because they each require an extra request.
... | [
"def",
"to_dict",
"(",
"self",
",",
"properties",
"=",
"None",
")",
":",
"if",
"not",
"properties",
":",
"skip",
"=",
"{",
"'aids'",
",",
"'sids'",
",",
"'synonyms'",
"}",
"properties",
"=",
"[",
"p",
"for",
"p",
"in",
"dir",
"(",
"Compound",
")",
... | Return a dictionary containing Compound data. Optionally specify a list of the desired properties.
synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is
because they each require an extra request. | [
"Return",
"a",
"dictionary",
"containing",
"Compound",
"data",
".",
"Optionally",
"specify",
"a",
"list",
"of",
"the",
"desired",
"properties",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L735-L744 | train |
mcs07/PubChemPy | pubchempy.py | Compound.synonyms | def synonyms(self):
"""A ranked list of all the names associated with this Compound.
Requires an extra request. Result is cached.
"""
if self.cid:
results = get_json(self.cid, operation='synonyms')
return results['InformationList']['Information'][0]['Synonym'] if... | python | def synonyms(self):
"""A ranked list of all the names associated with this Compound.
Requires an extra request. Result is cached.
"""
if self.cid:
results = get_json(self.cid, operation='synonyms')
return results['InformationList']['Information'][0]['Synonym'] if... | [
"def",
"synonyms",
"(",
"self",
")",
":",
"if",
"self",
".",
"cid",
":",
"results",
"=",
"get_json",
"(",
"self",
".",
"cid",
",",
"operation",
"=",
"'synonyms'",
")",
"return",
"results",
"[",
"'InformationList'",
"]",
"[",
"'Information'",
"]",
"[",
... | A ranked list of all the names associated with this Compound.
Requires an extra request. Result is cached. | [
"A",
"ranked",
"list",
"of",
"all",
"the",
"names",
"associated",
"with",
"this",
"Compound",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L785-L792 | train |
mcs07/PubChemPy | pubchempy.py | Substance.from_sid | def from_sid(cls, sid):
"""Retrieve the Substance record for the specified SID.
:param int sid: The PubChem Substance Identifier (SID).
"""
record = json.loads(request(sid, 'sid', 'substance').read().decode())['PC_Substances'][0]
return cls(record) | python | def from_sid(cls, sid):
"""Retrieve the Substance record for the specified SID.
:param int sid: The PubChem Substance Identifier (SID).
"""
record = json.loads(request(sid, 'sid', 'substance').read().decode())['PC_Substances'][0]
return cls(record) | [
"def",
"from_sid",
"(",
"cls",
",",
"sid",
")",
":",
"record",
"=",
"json",
".",
"loads",
"(",
"request",
"(",
"sid",
",",
"'sid'",
",",
"'substance'",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
")",
"[",
"'PC_Substances'",
"]",
"[",
"0... | Retrieve the Substance record for the specified SID.
:param int sid: The PubChem Substance Identifier (SID). | [
"Retrieve",
"the",
"Substance",
"record",
"for",
"the",
"specified",
"SID",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1047-L1053 | train |
mcs07/PubChemPy | pubchempy.py | Substance.to_dict | def to_dict(self, properties=None):
"""Return a dictionary containing Substance data.
If the properties parameter is not specified, everything except cids and aids is included. This is because the
aids and cids properties each require an extra request to retrieve.
:param properties: (o... | python | def to_dict(self, properties=None):
"""Return a dictionary containing Substance data.
If the properties parameter is not specified, everything except cids and aids is included. This is because the
aids and cids properties each require an extra request to retrieve.
:param properties: (o... | [
"def",
"to_dict",
"(",
"self",
",",
"properties",
"=",
"None",
")",
":",
"if",
"not",
"properties",
":",
"skip",
"=",
"{",
"'deposited_compound'",
",",
"'standardized_compound'",
",",
"'cids'",
",",
"'aids'",
"}",
"properties",
"=",
"[",
"p",
"for",
"p",
... | Return a dictionary containing Substance data.
If the properties parameter is not specified, everything except cids and aids is included. This is because the
aids and cids properties each require an extra request to retrieve.
:param properties: (optional) A list of the desired properties. | [
"Return",
"a",
"dictionary",
"containing",
"Substance",
"data",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1065-L1076 | train |
mcs07/PubChemPy | pubchempy.py | Assay.from_aid | def from_aid(cls, aid):
"""Retrieve the Assay record for the specified AID.
:param int aid: The PubChem Assay Identifier (AID).
"""
record = json.loads(request(aid, 'aid', 'assay', 'description').read().decode())['PC_AssayContainer'][0]
return cls(record) | python | def from_aid(cls, aid):
"""Retrieve the Assay record for the specified AID.
:param int aid: The PubChem Assay Identifier (AID).
"""
record = json.loads(request(aid, 'aid', 'assay', 'description').read().decode())['PC_AssayContainer'][0]
return cls(record) | [
"def",
"from_aid",
"(",
"cls",
",",
"aid",
")",
":",
"record",
"=",
"json",
".",
"loads",
"(",
"request",
"(",
"aid",
",",
"'aid'",
",",
"'assay'",
",",
"'description'",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
")",
"[",
"'PC_AssayConta... | Retrieve the Assay record for the specified AID.
:param int aid: The PubChem Assay Identifier (AID). | [
"Retrieve",
"the",
"Assay",
"record",
"for",
"the",
"specified",
"AID",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1160-L1166 | train |
mcs07/PubChemPy | pubchempy.py | Assay.to_dict | def to_dict(self, properties=None):
"""Return a dictionary containing Assay data.
If the properties parameter is not specified, everything is included.
:param properties: (optional) A list of the desired properties.
"""
if not properties:
properties = [p for p in di... | python | def to_dict(self, properties=None):
"""Return a dictionary containing Assay data.
If the properties parameter is not specified, everything is included.
:param properties: (optional) A list of the desired properties.
"""
if not properties:
properties = [p for p in di... | [
"def",
"to_dict",
"(",
"self",
",",
"properties",
"=",
"None",
")",
":",
"if",
"not",
"properties",
":",
"properties",
"=",
"[",
"p",
"for",
"p",
"in",
"dir",
"(",
"Assay",
")",
"if",
"isinstance",
"(",
"getattr",
"(",
"Assay",
",",
"p",
")",
",",
... | Return a dictionary containing Assay data.
If the properties parameter is not specified, everything is included.
:param properties: (optional) A list of the desired properties. | [
"Return",
"a",
"dictionary",
"containing",
"Assay",
"data",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1178-L1187 | train |
tadeck/onetimepass | onetimepass/__init__.py | _is_possible_token | def _is_possible_token(token, token_length=6):
"""Determines if given value is acceptable as a token. Used when validating
tokens.
Currently allows only numeric tokens no longer than 6 chars.
:param token: token value to be checked
:type token: int or str
:param token_length: allowed length of... | python | def _is_possible_token(token, token_length=6):
"""Determines if given value is acceptable as a token. Used when validating
tokens.
Currently allows only numeric tokens no longer than 6 chars.
:param token: token value to be checked
:type token: int or str
:param token_length: allowed length of... | [
"def",
"_is_possible_token",
"(",
"token",
",",
"token_length",
"=",
"6",
")",
":",
"if",
"not",
"isinstance",
"(",
"token",
",",
"bytes",
")",
":",
"token",
"=",
"six",
".",
"b",
"(",
"str",
"(",
"token",
")",
")",
"return",
"token",
".",
"isdigit",... | Determines if given value is acceptable as a token. Used when validating
tokens.
Currently allows only numeric tokens no longer than 6 chars.
:param token: token value to be checked
:type token: int or str
:param token_length: allowed length of token
:type token_length: int
:return: True i... | [
"Determines",
"if",
"given",
"value",
"is",
"acceptable",
"as",
"a",
"token",
".",
"Used",
"when",
"validating",
"tokens",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L44-L68 | train |
tadeck/onetimepass | onetimepass/__init__.py | get_hotp | def get_hotp(
secret,
intervals_no,
as_string=False,
casefold=True,
digest_method=hashlib.sha1,
token_length=6,
):
"""
Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as se... | python | def get_hotp(
secret,
intervals_no,
as_string=False,
casefold=True,
digest_method=hashlib.sha1,
token_length=6,
):
"""
Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as se... | [
"def",
"get_hotp",
"(",
"secret",
",",
"intervals_no",
",",
"as_string",
"=",
"False",
",",
"casefold",
"=",
"True",
",",
"digest_method",
"=",
"hashlib",
".",
"sha1",
",",
"token_length",
"=",
"6",
",",
")",
":",
"if",
"isinstance",
"(",
"secret",
",",
... | Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as secret key
:type secret: str or unicode
:param intervals_no: interval number used for getting different tokens, it
is incremented with each use
:type interva... | [
"Get",
"HMAC",
"-",
"based",
"one",
"-",
"time",
"password",
"on",
"the",
"basis",
"of",
"given",
"secret",
"and",
"interval",
"number",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L71-L126 | train |
tadeck/onetimepass | onetimepass/__init__.py | get_totp | def get_totp(
secret,
as_string=False,
digest_method=hashlib.sha1,
token_length=6,
interval_length=30,
clock=None,
):
"""Get time-based one-time password on the basis of given secret and time.
:param secret: the base32-encoded string acting as secret key
:typ... | python | def get_totp(
secret,
as_string=False,
digest_method=hashlib.sha1,
token_length=6,
interval_length=30,
clock=None,
):
"""Get time-based one-time password on the basis of given secret and time.
:param secret: the base32-encoded string acting as secret key
:typ... | [
"def",
"get_totp",
"(",
"secret",
",",
"as_string",
"=",
"False",
",",
"digest_method",
"=",
"hashlib",
".",
"sha1",
",",
"token_length",
"=",
"6",
",",
"interval_length",
"=",
"30",
",",
"clock",
"=",
"None",
",",
")",
":",
"if",
"clock",
"is",
"None"... | Get time-based one-time password on the basis of given secret and time.
:param secret: the base32-encoded string acting as secret key
:type secret: str
:param as_string: True if result should be padded string, False otherwise
:type as_string: bool
:param digest_method: method of generating digest (... | [
"Get",
"time",
"-",
"based",
"one",
"-",
"time",
"password",
"on",
"the",
"basis",
"of",
"given",
"secret",
"and",
"time",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L129-L170 | train |
tadeck/onetimepass | onetimepass/__init__.py | valid_hotp | def valid_hotp(
token,
secret,
last=1,
trials=1000,
digest_method=hashlib.sha1,
token_length=6,
):
"""Check if given token is valid for given secret. Return interval number
that was successful, or False if not found.
:param token: token being checked
:typ... | python | def valid_hotp(
token,
secret,
last=1,
trials=1000,
digest_method=hashlib.sha1,
token_length=6,
):
"""Check if given token is valid for given secret. Return interval number
that was successful, or False if not found.
:param token: token being checked
:typ... | [
"def",
"valid_hotp",
"(",
"token",
",",
"secret",
",",
"last",
"=",
"1",
",",
"trials",
"=",
"1000",
",",
"digest_method",
"=",
"hashlib",
".",
"sha1",
",",
"token_length",
"=",
"6",
",",
")",
":",
"if",
"not",
"_is_possible_token",
"(",
"token",
",",
... | Check if given token is valid for given secret. Return interval number
that was successful, or False if not found.
:param token: token being checked
:type token: int or str
:param secret: secret for which token is checked
:type secret: str
:param last: last used interval (start checking with ne... | [
"Check",
"if",
"given",
"token",
"is",
"valid",
"for",
"given",
"secret",
".",
"Return",
"interval",
"number",
"that",
"was",
"successful",
"or",
"False",
"if",
"not",
"found",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L173-L218 | train |
tadeck/onetimepass | onetimepass/__init__.py | valid_totp | def valid_totp(
token,
secret,
digest_method=hashlib.sha1,
token_length=6,
interval_length=30,
clock=None,
window=0,
):
"""Check if given token is valid time-based one-time password for given
secret.
:param token: token which is being checked
:typ... | python | def valid_totp(
token,
secret,
digest_method=hashlib.sha1,
token_length=6,
interval_length=30,
clock=None,
window=0,
):
"""Check if given token is valid time-based one-time password for given
secret.
:param token: token which is being checked
:typ... | [
"def",
"valid_totp",
"(",
"token",
",",
"secret",
",",
"digest_method",
"=",
"hashlib",
".",
"sha1",
",",
"token_length",
"=",
"6",
",",
"interval_length",
"=",
"30",
",",
"clock",
"=",
"None",
",",
"window",
"=",
"0",
",",
")",
":",
"if",
"_is_possibl... | Check if given token is valid time-based one-time password for given
secret.
:param token: token which is being checked
:type token: int or str
:param secret: secret for which the token is being checked
:type secret: str
:param digest_method: method of generating digest (hashlib.sha1 by default... | [
"Check",
"if",
"given",
"token",
"is",
"valid",
"time",
"-",
"based",
"one",
"-",
"time",
"password",
"for",
"given",
"secret",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L221-L276 | train |
uber/multidimensional_urlencode | multidimensional_urlencode/urlencoder.py | parametrize | def parametrize(params):
"""Return list of params as params.
>>> parametrize(['a'])
'a'
>>> parametrize(['a', 'b'])
'a[b]'
>>> parametrize(['a', 'b', 'c'])
'a[b][c]'
"""
returned = str(params[0])
returned += "".join("[" + str(p) + "]" for p in params[1:])
return returned | python | def parametrize(params):
"""Return list of params as params.
>>> parametrize(['a'])
'a'
>>> parametrize(['a', 'b'])
'a[b]'
>>> parametrize(['a', 'b', 'c'])
'a[b][c]'
"""
returned = str(params[0])
returned += "".join("[" + str(p) + "]" for p in params[1:])
return returned | [
"def",
"parametrize",
"(",
"params",
")",
":",
"returned",
"=",
"str",
"(",
"params",
"[",
"0",
"]",
")",
"returned",
"+=",
"\"\"",
".",
"join",
"(",
"\"[\"",
"+",
"str",
"(",
"p",
")",
"+",
"\"]\"",
"for",
"p",
"in",
"params",
"[",
"1",
":",
"... | Return list of params as params.
>>> parametrize(['a'])
'a'
>>> parametrize(['a', 'b'])
'a[b]'
>>> parametrize(['a', 'b', 'c'])
'a[b][c]' | [
"Return",
"list",
"of",
"params",
"as",
"params",
"."
] | f626528bc3535503fa1557a53bbfacaa29920251 | https://github.com/uber/multidimensional_urlencode/blob/f626528bc3535503fa1557a53bbfacaa29920251/multidimensional_urlencode/urlencoder.py#L41-L54 | train |
uber/multidimensional_urlencode | multidimensional_urlencode/urlencoder.py | urlencode | def urlencode(params):
"""Urlencode a multidimensional dict."""
# Not doing duck typing here. Will make debugging easier.
if not isinstance(params, dict):
raise TypeError("Only dicts are supported.")
params = flatten(params)
url_params = OrderedDict()
for param in params:
valu... | python | def urlencode(params):
"""Urlencode a multidimensional dict."""
# Not doing duck typing here. Will make debugging easier.
if not isinstance(params, dict):
raise TypeError("Only dicts are supported.")
params = flatten(params)
url_params = OrderedDict()
for param in params:
valu... | [
"def",
"urlencode",
"(",
"params",
")",
":",
"if",
"not",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Only dicts are supported.\"",
")",
"params",
"=",
"flatten",
"(",
"params",
")",
"url_params",
"=",
"OrderedDict",
"("... | Urlencode a multidimensional dict. | [
"Urlencode",
"a",
"multidimensional",
"dict",
"."
] | f626528bc3535503fa1557a53bbfacaa29920251 | https://github.com/uber/multidimensional_urlencode/blob/f626528bc3535503fa1557a53bbfacaa29920251/multidimensional_urlencode/urlencoder.py#L57-L76 | train |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | find_matlab_root | def find_matlab_root():
"""Look for matlab binary and return root directory of MATLAB
installation.
"""
matlab_root = None
path_dirs = os.environ.get("PATH").split(os.pathsep)
for path_dir in path_dirs:
candidate = realpath(join(path_dir, 'matlab'))
if isfile(candidate) or isfi... | python | def find_matlab_root():
"""Look for matlab binary and return root directory of MATLAB
installation.
"""
matlab_root = None
path_dirs = os.environ.get("PATH").split(os.pathsep)
for path_dir in path_dirs:
candidate = realpath(join(path_dir, 'matlab'))
if isfile(candidate) or isfi... | [
"def",
"find_matlab_root",
"(",
")",
":",
"matlab_root",
"=",
"None",
"path_dirs",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PATH\"",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"for",
"path_dir",
"in",
"path_dirs",
":",
"candidate",
"=",
"... | Look for matlab binary and return root directory of MATLAB
installation. | [
"Look",
"for",
"matlab",
"binary",
"and",
"return",
"root",
"directory",
"of",
"MATLAB",
"installation",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L246-L260 | train |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | load_engine_and_libs | def load_engine_and_libs(matlab_root, options):
"""Load and return `libeng` and `libmx`. Start and return MATLAB
engine.
Returns
-------
engine
libeng
libmx
"""
if sys.maxsize > 2**32:
bits = '64bit'
else:
bits = '32bit'
system = platform.system()
if ... | python | def load_engine_and_libs(matlab_root, options):
"""Load and return `libeng` and `libmx`. Start and return MATLAB
engine.
Returns
-------
engine
libeng
libmx
"""
if sys.maxsize > 2**32:
bits = '64bit'
else:
bits = '32bit'
system = platform.system()
if ... | [
"def",
"load_engine_and_libs",
"(",
"matlab_root",
",",
"options",
")",
":",
"if",
"sys",
".",
"maxsize",
">",
"2",
"**",
"32",
":",
"bits",
"=",
"'64bit'",
"else",
":",
"bits",
"=",
"'32bit'",
"system",
"=",
"platform",
".",
"system",
"(",
")",
"if",
... | Load and return `libeng` and `libmx`. Start and return MATLAB
engine.
Returns
-------
engine
libeng
libmx | [
"Load",
"and",
"return",
"libeng",
"and",
"libmx",
".",
"Start",
"and",
"return",
"MATLAB",
"engine",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L263-L363 | train |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | check_python_matlab_architecture | def check_python_matlab_architecture(bits, lib_dir):
"""Make sure we can find corresponding installation of Python and MATLAB."""
if not os.path.isdir(lib_dir):
raise RuntimeError("It seem that you are using {bits} version of Python, but there's no matching MATLAB installation in {lib_dir}.".format(bits... | python | def check_python_matlab_architecture(bits, lib_dir):
"""Make sure we can find corresponding installation of Python and MATLAB."""
if not os.path.isdir(lib_dir):
raise RuntimeError("It seem that you are using {bits} version of Python, but there's no matching MATLAB installation in {lib_dir}.".format(bits... | [
"def",
"check_python_matlab_architecture",
"(",
"bits",
",",
"lib_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"lib_dir",
")",
":",
"raise",
"RuntimeError",
"(",
"\"It seem that you are using {bits} version of Python, but there's no matching MATLAB i... | Make sure we can find corresponding installation of Python and MATLAB. | [
"Make",
"sure",
"we",
"can",
"find",
"corresponding",
"installation",
"of",
"Python",
"and",
"MATLAB",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L366-L369 | train |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | MatlabSession.eval | def eval(self, expression):
"""Evaluate `expression` in MATLAB engine.
Parameters
----------
expression : str
Expression is passed to MATLAB engine and evaluated.
"""
expression_wrapped = wrap_script.format(expression)
### Evaluate the expression
... | python | def eval(self, expression):
"""Evaluate `expression` in MATLAB engine.
Parameters
----------
expression : str
Expression is passed to MATLAB engine and evaluated.
"""
expression_wrapped = wrap_script.format(expression)
### Evaluate the expression
... | [
"def",
"eval",
"(",
"self",
",",
"expression",
")",
":",
"expression_wrapped",
"=",
"wrap_script",
".",
"format",
"(",
"expression",
")",
"self",
".",
"_libeng",
".",
"engEvalString",
"(",
"self",
".",
"_ep",
",",
"expression_wrapped",
")",
"mxresult",
"=",
... | Evaluate `expression` in MATLAB engine.
Parameters
----------
expression : str
Expression is passed to MATLAB engine and evaluated. | [
"Evaluate",
"expression",
"in",
"MATLAB",
"engine",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L161-L184 | train |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | MatlabSession.get | def get(self, name):
"""Get variable `name` from MATLAB workspace.
Parameters
----------
name : str
Name of the variable in MATLAB workspace.
Returns
-------
array_like
Value of the variable `name`.
"""
pm = self._libeng.... | python | def get(self, name):
"""Get variable `name` from MATLAB workspace.
Parameters
----------
name : str
Name of the variable in MATLAB workspace.
Returns
-------
array_like
Value of the variable `name`.
"""
pm = self._libeng.... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"pm",
"=",
"self",
".",
"_libeng",
".",
"engGetVariable",
"(",
"self",
".",
"_ep",
",",
"name",
")",
"out",
"=",
"mxarray_to_ndarray",
"(",
"self",
".",
"_libmx",
",",
"pm",
")",
"self",
".",
"_libm... | Get variable `name` from MATLAB workspace.
Parameters
----------
name : str
Name of the variable in MATLAB workspace.
Returns
-------
array_like
Value of the variable `name`. | [
"Get",
"variable",
"name",
"from",
"MATLAB",
"workspace",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L188-L209 | train |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | MatlabSession.put | def put(self, name, value):
"""Put a variable to MATLAB workspace.
"""
pm = ndarray_to_mxarray(self._libmx, value)
self._libeng.engPutVariable(self._ep, name, pm)
self._libmx.mxDestroyArray(pm) | python | def put(self, name, value):
"""Put a variable to MATLAB workspace.
"""
pm = ndarray_to_mxarray(self._libmx, value)
self._libeng.engPutVariable(self._ep, name, pm)
self._libmx.mxDestroyArray(pm) | [
"def",
"put",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"pm",
"=",
"ndarray_to_mxarray",
"(",
"self",
".",
"_libmx",
",",
"value",
")",
"self",
".",
"_libeng",
".",
"engPutVariable",
"(",
"self",
".",
"_ep",
",",
"name",
",",
"pm",
")",
"se... | Put a variable to MATLAB workspace. | [
"Put",
"a",
"variable",
"to",
"MATLAB",
"workspace",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L214-L223 | train |
mesosphere/deimos | deimos/cleanup.py | Cleanup.dirs | def dirs(self, before=time.time(), exited=True):
"""
Provider a generator of container state directories.
If exited is None, all are returned. If it is False, unexited
containers are returned. If it is True, only exited containers are
returned.
"""
timestamp = is... | python | def dirs(self, before=time.time(), exited=True):
"""
Provider a generator of container state directories.
If exited is None, all are returned. If it is False, unexited
containers are returned. If it is True, only exited containers are
returned.
"""
timestamp = is... | [
"def",
"dirs",
"(",
"self",
",",
"before",
"=",
"time",
".",
"time",
"(",
")",
",",
"exited",
"=",
"True",
")",
":",
"timestamp",
"=",
"iso",
"(",
"before",
")",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"root",
",",
"\"sta... | Provider a generator of container state directories.
If exited is None, all are returned. If it is False, unexited
containers are returned. If it is True, only exited containers are
returned. | [
"Provider",
"a",
"generator",
"of",
"container",
"state",
"directories",
"."
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/cleanup.py#L21-L40 | train |
mesosphere/deimos | deimos/containerizer/__init__.py | methods | def methods():
"Names of operations provided by containerizers, as a set."
pairs = inspect.getmembers(Containerizer, predicate=inspect.ismethod)
return set(k for k, _ in pairs if k[0:1] != "_") | python | def methods():
"Names of operations provided by containerizers, as a set."
pairs = inspect.getmembers(Containerizer, predicate=inspect.ismethod)
return set(k for k, _ in pairs if k[0:1] != "_") | [
"def",
"methods",
"(",
")",
":",
"\"Names of operations provided by containerizers, as a set.\"",
"pairs",
"=",
"inspect",
".",
"getmembers",
"(",
"Containerizer",
",",
"predicate",
"=",
"inspect",
".",
"ismethod",
")",
"return",
"set",
"(",
"k",
"for",
"k",
",",
... | Names of operations provided by containerizers, as a set. | [
"Names",
"of",
"operations",
"provided",
"by",
"containerizers",
"as",
"a",
"set",
"."
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/containerizer/__init__.py#L49-L52 | train |
mesosphere/deimos | deimos/containerizer/__init__.py | stdio | def stdio(containerizer, *args):
"""Connect containerizer class to command line args and STDIN
Dispatches to an appropriate containerizer method based on the first
argument and parses the input using an appropriate Protobuf type.
launch < containerizer::Launch
update < containerizer::Updat... | python | def stdio(containerizer, *args):
"""Connect containerizer class to command line args and STDIN
Dispatches to an appropriate containerizer method based on the first
argument and parses the input using an appropriate Protobuf type.
launch < containerizer::Launch
update < containerizer::Updat... | [
"def",
"stdio",
"(",
"containerizer",
",",
"*",
"args",
")",
":",
"try",
":",
"name",
"=",
"args",
"[",
"0",
"]",
"method",
",",
"proto",
"=",
"{",
"\"launch\"",
":",
"(",
"containerizer",
".",
"launch",
",",
"Launch",
")",
",",
"\"update\"",
":",
... | Connect containerizer class to command line args and STDIN
Dispatches to an appropriate containerizer method based on the first
argument and parses the input using an appropriate Protobuf type.
launch < containerizer::Launch
update < containerizer::Update
usage < containerizer::Usage >... | [
"Connect",
"containerizer",
"class",
"to",
"command",
"line",
"args",
"and",
"STDIN"
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/containerizer/__init__.py#L57-L100 | train |
mesosphere/deimos | deimos/cgroups.py | construct | def construct(path, name=None):
"Selects an appropriate CGroup subclass for the given CGroup path."
name = name if name else path.split("/")[4]
classes = {"memory": Memory,
"cpu": CPU,
"cpuacct": CPUAcct}
constructor = classes.get(name, CGroup)
log.debug("Chose %s for: ... | python | def construct(path, name=None):
"Selects an appropriate CGroup subclass for the given CGroup path."
name = name if name else path.split("/")[4]
classes = {"memory": Memory,
"cpu": CPU,
"cpuacct": CPUAcct}
constructor = classes.get(name, CGroup)
log.debug("Chose %s for: ... | [
"def",
"construct",
"(",
"path",
",",
"name",
"=",
"None",
")",
":",
"\"Selects an appropriate CGroup subclass for the given CGroup path.\"",
"name",
"=",
"name",
"if",
"name",
"else",
"path",
".",
"split",
"(",
"\"/\"",
")",
"[",
"4",
"]",
"classes",
"=",
"{"... | Selects an appropriate CGroup subclass for the given CGroup path. | [
"Selects",
"an",
"appropriate",
"CGroup",
"subclass",
"for",
"the",
"given",
"CGroup",
"path",
"."
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/cgroups.py#L43-L51 | train |
mesosphere/deimos | deimos/proto.py | serialize | def serialize(cls, **properties):
"""
With a Protobuf class and properties as keyword arguments, sets all the
properties on a new instance of the class and serializes the resulting
value.
"""
obj = cls()
for k, v in properties.iteritems():
log.debug("%s.%s = %r", cls.__name__, k, v)
... | python | def serialize(cls, **properties):
"""
With a Protobuf class and properties as keyword arguments, sets all the
properties on a new instance of the class and serializes the resulting
value.
"""
obj = cls()
for k, v in properties.iteritems():
log.debug("%s.%s = %r", cls.__name__, k, v)
... | [
"def",
"serialize",
"(",
"cls",
",",
"**",
"properties",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"for",
"k",
",",
"v",
"in",
"properties",
".",
"iteritems",
"(",
")",
":",
"log",
".",
"debug",
"(",
"\"%s.%s = %r\"",
",",
"cls",
".",
"__name__",
",",... | With a Protobuf class and properties as keyword arguments, sets all the
properties on a new instance of the class and serializes the resulting
value. | [
"With",
"a",
"Protobuf",
"class",
"and",
"properties",
"as",
"keyword",
"arguments",
"sets",
"all",
"the",
"properties",
"on",
"a",
"new",
"instance",
"of",
"the",
"class",
"and",
"serializes",
"the",
"resulting",
"value",
"."
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/proto.py#L41-L51 | train |
mesosphere/deimos | deimos/logger.py | logger | def logger(height=1): # http://stackoverflow.com/a/900404/48251
"""
Obtain a function logger for the calling function. Uses the inspect module
to find the name of the calling function and its position in the module
hierarchy. With the optional height argument, logs for caller's caller, a... | python | def logger(height=1): # http://stackoverflow.com/a/900404/48251
"""
Obtain a function logger for the calling function. Uses the inspect module
to find the name of the calling function and its position in the module
hierarchy. With the optional height argument, logs for caller's caller, a... | [
"def",
"logger",
"(",
"height",
"=",
"1",
")",
":",
"caller",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"height",
"]",
"scope",
"=",
"caller",
"[",
"0",
"]",
".",
"f_globals",
"function",
"=",
"caller",
"[",
"3",
"]",
"path",
"=",
"scope",
"["... | Obtain a function logger for the calling function. Uses the inspect module
to find the name of the calling function and its position in the module
hierarchy. With the optional height argument, logs for caller's caller, and
so forth. | [
"Obtain",
"a",
"function",
"logger",
"for",
"the",
"calling",
"function",
".",
"Uses",
"the",
"inspect",
"module",
"to",
"find",
"the",
"name",
"of",
"the",
"calling",
"function",
"and",
"its",
"position",
"in",
"the",
"module",
"hierarchy",
".",
"With",
"... | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/logger.py#L65-L78 | train |
googlecolab/jupyter_http_over_ws | jupyter_http_over_ws/__init__.py | load_jupyter_server_extension | def load_jupyter_server_extension(nb_server_app):
"""Called by Jupyter when this module is loaded as a server extension."""
app = nb_server_app.web_app
host_pattern = '.*$'
app.add_handlers(host_pattern, [
(utils.url_path_join(app.settings['base_url'], '/http_over_websocket'),
handlers.HttpOverWeb... | python | def load_jupyter_server_extension(nb_server_app):
"""Called by Jupyter when this module is loaded as a server extension."""
app = nb_server_app.web_app
host_pattern = '.*$'
app.add_handlers(host_pattern, [
(utils.url_path_join(app.settings['base_url'], '/http_over_websocket'),
handlers.HttpOverWeb... | [
"def",
"load_jupyter_server_extension",
"(",
"nb_server_app",
")",
":",
"app",
"=",
"nb_server_app",
".",
"web_app",
"host_pattern",
"=",
"'.*$'",
"app",
".",
"add_handlers",
"(",
"host_pattern",
",",
"[",
"(",
"utils",
".",
"url_path_join",
"(",
"app",
".",
"... | Called by Jupyter when this module is loaded as a server extension. | [
"Called",
"by",
"Jupyter",
"when",
"this",
"module",
"is",
"loaded",
"as",
"a",
"server",
"extension",
"."
] | 21fe278cae6fca4e6c92f92d6d786fae8fdea9b1 | https://github.com/googlecolab/jupyter_http_over_ws/blob/21fe278cae6fca4e6c92f92d6d786fae8fdea9b1/jupyter_http_over_ws/__init__.py#L30-L43 | train |
googlecolab/jupyter_http_over_ws | jupyter_http_over_ws/handlers.py | _validate_min_version | def _validate_min_version(min_version):
"""Validates the extension version matches the requested version.
Args:
min_version: Minimum version passed as a query param when establishing the
connection.
Returns:
An ExtensionVersionResult indicating validation status. If there is a
problem, the err... | python | def _validate_min_version(min_version):
"""Validates the extension version matches the requested version.
Args:
min_version: Minimum version passed as a query param when establishing the
connection.
Returns:
An ExtensionVersionResult indicating validation status. If there is a
problem, the err... | [
"def",
"_validate_min_version",
"(",
"min_version",
")",
":",
"if",
"min_version",
"is",
"not",
"None",
":",
"try",
":",
"parsed_min_version",
"=",
"version",
".",
"StrictVersion",
"(",
"min_version",
")",
"except",
"ValueError",
":",
"return",
"ExtensionVersionRe... | Validates the extension version matches the requested version.
Args:
min_version: Minimum version passed as a query param when establishing the
connection.
Returns:
An ExtensionVersionResult indicating validation status. If there is a
problem, the error_reason field will be non-empty. | [
"Validates",
"the",
"extension",
"version",
"matches",
"the",
"requested",
"version",
"."
] | 21fe278cae6fca4e6c92f92d6d786fae8fdea9b1 | https://github.com/googlecolab/jupyter_http_over_ws/blob/21fe278cae6fca4e6c92f92d6d786fae8fdea9b1/jupyter_http_over_ws/handlers.py#L76-L101 | train |
googlecolab/jupyter_http_over_ws | jupyter_http_over_ws/handlers.py | _StreamingResponseEmitter.streaming_callback | def streaming_callback(self, body_part):
"""Handles a streaming chunk of the response.
The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received chunk of the
resp... | python | def streaming_callback(self, body_part):
"""Handles a streaming chunk of the response.
The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received chunk of the
resp... | [
"def",
"streaming_callback",
"(",
"self",
",",
"body_part",
")",
":",
"b64_body_string",
"=",
"base64",
".",
"b64encode",
"(",
"body_part",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"response",
"=",
"{",
"'message_id'",
":",
"self",
".",
"_message_id",
",",
... | Handles a streaming chunk of the response.
The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received chunk of the
response. Each time this is called, the previous chu... | [
"Handles",
"a",
"streaming",
"chunk",
"of",
"the",
"response",
"."
] | 21fe278cae6fca4e6c92f92d6d786fae8fdea9b1 | https://github.com/googlecolab/jupyter_http_over_ws/blob/21fe278cae6fca4e6c92f92d6d786fae8fdea9b1/jupyter_http_over_ws/handlers.py#L261-L288 | train |
kennethreitz/env | env.py | lower_dict | def lower_dict(d):
"""Lower cases string keys in given dict."""
_d = {}
for k, v in d.items():
try:
_d[k.lower()] = v
except AttributeError:
_d[k] = v
return _d | python | def lower_dict(d):
"""Lower cases string keys in given dict."""
_d = {}
for k, v in d.items():
try:
_d[k.lower()] = v
except AttributeError:
_d[k] = v
return _d | [
"def",
"lower_dict",
"(",
"d",
")",
":",
"_d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"try",
":",
"_d",
"[",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"v",
"except",
"AttributeError",
":",
"_d",
"[",
"k",
... | Lower cases string keys in given dict. | [
"Lower",
"cases",
"string",
"keys",
"in",
"given",
"dict",
"."
] | de639fe021c6a42a99f8458ebb90a01c0c4085d7 | https://github.com/kennethreitz/env/blob/de639fe021c6a42a99f8458ebb90a01c0c4085d7/env.py#L10-L21 | train |
kennethreitz/env | env.py | urlparse | def urlparse(d, keys=None):
"""Returns a copy of the given dictionary with url values parsed."""
d = d.copy()
if keys is None:
keys = d.keys()
for key in keys:
d[key] = _urlparse(d[key])
return d | python | def urlparse(d, keys=None):
"""Returns a copy of the given dictionary with url values parsed."""
d = d.copy()
if keys is None:
keys = d.keys()
for key in keys:
d[key] = _urlparse(d[key])
return d | [
"def",
"urlparse",
"(",
"d",
",",
"keys",
"=",
"None",
")",
":",
"d",
"=",
"d",
".",
"copy",
"(",
")",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"d",
".",
"keys",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"d",
"[",
"key",
"]",
"=",
"... | Returns a copy of the given dictionary with url values parsed. | [
"Returns",
"a",
"copy",
"of",
"the",
"given",
"dictionary",
"with",
"url",
"values",
"parsed",
"."
] | de639fe021c6a42a99f8458ebb90a01c0c4085d7 | https://github.com/kennethreitz/env/blob/de639fe021c6a42a99f8458ebb90a01c0c4085d7/env.py#L24-L35 | train |
kennethreitz/env | env.py | prefix | def prefix(prefix):
"""Returns a dictionary of all environment variables starting with
the given prefix, lower cased and stripped.
"""
d = {}
e = lower_dict(environ.copy())
prefix = prefix.lower()
for k, v in e.items():
try:
if k.startswith(prefix):
k =... | python | def prefix(prefix):
"""Returns a dictionary of all environment variables starting with
the given prefix, lower cased and stripped.
"""
d = {}
e = lower_dict(environ.copy())
prefix = prefix.lower()
for k, v in e.items():
try:
if k.startswith(prefix):
k =... | [
"def",
"prefix",
"(",
"prefix",
")",
":",
"d",
"=",
"{",
"}",
"e",
"=",
"lower_dict",
"(",
"environ",
".",
"copy",
"(",
")",
")",
"prefix",
"=",
"prefix",
".",
"lower",
"(",
")",
"for",
"k",
",",
"v",
"in",
"e",
".",
"items",
"(",
")",
":",
... | Returns a dictionary of all environment variables starting with
the given prefix, lower cased and stripped. | [
"Returns",
"a",
"dictionary",
"of",
"all",
"environment",
"variables",
"starting",
"with",
"the",
"given",
"prefix",
"lower",
"cased",
"and",
"stripped",
"."
] | de639fe021c6a42a99f8458ebb90a01c0c4085d7 | https://github.com/kennethreitz/env/blob/de639fe021c6a42a99f8458ebb90a01c0c4085d7/env.py#L38-L56 | train |
kennethreitz/env | env.py | map | def map(**kwargs):
"""Returns a dictionary of the given keyword arguments mapped to their
values from the environment, with input keys lower cased.
"""
d = {}
e = lower_dict(environ.copy())
for k, v in kwargs.items():
d[k] = e.get(v.lower())
return d | python | def map(**kwargs):
"""Returns a dictionary of the given keyword arguments mapped to their
values from the environment, with input keys lower cased.
"""
d = {}
e = lower_dict(environ.copy())
for k, v in kwargs.items():
d[k] = e.get(v.lower())
return d | [
"def",
"map",
"(",
"**",
"kwargs",
")",
":",
"d",
"=",
"{",
"}",
"e",
"=",
"lower_dict",
"(",
"environ",
".",
"copy",
"(",
")",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"d",
"[",
"k",
"]",
"=",
"e",
".",
"ge... | Returns a dictionary of the given keyword arguments mapped to their
values from the environment, with input keys lower cased. | [
"Returns",
"a",
"dictionary",
"of",
"the",
"given",
"keyword",
"arguments",
"mapped",
"to",
"their",
"values",
"from",
"the",
"environment",
"with",
"input",
"keys",
"lower",
"cased",
"."
] | de639fe021c6a42a99f8458ebb90a01c0c4085d7 | https://github.com/kennethreitz/env/blob/de639fe021c6a42a99f8458ebb90a01c0c4085d7/env.py#L59-L70 | train |
masfaraud/BMSpy | bms/core.py | Load | def Load(file):
""" Loads a model from specified file """
with open(file, 'rb') as file:
model = dill.load(file)
return model | python | def Load(file):
""" Loads a model from specified file """
with open(file, 'rb') as file:
model = dill.load(file)
return model | [
"def",
"Load",
"(",
"file",
")",
":",
"with",
"open",
"(",
"file",
",",
"'rb'",
")",
"as",
"file",
":",
"model",
"=",
"dill",
".",
"load",
"(",
"file",
")",
"return",
"model"
] | Loads a model from specified file | [
"Loads",
"a",
"model",
"from",
"specified",
"file"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L555-L559 | train |
masfaraud/BMSpy | bms/core.py | Block._AddInput | def _AddInput(self, variable):
"""
Add one more variable as an input of the block
:param variable: variable (or signal as it is also a variable)
"""
if isinstance(variable, Variable):
self.inputs.append(variable)
else:
print('Error: ', variable.na... | python | def _AddInput(self, variable):
"""
Add one more variable as an input of the block
:param variable: variable (or signal as it is also a variable)
"""
if isinstance(variable, Variable):
self.inputs.append(variable)
else:
print('Error: ', variable.na... | [
"def",
"_AddInput",
"(",
"self",
",",
"variable",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"Variable",
")",
":",
"self",
".",
"inputs",
".",
"append",
"(",
"variable",
")",
"else",
":",
"print",
"(",
"'Error: '",
",",
"variable",
".",
"name"... | Add one more variable as an input of the block
:param variable: variable (or signal as it is also a variable) | [
"Add",
"one",
"more",
"variable",
"as",
"an",
"input",
"of",
"the",
"block"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L118-L129 | train |
masfaraud/BMSpy | bms/core.py | Block._AddOutput | def _AddOutput(self, variable):
"""
Add one more variable as an output of the block
:param variable: variable (or signal as it is also a variable)
"""
if isinstance(variable, Variable):
self.outputs.append(variable)
else:
print(variable)
... | python | def _AddOutput(self, variable):
"""
Add one more variable as an output of the block
:param variable: variable (or signal as it is also a variable)
"""
if isinstance(variable, Variable):
self.outputs.append(variable)
else:
print(variable)
... | [
"def",
"_AddOutput",
"(",
"self",
",",
"variable",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"Variable",
")",
":",
"self",
".",
"outputs",
".",
"append",
"(",
"variable",
")",
"else",
":",
"print",
"(",
"variable",
")",
"raise",
"TypeError"
] | Add one more variable as an output of the block
:param variable: variable (or signal as it is also a variable) | [
"Add",
"one",
"more",
"variable",
"as",
"an",
"output",
"of",
"the",
"block"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L131-L141 | train |
masfaraud/BMSpy | bms/core.py | Block.InputValues | def InputValues(self, it, nsteps=None):
"""
Returns the input values at a given iteration for solving the block outputs
"""
if nsteps == None:
nsteps = self.max_input_order
# print(self,it)
# Provides values in inputs values for computing at iteration it
... | python | def InputValues(self, it, nsteps=None):
"""
Returns the input values at a given iteration for solving the block outputs
"""
if nsteps == None:
nsteps = self.max_input_order
# print(self,it)
# Provides values in inputs values for computing at iteration it
... | [
"def",
"InputValues",
"(",
"self",
",",
"it",
",",
"nsteps",
"=",
"None",
")",
":",
"if",
"nsteps",
"==",
"None",
":",
"nsteps",
"=",
"self",
".",
"max_input_order",
"I",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"n_inputs",
",",
"nsteps",
")... | Returns the input values at a given iteration for solving the block outputs | [
"Returns",
"the",
"input",
"values",
"at",
"a",
"given",
"iteration",
"for",
"solving",
"the",
"block",
"outputs"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L143-L156 | train |
masfaraud/BMSpy | bms/core.py | DynamicSystem._AddVariable | def _AddVariable(self, variable):
"""
Add a variable to the model. Should not be used by end-user
"""
if isinstance(variable, Signal):
if not variable in self.signals:
self.signals.append(variable)
elif isinstance(variable, Variable):
if no... | python | def _AddVariable(self, variable):
"""
Add a variable to the model. Should not be used by end-user
"""
if isinstance(variable, Signal):
if not variable in self.signals:
self.signals.append(variable)
elif isinstance(variable, Variable):
if no... | [
"def",
"_AddVariable",
"(",
"self",
",",
"variable",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"Signal",
")",
":",
"if",
"not",
"variable",
"in",
"self",
".",
"signals",
":",
"self",
".",
"signals",
".",
"append",
"(",
"variable",
")",
"elif"... | Add a variable to the model. Should not be used by end-user | [
"Add",
"a",
"variable",
"to",
"the",
"model",
".",
"Should",
"not",
"be",
"used",
"by",
"end",
"-",
"user"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L222-L234 | train |
masfaraud/BMSpy | bms/core.py | DynamicSystem.VariablesValues | def VariablesValues(self, variables, t):
"""
Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation
"""
# TODO: put interpolatio... | python | def VariablesValues(self, variables, t):
"""
Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation
"""
# TODO: put interpolatio... | [
"def",
"VariablesValues",
"(",
"self",
",",
"variables",
",",
"t",
")",
":",
"if",
"(",
"t",
"<",
"self",
".",
"te",
")",
"|",
"(",
"t",
">",
"0",
")",
":",
"i",
"=",
"t",
"//",
"self",
".",
"ts",
"ti",
"=",
"self",
".",
"ts",
"*",
"i",
"... | Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation | [
"Returns",
"the",
"value",
"of",
"given",
"variables",
"at",
"time",
"t",
".",
"Linear",
"interpolation",
"is",
"performed",
"between",
"two",
"time",
"steps",
"."
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L488-L512 | train |
skorokithakis/django-annoying | annoying/fields.py | JSONField.to_python | def to_python(self, value):
"""
Convert a string from the database to a Python value.
"""
if value == "":
return None
try:
if isinstance(value, six.string_types):
return self.deserializer(value)
elif isinstance(value, bytes):
... | python | def to_python(self, value):
"""
Convert a string from the database to a Python value.
"""
if value == "":
return None
try:
if isinstance(value, six.string_types):
return self.deserializer(value)
elif isinstance(value, bytes):
... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"\"\"",
":",
"return",
"None",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"return",
"self",
".",
"deserializer",
"(",
"value",
... | Convert a string from the database to a Python value. | [
"Convert",
"a",
"string",
"from",
"the",
"database",
"to",
"a",
"Python",
"value",
"."
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/fields.py#L107-L121 | train |
skorokithakis/django-annoying | annoying/fields.py | JSONField.get_prep_value | def get_prep_value(self, value):
"""
Convert the value to a string so it can be stored in the database.
"""
if value == "":
return None
if isinstance(value, (dict, list)):
return self.serializer(value)
return super(JSONField, self).get_prep_value(v... | python | def get_prep_value(self, value):
"""
Convert the value to a string so it can be stored in the database.
"""
if value == "":
return None
if isinstance(value, (dict, list)):
return self.serializer(value)
return super(JSONField, self).get_prep_value(v... | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"\"\"",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"dict",
",",
"list",
")",
")",
":",
"return",
"self",
".",
"serializer",
"(",
"value",
")",
... | Convert the value to a string so it can be stored in the database. | [
"Convert",
"the",
"value",
"to",
"a",
"string",
"so",
"it",
"can",
"be",
"stored",
"in",
"the",
"database",
"."
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/fields.py#L123-L131 | train |
skorokithakis/django-annoying | annoying/decorators.py | render_to | def render_to(template=None, content_type=None):
"""
Decorator for Django views that sends returned dict to render_to_response
function.
Template name can be decorator parameter or TEMPLATE item in returned
dictionary. RequestContext always added as context instance.
If view doesn't return dic... | python | def render_to(template=None, content_type=None):
"""
Decorator for Django views that sends returned dict to render_to_response
function.
Template name can be decorator parameter or TEMPLATE item in returned
dictionary. RequestContext always added as context instance.
If view doesn't return dic... | [
"def",
"render_to",
"(",
"template",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"def",
"renderer",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
"... | Decorator for Django views that sends returned dict to render_to_response
function.
Template name can be decorator parameter or TEMPLATE item in returned
dictionary. RequestContext always added as context instance.
If view doesn't return dict then decorator simply returns output.
Parameters:
... | [
"Decorator",
"for",
"Django",
"views",
"that",
"sends",
"returned",
"dict",
"to",
"render_to_response",
"function",
"."
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/decorators.py#L18-L83 | train |
skorokithakis/django-annoying | annoying/decorators.py | ajax_request | def ajax_request(func):
"""
If view returned serializable dict, returns response in a format requested
by HTTP_ACCEPT header. Defaults to JSON if none requested or match.
Currently supports JSON or YAML (if installed), but can easily be extended.
example:
@ajax_request
def my_view... | python | def ajax_request(func):
"""
If view returned serializable dict, returns response in a format requested
by HTTP_ACCEPT header. Defaults to JSON if none requested or match.
Currently supports JSON or YAML (if installed), but can easily be extended.
example:
@ajax_request
def my_view... | [
"def",
"ajax_request",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"for",
"accepted_type",
"in",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_ACCEPT'",
"... | If view returned serializable dict, returns response in a format requested
by HTTP_ACCEPT header. Defaults to JSON if none requested or match.
Currently supports JSON or YAML (if installed), but can easily be extended.
example:
@ajax_request
def my_view(request):
news = News.o... | [
"If",
"view",
"returned",
"serializable",
"dict",
"returns",
"response",
"in",
"a",
"format",
"requested",
"by",
"HTTP_ACCEPT",
"header",
".",
"Defaults",
"to",
"JSON",
"if",
"none",
"requested",
"or",
"match",
"."
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/decorators.py#L167-L206 | train |
skorokithakis/django-annoying | annoying/decorators.py | autostrip | def autostrip(cls):
"""
strip text fields before validation
example:
@autostrip
class PersonForm(forms.Form):
name = forms.CharField(min_length=2, max_length=10)
email = forms.EmailField()
Author: nail.xx
"""
warnings.warn(
"django-annoying autostrip is deprecat... | python | def autostrip(cls):
"""
strip text fields before validation
example:
@autostrip
class PersonForm(forms.Form):
name = forms.CharField(min_length=2, max_length=10)
email = forms.EmailField()
Author: nail.xx
"""
warnings.warn(
"django-annoying autostrip is deprecat... | [
"def",
"autostrip",
"(",
"cls",
")",
":",
"warnings",
".",
"warn",
"(",
"\"django-annoying autostrip is deprecated and will be removed in a \"",
"\"future version. Django now has native support for stripping form \"",
"\"fields. \"",
"\"https://docs.djangoproject.com/en/stable/ref/forms/fi... | strip text fields before validation
example:
@autostrip
class PersonForm(forms.Form):
name = forms.CharField(min_length=2, max_length=10)
email = forms.EmailField()
Author: nail.xx | [
"strip",
"text",
"fields",
"before",
"validation"
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/decorators.py#L209-L235 | train |
xtacocorex/CHIP_IO | distribute_setup.py | _patch_file | def _patch_file(path, content):
"""Will backup the file then patch it"""
f = open(path)
existing_content = f.read()
f.close()
if existing_content == content:
# already patched
log.warn('Already patched.')
return False
log.warn('Patching...')
_rename_path(path)
f =... | python | def _patch_file(path, content):
"""Will backup the file then patch it"""
f = open(path)
existing_content = f.read()
f.close()
if existing_content == content:
# already patched
log.warn('Already patched.')
return False
log.warn('Patching...')
_rename_path(path)
f =... | [
"def",
"_patch_file",
"(",
"path",
",",
"content",
")",
":",
"f",
"=",
"open",
"(",
"path",
")",
"existing_content",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"if",
"existing_content",
"==",
"content",
":",
"log",
".",
"warn",
"... | Will backup the file then patch it | [
"Will",
"backup",
"the",
"file",
"then",
"patch",
"it"
] | 84df4376f83bb4de2b4e2f77447cb75704ebdaf4 | https://github.com/xtacocorex/CHIP_IO/blob/84df4376f83bb4de2b4e2f77447cb75704ebdaf4/distribute_setup.py#L250-L266 | train |
xtacocorex/CHIP_IO | CHIP_IO/OverlayManager.py | _set_overlay_verify | def _set_overlay_verify(name, overlay_path, config_path):
"""
_set_overlay_verify - Function to load the overlay and verify it was setup properly
"""
global DEBUG
# VERIFY PATH IS NOT THERE
if os.path.exists(config_path):
print("Config path already exists! Not moving forward")
p... | python | def _set_overlay_verify(name, overlay_path, config_path):
"""
_set_overlay_verify - Function to load the overlay and verify it was setup properly
"""
global DEBUG
# VERIFY PATH IS NOT THERE
if os.path.exists(config_path):
print("Config path already exists! Not moving forward")
p... | [
"def",
"_set_overlay_verify",
"(",
"name",
",",
"overlay_path",
",",
"config_path",
")",
":",
"global",
"DEBUG",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
")",
":",
"print",
"(",
"\"Config path already exists! Not moving forward\"",
")",
"print",... | _set_overlay_verify - Function to load the overlay and verify it was setup properly | [
"_set_overlay_verify",
"-",
"Function",
"to",
"load",
"the",
"overlay",
"and",
"verify",
"it",
"was",
"setup",
"properly"
] | 84df4376f83bb4de2b4e2f77447cb75704ebdaf4 | https://github.com/xtacocorex/CHIP_IO/blob/84df4376f83bb4de2b4e2f77447cb75704ebdaf4/CHIP_IO/OverlayManager.py#L87-L130 | train |
xtacocorex/CHIP_IO | CHIP_IO/OverlayManager.py | load | def load(overlay, path=""):
"""
load - Load a DTB Overlay
Inputs:
overlay - Overlay Key: SPI2, PWM0, CUST
path - Full Path to where the custom overlay is stored
Returns:
0 - Successful Load
1 - Unsuccessful Load
2 - Overlay was previously set
"""
global DEBU... | python | def load(overlay, path=""):
"""
load - Load a DTB Overlay
Inputs:
overlay - Overlay Key: SPI2, PWM0, CUST
path - Full Path to where the custom overlay is stored
Returns:
0 - Successful Load
1 - Unsuccessful Load
2 - Overlay was previously set
"""
global DEBU... | [
"def",
"load",
"(",
"overlay",
",",
"path",
"=",
"\"\"",
")",
":",
"global",
"DEBUG",
"global",
"_LOADED",
"if",
"DEBUG",
":",
"print",
"(",
"\"LOAD OVERLAY: {0} @ {1}\"",
".",
"format",
"(",
"overlay",
",",
"path",
")",
")",
"if",
"overlay",
".",
"upper... | load - Load a DTB Overlay
Inputs:
overlay - Overlay Key: SPI2, PWM0, CUST
path - Full Path to where the custom overlay is stored
Returns:
0 - Successful Load
1 - Unsuccessful Load
2 - Overlay was previously set | [
"load",
"-",
"Load",
"a",
"DTB",
"Overlay"
] | 84df4376f83bb4de2b4e2f77447cb75704ebdaf4 | https://github.com/xtacocorex/CHIP_IO/blob/84df4376f83bb4de2b4e2f77447cb75704ebdaf4/CHIP_IO/OverlayManager.py#L132-L195 | train |
thieman/dagobah | dagobah/core/components.py | Scheduler.run | def run(self):
""" Continually monitors Jobs of the parent Dagobah. """
while not self.stopped:
now = datetime.utcnow()
for job in self.parent.jobs:
if not job.next_run:
continue
if job.next_run >= self.last_check and job.next_r... | python | def run(self):
""" Continually monitors Jobs of the parent Dagobah. """
while not self.stopped:
now = datetime.utcnow()
for job in self.parent.jobs:
if not job.next_run:
continue
if job.next_run >= self.last_check and job.next_r... | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"stopped",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"for",
"job",
"in",
"self",
".",
"parent",
".",
"jobs",
":",
"if",
"not",
"job",
".",
"next_run",
":",
"continue",
... | Continually monitors Jobs of the parent Dagobah. | [
"Continually",
"monitors",
"Jobs",
"of",
"the",
"parent",
"Dagobah",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/components.py#L105-L118 | train |
thieman/dagobah | dagobah/core/core.py | Dagobah.set_backend | def set_backend(self, backend):
""" Manually set backend after construction. """
self.backend = backend
self.dagobah_id = self.backend.get_new_dagobah_id()
for job in self.jobs:
job.backend = backend
for task in job.tasks.values():
task.backend =... | python | def set_backend(self, backend):
""" Manually set backend after construction. """
self.backend = backend
self.dagobah_id = self.backend.get_new_dagobah_id()
for job in self.jobs:
job.backend = backend
for task in job.tasks.values():
task.backend =... | [
"def",
"set_backend",
"(",
"self",
",",
"backend",
")",
":",
"self",
".",
"backend",
"=",
"backend",
"self",
".",
"dagobah_id",
"=",
"self",
".",
"backend",
".",
"get_new_dagobah_id",
"(",
")",
"for",
"job",
"in",
"self",
".",
"jobs",
":",
"job",
".",
... | Manually set backend after construction. | [
"Manually",
"set",
"backend",
"after",
"construction",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L56-L67 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.