repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
DreamLab/VmShepherd | src/vmshepherd/http/__init__.py | Panel.get | async def get(self):
"""
Inject all preset data to Panel and Render a Home Page
"""
shepherd = self.request.app.vmshepherd
data = {'presets': {}, 'config': shepherd.config}
presets = await shepherd.preset_manager.list_presets()
runtime = shepherd.runtime_manager
for name in presets:
preset = shepherd.preset_manager.get_preset(name)
data['presets'][name] = {
'preset': preset,
'vms': preset.vms,
'runtime': await runtime.get_preset_data(name),
'vmshepherd_id': shepherd.instance_id,
'now': time.time()
}
return data | python | async def get(self):
"""
Inject all preset data to Panel and Render a Home Page
"""
shepherd = self.request.app.vmshepherd
data = {'presets': {}, 'config': shepherd.config}
presets = await shepherd.preset_manager.list_presets()
runtime = shepherd.runtime_manager
for name in presets:
preset = shepherd.preset_manager.get_preset(name)
data['presets'][name] = {
'preset': preset,
'vms': preset.vms,
'runtime': await runtime.get_preset_data(name),
'vmshepherd_id': shepherd.instance_id,
'now': time.time()
}
return data | [
"async",
"def",
"get",
"(",
"self",
")",
":",
"shepherd",
"=",
"self",
".",
"request",
".",
"app",
".",
"vmshepherd",
"data",
"=",
"{",
"'presets'",
":",
"{",
"}",
",",
"'config'",
":",
"shepherd",
".",
"config",
"}",
"presets",
"=",
"await",
"shephe... | Inject all preset data to Panel and Render a Home Page | [
"Inject",
"all",
"preset",
"data",
"to",
"Panel",
"and",
"Render",
"a",
"Home",
"Page"
] | 709a412c372b897d53808039c5c64a8b69c12c8d | https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/http/__init__.py#L59-L76 | train | 51,500 |
julot/sphinxcontrib-dd | sphinxcontrib/dd/database_diagram.py | serialize | def serialize(dictionary):
"""
Turn dictionary into argument like string.
"""
data = []
for key, value in dictionary.items():
data.append('{0}="{1}"'.format(key, value))
return ', '.join(data) | python | def serialize(dictionary):
"""
Turn dictionary into argument like string.
"""
data = []
for key, value in dictionary.items():
data.append('{0}="{1}"'.format(key, value))
return ', '.join(data) | [
"def",
"serialize",
"(",
"dictionary",
")",
":",
"data",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"data",
".",
"append",
"(",
"'{0}=\"{1}\"'",
".",
"format",
"(",
"key",
",",
"value",
")",
")",
"re... | Turn dictionary into argument like string. | [
"Turn",
"dictionary",
"into",
"argument",
"like",
"string",
"."
] | 18619b356508b9a99cc329eeae53cbf299a5d1de | https://github.com/julot/sphinxcontrib-dd/blob/18619b356508b9a99cc329eeae53cbf299a5d1de/sphinxcontrib/dd/database_diagram.py#L12-L21 | train | 51,501 |
bpannier/simpletr64 | simpletr64/actions/lan.py | Lan.getAmountOfHostsConnected | def getAmountOfHostsConnected(self, lanInterfaceId=1, timeout=1):
"""Execute NewHostNumberOfEntries action to get the amount of known hosts.
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: the amount of known hosts.
:rtype: int
.. seealso:: :meth:`~simpletr64.actions.Lan.getHostDetailsByIndex`
"""
namespace = Lan.getServiceType("getAmountOfHostsConnected") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetHostNumberOfEntries", timeout=timeout)
return int(results["NewHostNumberOfEntries"]) | python | def getAmountOfHostsConnected(self, lanInterfaceId=1, timeout=1):
"""Execute NewHostNumberOfEntries action to get the amount of known hosts.
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: the amount of known hosts.
:rtype: int
.. seealso:: :meth:`~simpletr64.actions.Lan.getHostDetailsByIndex`
"""
namespace = Lan.getServiceType("getAmountOfHostsConnected") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetHostNumberOfEntries", timeout=timeout)
return int(results["NewHostNumberOfEntries"]) | [
"def",
"getAmountOfHostsConnected",
"(",
"self",
",",
"lanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Lan",
".",
"getServiceType",
"(",
"\"getAmountOfHostsConnected\"",
")",
"+",
"str",
"(",
"lanInterfaceId",
")",
"uri",
"=",... | Execute NewHostNumberOfEntries action to get the amount of known hosts.
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: the amount of known hosts.
:rtype: int
.. seealso:: :meth:`~simpletr64.actions.Lan.getHostDetailsByIndex` | [
"Execute",
"NewHostNumberOfEntries",
"action",
"to",
"get",
"the",
"amount",
"of",
"known",
"hosts",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/lan.py#L91-L106 | train | 51,502 |
bpannier/simpletr64 | simpletr64/actions/lan.py | Lan.getHostDetailsByIndex | def getHostDetailsByIndex(self, index, lanInterfaceId=1, timeout=1):
"""Execute GetGenericHostEntry action to get detailed information's of a connected host.
:param index: the index of the host
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: the detailed information's of a connected host.
:rtype: HostDetails
.. seealso:: :meth:`~simpletr64.actions.Lan.getAmountOfHostsConnected`
"""
namespace = Lan.getServiceType("getHostDetailsByIndex") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetGenericHostEntry", timeout=timeout, NewIndex=index)
return HostDetails(results) | python | def getHostDetailsByIndex(self, index, lanInterfaceId=1, timeout=1):
"""Execute GetGenericHostEntry action to get detailed information's of a connected host.
:param index: the index of the host
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: the detailed information's of a connected host.
:rtype: HostDetails
.. seealso:: :meth:`~simpletr64.actions.Lan.getAmountOfHostsConnected`
"""
namespace = Lan.getServiceType("getHostDetailsByIndex") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetGenericHostEntry", timeout=timeout, NewIndex=index)
return HostDetails(results) | [
"def",
"getHostDetailsByIndex",
"(",
"self",
",",
"index",
",",
"lanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Lan",
".",
"getServiceType",
"(",
"\"getHostDetailsByIndex\"",
")",
"+",
"str",
"(",
"lanInterfaceId",
")",
"ur... | Execute GetGenericHostEntry action to get detailed information's of a connected host.
:param index: the index of the host
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: the detailed information's of a connected host.
:rtype: HostDetails
.. seealso:: :meth:`~simpletr64.actions.Lan.getAmountOfHostsConnected` | [
"Execute",
"GetGenericHostEntry",
"action",
"to",
"get",
"detailed",
"information",
"s",
"of",
"a",
"connected",
"host",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/lan.py#L108-L124 | train | 51,503 |
bpannier/simpletr64 | simpletr64/actions/lan.py | Lan.getHostDetailsByMACAddress | def getHostDetailsByMACAddress(self, macAddress, lanInterfaceId=1, timeout=1):
"""Get host details for a host specified by its MAC address.
:param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might
be case sensitive, depending on the router
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: return the host details if found otherwise an Exception will be raised
:rtype: HostDetails
"""
namespace = Lan.getServiceType("getHostDetailsByMACAddress") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetSpecificHostEntry", timeout=timeout, NewMACAddress=macAddress)
return HostDetails(results, macAddress=macAddress) | python | def getHostDetailsByMACAddress(self, macAddress, lanInterfaceId=1, timeout=1):
"""Get host details for a host specified by its MAC address.
:param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might
be case sensitive, depending on the router
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: return the host details if found otherwise an Exception will be raised
:rtype: HostDetails
"""
namespace = Lan.getServiceType("getHostDetailsByMACAddress") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetSpecificHostEntry", timeout=timeout, NewMACAddress=macAddress)
return HostDetails(results, macAddress=macAddress) | [
"def",
"getHostDetailsByMACAddress",
"(",
"self",
",",
"macAddress",
",",
"lanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Lan",
".",
"getServiceType",
"(",
"\"getHostDetailsByMACAddress\"",
")",
"+",
"str",
"(",
"lanInterfaceId... | Get host details for a host specified by its MAC address.
:param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might
be case sensitive, depending on the router
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: return the host details if found otherwise an Exception will be raised
:rtype: HostDetails | [
"Get",
"host",
"details",
"for",
"a",
"host",
"specified",
"by",
"its",
"MAC",
"address",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/lan.py#L126-L141 | train | 51,504 |
bpannier/simpletr64 | simpletr64/actions/lan.py | Lan.getEthernetInfo | def getEthernetInfo(self, lanInterfaceId=1, timeout=1):
"""Execute GetInfo action to get information's about the Ethernet interface.
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: information's about the Ethernet interface.
:rtype: EthernetInfo
"""
namespace = Lan.getServiceType("getEthernetInfo") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return EthernetInfo(results) | python | def getEthernetInfo(self, lanInterfaceId=1, timeout=1):
"""Execute GetInfo action to get information's about the Ethernet interface.
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: information's about the Ethernet interface.
:rtype: EthernetInfo
"""
namespace = Lan.getServiceType("getEthernetInfo") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return EthernetInfo(results) | [
"def",
"getEthernetInfo",
"(",
"self",
",",
"lanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Lan",
".",
"getServiceType",
"(",
"\"getEthernetInfo\"",
")",
"+",
"str",
"(",
"lanInterfaceId",
")",
"uri",
"=",
"self",
".",
... | Execute GetInfo action to get information's about the Ethernet interface.
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: information's about the Ethernet interface.
:rtype: EthernetInfo | [
"Execute",
"GetInfo",
"action",
"to",
"get",
"information",
"s",
"about",
"the",
"Ethernet",
"interface",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/lan.py#L143-L156 | train | 51,505 |
bpannier/simpletr64 | simpletr64/actions/lan.py | Lan.getEthernetStatistic | def getEthernetStatistic(self, lanInterfaceId=1, timeout=1):
"""Execute GetStatistics action to get statistics of the Ethernet interface.
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: statisticss of the Ethernet interface.
:rtype: EthernetStatistic
"""
namespace = Lan.getServiceType("getEthernetStatistic") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetStatistics", timeout=timeout)
return EthernetStatistic(results) | python | def getEthernetStatistic(self, lanInterfaceId=1, timeout=1):
"""Execute GetStatistics action to get statistics of the Ethernet interface.
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: statisticss of the Ethernet interface.
:rtype: EthernetStatistic
"""
namespace = Lan.getServiceType("getEthernetStatistic") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetStatistics", timeout=timeout)
return EthernetStatistic(results) | [
"def",
"getEthernetStatistic",
"(",
"self",
",",
"lanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Lan",
".",
"getServiceType",
"(",
"\"getEthernetStatistic\"",
")",
"+",
"str",
"(",
"lanInterfaceId",
")",
"uri",
"=",
"self",... | Execute GetStatistics action to get statistics of the Ethernet interface.
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: statisticss of the Ethernet interface.
:rtype: EthernetStatistic | [
"Execute",
"GetStatistics",
"action",
"to",
"get",
"statistics",
"of",
"the",
"Ethernet",
"interface",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/lan.py#L158-L171 | train | 51,506 |
bpannier/simpletr64 | simpletr64/actions/lan.py | Lan.setEnable | def setEnable(self, status, lanInterfaceId=1, timeout=1):
"""Set enable status for a LAN interface, be careful you don't cut yourself off.
:param bool status: enable or disable the interface
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
"""
namespace = Lan.getServiceType("setEnable") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
self.execute(uri, namespace, "SetEnable", timeout=timeout, NewEnable=setStatus) | python | def setEnable(self, status, lanInterfaceId=1, timeout=1):
"""Set enable status for a LAN interface, be careful you don't cut yourself off.
:param bool status: enable or disable the interface
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
"""
namespace = Lan.getServiceType("setEnable") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
self.execute(uri, namespace, "SetEnable", timeout=timeout, NewEnable=setStatus) | [
"def",
"setEnable",
"(",
"self",
",",
"status",
",",
"lanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Lan",
".",
"getServiceType",
"(",
"\"setEnable\"",
")",
"+",
"str",
"(",
"lanInterfaceId",
")",
"uri",
"=",
"self",
... | Set enable status for a LAN interface, be careful you don't cut yourself off.
:param bool status: enable or disable the interface
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed | [
"Set",
"enable",
"status",
"for",
"a",
"LAN",
"interface",
"be",
"careful",
"you",
"don",
"t",
"cut",
"yourself",
"off",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/lan.py#L173-L188 | train | 51,507 |
vsoch/helpme | helpme/main/uservoice/__init__.py | Helper.authenticate | def authenticate(self):
'''authenticate with uservoice by creating a client.'''
if not hasattr(self, 'client'):
self.client = uservoice.Client(self.subdomain,
self.api_key,
self.api_secret) | python | def authenticate(self):
'''authenticate with uservoice by creating a client.'''
if not hasattr(self, 'client'):
self.client = uservoice.Client(self.subdomain,
self.api_key,
self.api_secret) | [
"def",
"authenticate",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'client'",
")",
":",
"self",
".",
"client",
"=",
"uservoice",
".",
"Client",
"(",
"self",
".",
"subdomain",
",",
"self",
".",
"api_key",
",",
"self",
".",
"api_s... | authenticate with uservoice by creating a client. | [
"authenticate",
"with",
"uservoice",
"by",
"creating",
"a",
"client",
"."
] | e609172260b10cddadb2d2023ab26da8082a9feb | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/uservoice/__init__.py#L104-L110 | train | 51,508 |
vsoch/helpme | helpme/main/uservoice/__init__.py | Helper.post_ticket | def post_ticket(self, title, body):
'''post_ticket will post a ticket to the uservoice helpdesk
Parameters
==========
title: the title (subject) of the issue
body: the message to send
'''
# Populate the ticket
ticket = {'subject': title,
'message': body }
response = self.client.post("/api/v1/tickets.json", {
'email': self.email,
'ticket': ticket })['ticket']
bot.info(response['url']) | python | def post_ticket(self, title, body):
'''post_ticket will post a ticket to the uservoice helpdesk
Parameters
==========
title: the title (subject) of the issue
body: the message to send
'''
# Populate the ticket
ticket = {'subject': title,
'message': body }
response = self.client.post("/api/v1/tickets.json", {
'email': self.email,
'ticket': ticket })['ticket']
bot.info(response['url']) | [
"def",
"post_ticket",
"(",
"self",
",",
"title",
",",
"body",
")",
":",
"# Populate the ticket",
"ticket",
"=",
"{",
"'subject'",
":",
"title",
",",
"'message'",
":",
"body",
"}",
"response",
"=",
"self",
".",
"client",
".",
"post",
"(",
"\"/api/v1/tickets... | post_ticket will post a ticket to the uservoice helpdesk
Parameters
==========
title: the title (subject) of the issue
body: the message to send | [
"post_ticket",
"will",
"post",
"a",
"ticket",
"to",
"the",
"uservoice",
"helpdesk"
] | e609172260b10cddadb2d2023ab26da8082a9feb | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/uservoice/__init__.py#L114-L131 | train | 51,509 |
mjirik/io3d | io3d/datareader.py | _metadata | def _metadata(image, datapath):
"""Function which returns metadata dict.
:param image: image to get spacing from
:param datapath: path to data
:return: {'series_number': '', 'datadir': '', 'voxelsize_mm': ''}
"""
metadata = {'series_number': 0, 'datadir': datapath}
spacing = image.GetSpacing()
metadata['voxelsize_mm'] = [
spacing[2],
spacing[0],
spacing[1],
]
return metadata | python | def _metadata(image, datapath):
"""Function which returns metadata dict.
:param image: image to get spacing from
:param datapath: path to data
:return: {'series_number': '', 'datadir': '', 'voxelsize_mm': ''}
"""
metadata = {'series_number': 0, 'datadir': datapath}
spacing = image.GetSpacing()
metadata['voxelsize_mm'] = [
spacing[2],
spacing[0],
spacing[1],
]
return metadata | [
"def",
"_metadata",
"(",
"image",
",",
"datapath",
")",
":",
"metadata",
"=",
"{",
"'series_number'",
":",
"0",
",",
"'datadir'",
":",
"datapath",
"}",
"spacing",
"=",
"image",
".",
"GetSpacing",
"(",
")",
"metadata",
"[",
"'voxelsize_mm'",
"]",
"=",
"["... | Function which returns metadata dict.
:param image: image to get spacing from
:param datapath: path to data
:return: {'series_number': '', 'datadir': '', 'voxelsize_mm': ''} | [
"Function",
"which",
"returns",
"metadata",
"dict",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datareader.py#L44-L58 | train | 51,510 |
mjirik/io3d | io3d/datareader.py | DataReader.Get3DData | def Get3DData(self, datapath, qt_app=None, dataplus_format=True, gui=False, start=0, stop=None, step=1,
convert_to_gray=True, series_number=None, use_economic_dtype=True, dicom_expected=None, **kwargs):
"""Returns 3D data and its metadata.
# NOTE(:param qt_app:) If it is set to None (as default) all dialogs for series selection are performed in
terminal. If qt_app is set to QtGui.QApplication() dialogs are in Qt.
:param datapath: directory with input data
:param qt_app: Dialog destination. If None (default) -> terminal, if 'QtGui.QApplication()' -> Qt
:param dataplus_format: New data format. Metadata and data are returned in one structure.
:param gui: True if 'QtGui.QApplication()' instead of terminal should be used
:param int start: used for DicomReader, defines where 3D data reading should start
:param int stop: used for DicomReader, defines where 3D data reading should stop
:param int step: used for DicomReader, defines step for 3D data reading
:param bool convert_to_gray: if True -> RGB is converted to gray
:param int series_number: used in DicomReader, essential in metadata
:param use_economic_dtype: if True, casts 3D data array to less space consuming dtype
:param dicom_expected: set true if it is known that data is in dicom format. Set False to suppress
dicom warnings.
:return: tuple (data3d, metadata)
"""
self.orig_datapath = datapath
datapath = os.path.expanduser(datapath)
if series_number is not None and type(series_number) != int:
series_number = int(series_number)
if not os.path.exists(datapath):
logger.error("Path '" + datapath + "' does not exist")
return
if qt_app is None and gui is True:
from PyQt4.QtGui import QApplication
qt_app = QApplication(sys.argv)
if type(datapath) is not str:
datapath = str(datapath)
datapath = os.path.normpath(datapath)
self.start = start
self.stop = stop
self.step = step
self.convert_to_gray = convert_to_gray
self.series_number = series_number
self.kwargs = kwargs
self.qt_app = qt_app
self.gui = gui
if os.path.isfile(datapath):
logger.debug('file read recognized')
data3d, metadata = self.__ReadFromFile(datapath)
elif os.path.exists(datapath):
logger.debug('directory read recognized')
data3d, metadata = self.__ReadFromDirectory(datapath=datapath, dicom_expected=dicom_expected)
# datapath, start, stop, step, gui=gui, **kwargs)
else:
logger.error('Data path {} not found'.format(datapath))
if convert_to_gray:
if len(data3d.shape) > 3:
# TODO: implement better rgb2gray
data3d = data3d[:, :, :, 0]
if use_economic_dtype:
data3d = self.__use_economic_dtype(data3d)
if dataplus_format:
logger.debug('dataplus format')
# metadata = {'voxelsize_mm': [1, 1, 1]}
datap = metadata
datap['data3d'] = data3d
logger.debug('datap keys () : ' + str(datap.keys()))
return datap
else:
return data3d, metadata | python | def Get3DData(self, datapath, qt_app=None, dataplus_format=True, gui=False, start=0, stop=None, step=1,
convert_to_gray=True, series_number=None, use_economic_dtype=True, dicom_expected=None, **kwargs):
"""Returns 3D data and its metadata.
# NOTE(:param qt_app:) If it is set to None (as default) all dialogs for series selection are performed in
terminal. If qt_app is set to QtGui.QApplication() dialogs are in Qt.
:param datapath: directory with input data
:param qt_app: Dialog destination. If None (default) -> terminal, if 'QtGui.QApplication()' -> Qt
:param dataplus_format: New data format. Metadata and data are returned in one structure.
:param gui: True if 'QtGui.QApplication()' instead of terminal should be used
:param int start: used for DicomReader, defines where 3D data reading should start
:param int stop: used for DicomReader, defines where 3D data reading should stop
:param int step: used for DicomReader, defines step for 3D data reading
:param bool convert_to_gray: if True -> RGB is converted to gray
:param int series_number: used in DicomReader, essential in metadata
:param use_economic_dtype: if True, casts 3D data array to less space consuming dtype
:param dicom_expected: set true if it is known that data is in dicom format. Set False to suppress
dicom warnings.
:return: tuple (data3d, metadata)
"""
self.orig_datapath = datapath
datapath = os.path.expanduser(datapath)
if series_number is not None and type(series_number) != int:
series_number = int(series_number)
if not os.path.exists(datapath):
logger.error("Path '" + datapath + "' does not exist")
return
if qt_app is None and gui is True:
from PyQt4.QtGui import QApplication
qt_app = QApplication(sys.argv)
if type(datapath) is not str:
datapath = str(datapath)
datapath = os.path.normpath(datapath)
self.start = start
self.stop = stop
self.step = step
self.convert_to_gray = convert_to_gray
self.series_number = series_number
self.kwargs = kwargs
self.qt_app = qt_app
self.gui = gui
if os.path.isfile(datapath):
logger.debug('file read recognized')
data3d, metadata = self.__ReadFromFile(datapath)
elif os.path.exists(datapath):
logger.debug('directory read recognized')
data3d, metadata = self.__ReadFromDirectory(datapath=datapath, dicom_expected=dicom_expected)
# datapath, start, stop, step, gui=gui, **kwargs)
else:
logger.error('Data path {} not found'.format(datapath))
if convert_to_gray:
if len(data3d.shape) > 3:
# TODO: implement better rgb2gray
data3d = data3d[:, :, :, 0]
if use_economic_dtype:
data3d = self.__use_economic_dtype(data3d)
if dataplus_format:
logger.debug('dataplus format')
# metadata = {'voxelsize_mm': [1, 1, 1]}
datap = metadata
datap['data3d'] = data3d
logger.debug('datap keys () : ' + str(datap.keys()))
return datap
else:
return data3d, metadata | [
"def",
"Get3DData",
"(",
"self",
",",
"datapath",
",",
"qt_app",
"=",
"None",
",",
"dataplus_format",
"=",
"True",
",",
"gui",
"=",
"False",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
",",
"step",
"=",
"1",
",",
"convert_to_gray",
"=",
"True",... | Returns 3D data and its metadata.
# NOTE(:param qt_app:) If it is set to None (as default) all dialogs for series selection are performed in
terminal. If qt_app is set to QtGui.QApplication() dialogs are in Qt.
:param datapath: directory with input data
:param qt_app: Dialog destination. If None (default) -> terminal, if 'QtGui.QApplication()' -> Qt
:param dataplus_format: New data format. Metadata and data are returned in one structure.
:param gui: True if 'QtGui.QApplication()' instead of terminal should be used
:param int start: used for DicomReader, defines where 3D data reading should start
:param int stop: used for DicomReader, defines where 3D data reading should stop
:param int step: used for DicomReader, defines step for 3D data reading
:param bool convert_to_gray: if True -> RGB is converted to gray
:param int series_number: used in DicomReader, essential in metadata
:param use_economic_dtype: if True, casts 3D data array to less space consuming dtype
:param dicom_expected: set true if it is known that data is in dicom format. Set False to suppress
dicom warnings.
:return: tuple (data3d, metadata) | [
"Returns",
"3D",
"data",
"and",
"its",
"metadata",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datareader.py#L67-L140 | train | 51,511 |
mjirik/io3d | io3d/datareader.py | DataReader.__ReadFromDirectory | def __ReadFromDirectory(self, datapath, dicom_expected=None):
"""This function is actually the ONE, which reads 3D data from file
:param datapath: path to file
:return: tuple (data3d, metadata)
"""
start = self.start
stop = self.stop
step = self.step
kwargs = self.kwargs
gui = self.gui
if (dicom_expected is not False) and (dcmr.is_dicom_dir(datapath)): # reading dicom
logger.debug('Dir - DICOM')
logger.debug("dicom_expected " + str(dicom_expected))
reader = dcmr.DicomReader(datapath,
series_number=self.series_number,
gui=gui,
**kwargs) # qt_app=None, gui=True)
data3d = reader.get_3Ddata(start, stop, step)
metadata = reader.get_metaData()
metadata['series_number'] = reader.series_number
metadata['datadir'] = datapath
self.overlay_fcn = reader.get_overlay
else: # reading image sequence
logger.debug('Dir - Image sequence')
logger.debug('Getting list of readable files...')
flist = []
try:
import SimpleITK as Sitk
except ImportError as e:
logger.error("Unable to import SimpleITK. On Windows try version 1.0.1")
for f in os.listdir(datapath):
try:
Sitk.ReadImage(os.path.join(datapath, f))
except Exception as e:
logger.warning("Cant load file: " + str(f))
logger.warning(e)
continue
flist.append(os.path.join(datapath, f))
flist.sort()
logger.debug('Reading image data...')
image = Sitk.ReadImage(flist)
logger.debug('Getting numpy array from image data...')
data3d = Sitk.GetArrayFromImage(image)
metadata = _metadata(image, datapath)
return data3d, metadata | python | def __ReadFromDirectory(self, datapath, dicom_expected=None):
"""This function is actually the ONE, which reads 3D data from file
:param datapath: path to file
:return: tuple (data3d, metadata)
"""
start = self.start
stop = self.stop
step = self.step
kwargs = self.kwargs
gui = self.gui
if (dicom_expected is not False) and (dcmr.is_dicom_dir(datapath)): # reading dicom
logger.debug('Dir - DICOM')
logger.debug("dicom_expected " + str(dicom_expected))
reader = dcmr.DicomReader(datapath,
series_number=self.series_number,
gui=gui,
**kwargs) # qt_app=None, gui=True)
data3d = reader.get_3Ddata(start, stop, step)
metadata = reader.get_metaData()
metadata['series_number'] = reader.series_number
metadata['datadir'] = datapath
self.overlay_fcn = reader.get_overlay
else: # reading image sequence
logger.debug('Dir - Image sequence')
logger.debug('Getting list of readable files...')
flist = []
try:
import SimpleITK as Sitk
except ImportError as e:
logger.error("Unable to import SimpleITK. On Windows try version 1.0.1")
for f in os.listdir(datapath):
try:
Sitk.ReadImage(os.path.join(datapath, f))
except Exception as e:
logger.warning("Cant load file: " + str(f))
logger.warning(e)
continue
flist.append(os.path.join(datapath, f))
flist.sort()
logger.debug('Reading image data...')
image = Sitk.ReadImage(flist)
logger.debug('Getting numpy array from image data...')
data3d = Sitk.GetArrayFromImage(image)
metadata = _metadata(image, datapath)
return data3d, metadata | [
"def",
"__ReadFromDirectory",
"(",
"self",
",",
"datapath",
",",
"dicom_expected",
"=",
"None",
")",
":",
"start",
"=",
"self",
".",
"start",
"stop",
"=",
"self",
".",
"stop",
"step",
"=",
"self",
".",
"step",
"kwargs",
"=",
"self",
".",
"kwargs",
"gui... | This function is actually the ONE, which reads 3D data from file
:param datapath: path to file
:return: tuple (data3d, metadata) | [
"This",
"function",
"is",
"actually",
"the",
"ONE",
"which",
"reads",
"3D",
"data",
"from",
"file"
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datareader.py#L143-L191 | train | 51,512 |
mjirik/io3d | io3d/datareader.py | DataReader._fix_sitk_bug | def _fix_sitk_bug(path, metadata):
"""There is a bug in simple ITK for Z axis in 3D images. This is a fix.
:param path: path to dicom file to read
:param metadata: metadata to correct
:return: corrected metadata
"""
ds = dicom.read_file(path)
try:
metadata["voxelsize_mm"][0] = ds.SpacingBetweenSlices
except Exception as e:
logger.warning("Read dicom 'SpacingBetweenSlices' failed: ", e)
return metadata | python | def _fix_sitk_bug(path, metadata):
"""There is a bug in simple ITK for Z axis in 3D images. This is a fix.
:param path: path to dicom file to read
:param metadata: metadata to correct
:return: corrected metadata
"""
ds = dicom.read_file(path)
try:
metadata["voxelsize_mm"][0] = ds.SpacingBetweenSlices
except Exception as e:
logger.warning("Read dicom 'SpacingBetweenSlices' failed: ", e)
return metadata | [
"def",
"_fix_sitk_bug",
"(",
"path",
",",
"metadata",
")",
":",
"ds",
"=",
"dicom",
".",
"read_file",
"(",
"path",
")",
"try",
":",
"metadata",
"[",
"\"voxelsize_mm\"",
"]",
"[",
"0",
"]",
"=",
"ds",
".",
"SpacingBetweenSlices",
"except",
"Exception",
"a... | There is a bug in simple ITK for Z axis in 3D images. This is a fix.
:param path: path to dicom file to read
:param metadata: metadata to correct
:return: corrected metadata | [
"There",
"is",
"a",
"bug",
"in",
"simple",
"ITK",
"for",
"Z",
"axis",
"in",
"3D",
"images",
".",
"This",
"is",
"a",
"fix",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datareader.py#L276-L288 | train | 51,513 |
vsoch/helpme | helpme/utils/memory.py | get_pid | def get_pid(pid=None):
'''get_pid will return a pid of interest. First we use given variable,
then environmental variable PID, and then PID of running process
'''
if pid == None:
if os.environ.get("PID",None) != None:
pid = int(os.environ.get("PID"))
# Then use current running script as process
else:
pid = os.getpid()
print("pid is %s" %pid)
return pid | python | def get_pid(pid=None):
'''get_pid will return a pid of interest. First we use given variable,
then environmental variable PID, and then PID of running process
'''
if pid == None:
if os.environ.get("PID",None) != None:
pid = int(os.environ.get("PID"))
# Then use current running script as process
else:
pid = os.getpid()
print("pid is %s" %pid)
return pid | [
"def",
"get_pid",
"(",
"pid",
"=",
"None",
")",
":",
"if",
"pid",
"==",
"None",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"PID\"",
",",
"None",
")",
"!=",
"None",
":",
"pid",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"... | get_pid will return a pid of interest. First we use given variable,
then environmental variable PID, and then PID of running process | [
"get_pid",
"will",
"return",
"a",
"pid",
"of",
"interest",
".",
"First",
"we",
"use",
"given",
"variable",
"then",
"environmental",
"variable",
"PID",
"and",
"then",
"PID",
"of",
"running",
"process"
] | e609172260b10cddadb2d2023ab26da8082a9feb | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/memory.py#L30-L41 | train | 51,514 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper.load_stored_routine | def load_stored_routine(self):
"""
Loads the stored routine into the instance of MySQL.
Returns the metadata of the stored routine if the stored routine is loaded successfully. Otherwise returns
False.
:rtype: dict[str,str]|bool
"""
try:
self._routine_name = os.path.splitext(os.path.basename(self._source_filename))[0]
if os.path.exists(self._source_filename):
if os.path.isfile(self._source_filename):
self._m_time = int(os.path.getmtime(self._source_filename))
else:
raise LoaderException("Unable to get mtime of file '{}'".format(self._source_filename))
else:
raise LoaderException("Source file '{}' does not exist".format(self._source_filename))
if self._pystratum_old_metadata:
self._pystratum_metadata = self._pystratum_old_metadata
load = self._must_reload()
if load:
self.__read_source_file()
self.__get_placeholders()
self._get_designation_type()
self._get_name()
self.__substitute_replace_pairs()
self._load_routine_file()
if self._designation_type == 'bulk_insert':
self._get_bulk_insert_table_columns_info()
self._get_routine_parameters_info()
self.__get_doc_block_parts_wrapper()
self.__save_shadow_copy()
self._update_metadata()
return self._pystratum_metadata
except Exception as exception:
self._log_exception(exception)
return False | python | def load_stored_routine(self):
"""
Loads the stored routine into the instance of MySQL.
Returns the metadata of the stored routine if the stored routine is loaded successfully. Otherwise returns
False.
:rtype: dict[str,str]|bool
"""
try:
self._routine_name = os.path.splitext(os.path.basename(self._source_filename))[0]
if os.path.exists(self._source_filename):
if os.path.isfile(self._source_filename):
self._m_time = int(os.path.getmtime(self._source_filename))
else:
raise LoaderException("Unable to get mtime of file '{}'".format(self._source_filename))
else:
raise LoaderException("Source file '{}' does not exist".format(self._source_filename))
if self._pystratum_old_metadata:
self._pystratum_metadata = self._pystratum_old_metadata
load = self._must_reload()
if load:
self.__read_source_file()
self.__get_placeholders()
self._get_designation_type()
self._get_name()
self.__substitute_replace_pairs()
self._load_routine_file()
if self._designation_type == 'bulk_insert':
self._get_bulk_insert_table_columns_info()
self._get_routine_parameters_info()
self.__get_doc_block_parts_wrapper()
self.__save_shadow_copy()
self._update_metadata()
return self._pystratum_metadata
except Exception as exception:
self._log_exception(exception)
return False | [
"def",
"load_stored_routine",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_routine_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"_source_filename",
")",
")",
"[",
"0",
"]",
"if",
"os"... | Loads the stored routine into the instance of MySQL.
Returns the metadata of the stored routine if the stored routine is loaded successfully. Otherwise returns
False.
:rtype: dict[str,str]|bool | [
"Loads",
"the",
"stored",
"routine",
"into",
"the",
"instance",
"of",
"MySQL",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L190-L242 | train | 51,515 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper.__read_source_file | def __read_source_file(self):
"""
Reads the file with the source of the stored routine.
"""
with open(self._source_filename, 'r', encoding=self._routine_file_encoding) as file:
self._routine_source_code = file.read()
self._routine_source_code_lines = self._routine_source_code.split("\n") | python | def __read_source_file(self):
"""
Reads the file with the source of the stored routine.
"""
with open(self._source_filename, 'r', encoding=self._routine_file_encoding) as file:
self._routine_source_code = file.read()
self._routine_source_code_lines = self._routine_source_code.split("\n") | [
"def",
"__read_source_file",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"_source_filename",
",",
"'r'",
",",
"encoding",
"=",
"self",
".",
"_routine_file_encoding",
")",
"as",
"file",
":",
"self",
".",
"_routine_source_code",
"=",
"file",
".",
... | Reads the file with the source of the stored routine. | [
"Reads",
"the",
"file",
"with",
"the",
"source",
"of",
"the",
"stored",
"routine",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L245-L252 | train | 51,516 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper.__substitute_replace_pairs | def __substitute_replace_pairs(self):
"""
Substitutes all replace pairs in the source of the stored routine.
"""
self._set_magic_constants()
routine_source = []
i = 0
for line in self._routine_source_code_lines:
self._replace['__LINE__'] = "'%d'" % (i + 1)
for search, replace in self._replace.items():
tmp = re.findall(search, line, re.IGNORECASE)
if tmp:
line = line.replace(tmp[0], replace)
routine_source.append(line)
i += 1
self._routine_source_code = "\n".join(routine_source) | python | def __substitute_replace_pairs(self):
"""
Substitutes all replace pairs in the source of the stored routine.
"""
self._set_magic_constants()
routine_source = []
i = 0
for line in self._routine_source_code_lines:
self._replace['__LINE__'] = "'%d'" % (i + 1)
for search, replace in self._replace.items():
tmp = re.findall(search, line, re.IGNORECASE)
if tmp:
line = line.replace(tmp[0], replace)
routine_source.append(line)
i += 1
self._routine_source_code = "\n".join(routine_source) | [
"def",
"__substitute_replace_pairs",
"(",
"self",
")",
":",
"self",
".",
"_set_magic_constants",
"(",
")",
"routine_source",
"=",
"[",
"]",
"i",
"=",
"0",
"for",
"line",
"in",
"self",
".",
"_routine_source_code_lines",
":",
"self",
".",
"_replace",
"[",
"'__... | Substitutes all replace pairs in the source of the stored routine. | [
"Substitutes",
"all",
"replace",
"pairs",
"in",
"the",
"source",
"of",
"the",
"stored",
"routine",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L280-L297 | train | 51,517 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper._log_exception | def _log_exception(self, exception):
"""
Logs an exception.
:param Exception exception: The exception.
:rtype: None
"""
self._io.error(str(exception).strip().split(os.linesep)) | python | def _log_exception(self, exception):
"""
Logs an exception.
:param Exception exception: The exception.
:rtype: None
"""
self._io.error(str(exception).strip().split(os.linesep)) | [
"def",
"_log_exception",
"(",
"self",
",",
"exception",
")",
":",
"self",
".",
"_io",
".",
"error",
"(",
"str",
"(",
"exception",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"os",
".",
"linesep",
")",
")"
] | Logs an exception.
:param Exception exception: The exception.
:rtype: None | [
"Logs",
"an",
"exception",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L300-L308 | train | 51,518 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper.__get_placeholders | def __get_placeholders(self):
"""
Extracts the placeholders from the stored routine source.
"""
ret = True
pattern = re.compile('(@[A-Za-z0-9_.]+(%(max-)?type)?@)')
matches = pattern.findall(self._routine_source_code)
placeholders = []
if len(matches) != 0:
for tmp in matches:
placeholder = tmp[0]
if placeholder.lower() not in self._replace_pairs:
raise LoaderException("Unknown placeholder '{0}' in file {1}".
format(placeholder, self._source_filename))
if placeholder not in placeholders:
placeholders.append(placeholder)
for placeholder in placeholders:
if placeholder not in self._replace:
self._replace[placeholder] = self._replace_pairs[placeholder.lower()]
return ret | python | def __get_placeholders(self):
"""
Extracts the placeholders from the stored routine source.
"""
ret = True
pattern = re.compile('(@[A-Za-z0-9_.]+(%(max-)?type)?@)')
matches = pattern.findall(self._routine_source_code)
placeholders = []
if len(matches) != 0:
for tmp in matches:
placeholder = tmp[0]
if placeholder.lower() not in self._replace_pairs:
raise LoaderException("Unknown placeholder '{0}' in file {1}".
format(placeholder, self._source_filename))
if placeholder not in placeholders:
placeholders.append(placeholder)
for placeholder in placeholders:
if placeholder not in self._replace:
self._replace[placeholder] = self._replace_pairs[placeholder.lower()]
return ret | [
"def",
"__get_placeholders",
"(",
"self",
")",
":",
"ret",
"=",
"True",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'(@[A-Za-z0-9_.]+(%(max-)?type)?@)'",
")",
"matches",
"=",
"pattern",
".",
"findall",
"(",
"self",
".",
"_routine_source_code",
")",
"placeholders... | Extracts the placeholders from the stored routine source. | [
"Extracts",
"the",
"placeholders",
"from",
"the",
"stored",
"routine",
"source",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L321-L345 | train | 51,519 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper._get_designation_type | def _get_designation_type(self):
"""
Extracts the designation type of the stored routine.
"""
positions = self._get_specification_positions()
if positions[0] != -1 and positions[1] != -1:
pattern = re.compile(r'^\s*--\s+type\s*:\s*(\w+)\s*(.+)?\s*', re.IGNORECASE)
for line_number in range(positions[0], positions[1] + 1):
matches = pattern.findall(self._routine_source_code_lines[line_number])
if matches:
self._designation_type = matches[0][0].lower()
tmp = str(matches[0][1])
if self._designation_type == 'bulk_insert':
n = re.compile(r'([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_,]+)', re.IGNORECASE)
info = n.findall(tmp)
if not info:
raise LoaderException('Expected: -- type: bulk_insert <table_name> <columns> in file {0}'.
format(self._source_filename))
self._table_name = info[0][0]
self._columns = str(info[0][1]).split(',')
elif self._designation_type == 'rows_with_key' or self._designation_type == 'rows_with_index':
self._columns = str(matches[0][1]).split(',')
else:
if matches[0][1]:
raise LoaderException('Expected: -- type: {}'.format(self._designation_type))
if not self._designation_type:
raise LoaderException("Unable to find the designation type of the stored routine in file {0}".
format(self._source_filename)) | python | def _get_designation_type(self):
"""
Extracts the designation type of the stored routine.
"""
positions = self._get_specification_positions()
if positions[0] != -1 and positions[1] != -1:
pattern = re.compile(r'^\s*--\s+type\s*:\s*(\w+)\s*(.+)?\s*', re.IGNORECASE)
for line_number in range(positions[0], positions[1] + 1):
matches = pattern.findall(self._routine_source_code_lines[line_number])
if matches:
self._designation_type = matches[0][0].lower()
tmp = str(matches[0][1])
if self._designation_type == 'bulk_insert':
n = re.compile(r'([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_,]+)', re.IGNORECASE)
info = n.findall(tmp)
if not info:
raise LoaderException('Expected: -- type: bulk_insert <table_name> <columns> in file {0}'.
format(self._source_filename))
self._table_name = info[0][0]
self._columns = str(info[0][1]).split(',')
elif self._designation_type == 'rows_with_key' or self._designation_type == 'rows_with_index':
self._columns = str(matches[0][1]).split(',')
else:
if matches[0][1]:
raise LoaderException('Expected: -- type: {}'.format(self._designation_type))
if not self._designation_type:
raise LoaderException("Unable to find the designation type of the stored routine in file {0}".
format(self._source_filename)) | [
"def",
"_get_designation_type",
"(",
"self",
")",
":",
"positions",
"=",
"self",
".",
"_get_specification_positions",
"(",
")",
"if",
"positions",
"[",
"0",
"]",
"!=",
"-",
"1",
"and",
"positions",
"[",
"1",
"]",
"!=",
"-",
"1",
":",
"pattern",
"=",
"r... | Extracts the designation type of the stored routine. | [
"Extracts",
"the",
"designation",
"type",
"of",
"the",
"stored",
"routine",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L348-L377 | train | 51,520 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper._get_specification_positions | def _get_specification_positions(self):
"""
Returns a tuple with the start and end line numbers of the stored routine specification.
:rtype: tuple
"""
start = -1
for (i, line) in enumerate(self._routine_source_code_lines):
if self._is_start_of_stored_routine(line):
start = i
end = -1
for (i, line) in enumerate(self._routine_source_code_lines):
if self._is_start_of_stored_routine_body(line):
end = i - 1
return start, end | python | def _get_specification_positions(self):
"""
Returns a tuple with the start and end line numbers of the stored routine specification.
:rtype: tuple
"""
start = -1
for (i, line) in enumerate(self._routine_source_code_lines):
if self._is_start_of_stored_routine(line):
start = i
end = -1
for (i, line) in enumerate(self._routine_source_code_lines):
if self._is_start_of_stored_routine_body(line):
end = i - 1
return start, end | [
"def",
"_get_specification_positions",
"(",
"self",
")",
":",
"start",
"=",
"-",
"1",
"for",
"(",
"i",
",",
"line",
")",
"in",
"enumerate",
"(",
"self",
".",
"_routine_source_code_lines",
")",
":",
"if",
"self",
".",
"_is_start_of_stored_routine",
"(",
"line... | Returns a tuple with the start and end line numbers of the stored routine specification.
:rtype: tuple | [
"Returns",
"a",
"tuple",
"with",
"the",
"start",
"and",
"end",
"line",
"numbers",
"of",
"the",
"stored",
"routine",
"specification",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L380-L396 | train | 51,521 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper.__get_doc_block_lines | def __get_doc_block_lines(self):
"""
Returns the start and end line of the DOcBlock of the stored routine code.
"""
line1 = None
line2 = None
i = 0
for line in self._routine_source_code_lines:
if re.match(r'\s*/\*\*', line):
line1 = i
if re.match(r'\s*\*/', line):
line2 = i
if self._is_start_of_stored_routine(line):
break
i += 1
return line1, line2 | python | def __get_doc_block_lines(self):
"""
Returns the start and end line of the DOcBlock of the stored routine code.
"""
line1 = None
line2 = None
i = 0
for line in self._routine_source_code_lines:
if re.match(r'\s*/\*\*', line):
line1 = i
if re.match(r'\s*\*/', line):
line2 = i
if self._is_start_of_stored_routine(line):
break
i += 1
return line1, line2 | [
"def",
"__get_doc_block_lines",
"(",
"self",
")",
":",
"line1",
"=",
"None",
"line2",
"=",
"None",
"i",
"=",
"0",
"for",
"line",
"in",
"self",
".",
"_routine_source_code_lines",
":",
"if",
"re",
".",
"match",
"(",
"r'\\s*/\\*\\*'",
",",
"line",
")",
":",... | Returns the start and end line of the DOcBlock of the stored routine code. | [
"Returns",
"the",
"start",
"and",
"end",
"line",
"of",
"the",
"DOcBlock",
"of",
"the",
"stored",
"routine",
"code",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L422-L442 | train | 51,522 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper.__get_doc_block_parts_wrapper | def __get_doc_block_parts_wrapper(self):
"""
Generates the DocBlock parts to be used by the wrapper generator.
"""
self.__get_doc_block_parts_source()
helper = self._get_data_type_helper()
parameters = list()
for parameter_info in self._parameters:
parameters.append(
{'parameter_name': parameter_info['name'],
'python_type': helper.column_type_to_python_type(parameter_info),
'data_type_descriptor': parameter_info['data_type_descriptor'],
'description': self.__get_parameter_doc_description(parameter_info['name'])})
self._doc_block_parts_wrapper['description'] = self._doc_block_parts_source['description']
self._doc_block_parts_wrapper['parameters'] = parameters | python | def __get_doc_block_parts_wrapper(self):
"""
Generates the DocBlock parts to be used by the wrapper generator.
"""
self.__get_doc_block_parts_source()
helper = self._get_data_type_helper()
parameters = list()
for parameter_info in self._parameters:
parameters.append(
{'parameter_name': parameter_info['name'],
'python_type': helper.column_type_to_python_type(parameter_info),
'data_type_descriptor': parameter_info['data_type_descriptor'],
'description': self.__get_parameter_doc_description(parameter_info['name'])})
self._doc_block_parts_wrapper['description'] = self._doc_block_parts_source['description']
self._doc_block_parts_wrapper['parameters'] = parameters | [
"def",
"__get_doc_block_parts_wrapper",
"(",
"self",
")",
":",
"self",
".",
"__get_doc_block_parts_source",
"(",
")",
"helper",
"=",
"self",
".",
"_get_data_type_helper",
"(",
")",
"parameters",
"=",
"list",
"(",
")",
"for",
"parameter_info",
"in",
"self",
".",
... | Generates the DocBlock parts to be used by the wrapper generator. | [
"Generates",
"the",
"DocBlock",
"parts",
"to",
"be",
"used",
"by",
"the",
"wrapper",
"generator",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L493-L510 | train | 51,523 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper._update_metadata | def _update_metadata(self):
"""
Updates the metadata of the stored routine.
"""
self._pystratum_metadata['routine_name'] = self._routine_name
self._pystratum_metadata['designation'] = self._designation_type
self._pystratum_metadata['table_name'] = self._table_name
self._pystratum_metadata['parameters'] = self._parameters
self._pystratum_metadata['columns'] = self._columns
self._pystratum_metadata['fields'] = self._fields
self._pystratum_metadata['column_types'] = self._columns_types
self._pystratum_metadata['timestamp'] = self._m_time
self._pystratum_metadata['replace'] = self._replace
self._pystratum_metadata['pydoc'] = self._doc_block_parts_wrapper | python | def _update_metadata(self):
"""
Updates the metadata of the stored routine.
"""
self._pystratum_metadata['routine_name'] = self._routine_name
self._pystratum_metadata['designation'] = self._designation_type
self._pystratum_metadata['table_name'] = self._table_name
self._pystratum_metadata['parameters'] = self._parameters
self._pystratum_metadata['columns'] = self._columns
self._pystratum_metadata['fields'] = self._fields
self._pystratum_metadata['column_types'] = self._columns_types
self._pystratum_metadata['timestamp'] = self._m_time
self._pystratum_metadata['replace'] = self._replace
self._pystratum_metadata['pydoc'] = self._doc_block_parts_wrapper | [
"def",
"_update_metadata",
"(",
"self",
")",
":",
"self",
".",
"_pystratum_metadata",
"[",
"'routine_name'",
"]",
"=",
"self",
".",
"_routine_name",
"self",
".",
"_pystratum_metadata",
"[",
"'designation'",
"]",
"=",
"self",
".",
"_designation_type",
"self",
"."... | Updates the metadata of the stored routine. | [
"Updates",
"the",
"metadata",
"of",
"the",
"stored",
"routine",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L547-L560 | train | 51,524 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper._set_magic_constants | def _set_magic_constants(self):
"""
Adds magic constants to replace list.
"""
real_path = os.path.realpath(self._source_filename)
self._replace['__FILE__'] = "'%s'" % real_path
self._replace['__ROUTINE__'] = "'%s'" % self._routine_name
self._replace['__DIR__'] = "'%s'" % os.path.dirname(real_path) | python | def _set_magic_constants(self):
"""
Adds magic constants to replace list.
"""
real_path = os.path.realpath(self._source_filename)
self._replace['__FILE__'] = "'%s'" % real_path
self._replace['__ROUTINE__'] = "'%s'" % self._routine_name
self._replace['__DIR__'] = "'%s'" % os.path.dirname(real_path) | [
"def",
"_set_magic_constants",
"(",
"self",
")",
":",
"real_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"self",
".",
"_source_filename",
")",
"self",
".",
"_replace",
"[",
"'__FILE__'",
"]",
"=",
"\"'%s'\"",
"%",
"real_path",
"self",
".",
"_replac... | Adds magic constants to replace list. | [
"Adds",
"magic",
"constants",
"to",
"replace",
"list",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L571-L579 | train | 51,525 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper._unset_magic_constants | def _unset_magic_constants(self):
"""
Removes magic constants from current replace list.
"""
if '__FILE__' in self._replace:
del self._replace['__FILE__']
if '__ROUTINE__' in self._replace:
del self._replace['__ROUTINE__']
if '__DIR__' in self._replace:
del self._replace['__DIR__']
if '__LINE__' in self._replace:
del self._replace['__LINE__'] | python | def _unset_magic_constants(self):
"""
Removes magic constants from current replace list.
"""
if '__FILE__' in self._replace:
del self._replace['__FILE__']
if '__ROUTINE__' in self._replace:
del self._replace['__ROUTINE__']
if '__DIR__' in self._replace:
del self._replace['__DIR__']
if '__LINE__' in self._replace:
del self._replace['__LINE__'] | [
"def",
"_unset_magic_constants",
"(",
"self",
")",
":",
"if",
"'__FILE__'",
"in",
"self",
".",
"_replace",
":",
"del",
"self",
".",
"_replace",
"[",
"'__FILE__'",
"]",
"if",
"'__ROUTINE__'",
"in",
"self",
".",
"_replace",
":",
"del",
"self",
".",
"_replace... | Removes magic constants from current replace list. | [
"Removes",
"magic",
"constants",
"from",
"current",
"replace",
"list",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L582-L596 | train | 51,526 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | RoutineLoaderHelper._print_sql_with_error | def _print_sql_with_error(self, sql, error_line):
"""
Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted.
:param str sql: The SQL statement.
:param int error_line: The line where the error occurs.
"""
if os.linesep in sql:
lines = sql.split(os.linesep)
digits = math.ceil(math.log(len(lines) + 1, 10))
i = 1
for line in lines:
if i == error_line:
self._io.text('<error>{0:{width}} {1}</error>'.format(i, line, width=digits, ))
else:
self._io.text('{0:{width}} {1}'.format(i, line, width=digits, ))
i += 1
else:
self._io.text(sql) | python | def _print_sql_with_error(self, sql, error_line):
"""
Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted.
:param str sql: The SQL statement.
:param int error_line: The line where the error occurs.
"""
if os.linesep in sql:
lines = sql.split(os.linesep)
digits = math.ceil(math.log(len(lines) + 1, 10))
i = 1
for line in lines:
if i == error_line:
self._io.text('<error>{0:{width}} {1}</error>'.format(i, line, width=digits, ))
else:
self._io.text('{0:{width}} {1}'.format(i, line, width=digits, ))
i += 1
else:
self._io.text(sql) | [
"def",
"_print_sql_with_error",
"(",
"self",
",",
"sql",
",",
"error_line",
")",
":",
"if",
"os",
".",
"linesep",
"in",
"sql",
":",
"lines",
"=",
"sql",
".",
"split",
"(",
"os",
".",
"linesep",
")",
"digits",
"=",
"math",
".",
"ceil",
"(",
"math",
... | Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted.
:param str sql: The SQL statement.
:param int error_line: The line where the error occurs. | [
"Writes",
"a",
"SQL",
"statement",
"with",
"an",
"syntax",
"error",
"to",
"the",
"output",
".",
"The",
"line",
"where",
"the",
"error",
"occurs",
"is",
"highlighted",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L599-L617 | train | 51,527 |
mjirik/io3d | io3d/dili.py | list_filter | def list_filter(lst, startswith=None, notstartswith=None,
contain=None, notcontain=None):
""" Keep in list items according to filter parameters.
:param lst: item list
:param startswith: keep items starting with
:param notstartswith: remove items starting with
:return:
"""
keeped = []
for item in lst:
keep = False
if startswith is not None:
if item.startswith(startswith):
keep = True
if notstartswith is not None:
if not item.startswith(notstartswith):
keep = True
if contain is not None:
if contain in item:
keep = True
if notcontain is not None:
if not notcontain in item:
keep = True
if keep:
keeped.append(item)
return keeped | python | def list_filter(lst, startswith=None, notstartswith=None,
contain=None, notcontain=None):
""" Keep in list items according to filter parameters.
:param lst: item list
:param startswith: keep items starting with
:param notstartswith: remove items starting with
:return:
"""
keeped = []
for item in lst:
keep = False
if startswith is not None:
if item.startswith(startswith):
keep = True
if notstartswith is not None:
if not item.startswith(notstartswith):
keep = True
if contain is not None:
if contain in item:
keep = True
if notcontain is not None:
if not notcontain in item:
keep = True
if keep:
keeped.append(item)
return keeped | [
"def",
"list_filter",
"(",
"lst",
",",
"startswith",
"=",
"None",
",",
"notstartswith",
"=",
"None",
",",
"contain",
"=",
"None",
",",
"notcontain",
"=",
"None",
")",
":",
"keeped",
"=",
"[",
"]",
"for",
"item",
"in",
"lst",
":",
"keep",
"=",
"False"... | Keep in list items according to filter parameters.
:param lst: item list
:param startswith: keep items starting with
:param notstartswith: remove items starting with
:return: | [
"Keep",
"in",
"list",
"items",
"according",
"to",
"filter",
"parameters",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L41-L68 | train | 51,528 |
mjirik/io3d | io3d/dili.py | split_dict | def split_dict(dct, keys):
"""
Split dict into two subdicts based on keys.
:param dct:
:param keys:
:return: dict_in, dict_out
"""
if type(dct) == collections.OrderedDict:
dict_in = collections.OrderedDict()
dict_out = collections.OrderedDict()
else:
dict_in = {}
dict_out = {}
for key, value in dct.items:
if key in keys:
dict_in[key] = value
else:
dict_out[key] = value
return dict_in, dict_out | python | def split_dict(dct, keys):
"""
Split dict into two subdicts based on keys.
:param dct:
:param keys:
:return: dict_in, dict_out
"""
if type(dct) == collections.OrderedDict:
dict_in = collections.OrderedDict()
dict_out = collections.OrderedDict()
else:
dict_in = {}
dict_out = {}
for key, value in dct.items:
if key in keys:
dict_in[key] = value
else:
dict_out[key] = value
return dict_in, dict_out | [
"def",
"split_dict",
"(",
"dct",
",",
"keys",
")",
":",
"if",
"type",
"(",
"dct",
")",
"==",
"collections",
".",
"OrderedDict",
":",
"dict_in",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"dict_out",
"=",
"collections",
".",
"OrderedDict",
"(",
")"... | Split dict into two subdicts based on keys.
:param dct:
:param keys:
:return: dict_in, dict_out | [
"Split",
"dict",
"into",
"two",
"subdicts",
"based",
"on",
"keys",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L82-L102 | train | 51,529 |
mjirik/io3d | io3d/dili.py | recursive_update | def recursive_update(d, u):
"""
Dict recursive update.
Based on Alex Martelli code on stackoverflow
http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth?answertab=votes#tab-top
:param d: dict to update
:param u: dict with new data
:return:
"""
for k, v in u.iteritems():
if isinstance(v, collections.Mapping):
r = recursive_update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d | python | def recursive_update(d, u):
"""
Dict recursive update.
Based on Alex Martelli code on stackoverflow
http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth?answertab=votes#tab-top
:param d: dict to update
:param u: dict with new data
:return:
"""
for k, v in u.iteritems():
if isinstance(v, collections.Mapping):
r = recursive_update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d | [
"def",
"recursive_update",
"(",
"d",
",",
"u",
")",
":",
"for",
"k",
",",
"v",
"in",
"u",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"collections",
".",
"Mapping",
")",
":",
"r",
"=",
"recursive_update",
"(",
"d",
".",
"g... | Dict recursive update.
Based on Alex Martelli code on stackoverflow
http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth?answertab=votes#tab-top
:param d: dict to update
:param u: dict with new data
:return: | [
"Dict",
"recursive",
"update",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L104-L121 | train | 51,530 |
mjirik/io3d | io3d/dili.py | flatten_dict_join_keys | def flatten_dict_join_keys(dct, join_symbol=" "):
""" Flatten dict with defined key join symbol.
:param dct: dict to flatten
:param join_symbol: default value is " "
:return:
"""
return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) ) | python | def flatten_dict_join_keys(dct, join_symbol=" "):
""" Flatten dict with defined key join symbol.
:param dct: dict to flatten
:param join_symbol: default value is " "
:return:
"""
return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) ) | [
"def",
"flatten_dict_join_keys",
"(",
"dct",
",",
"join_symbol",
"=",
"\" \"",
")",
":",
"return",
"dict",
"(",
"flatten_dict",
"(",
"dct",
",",
"join",
"=",
"lambda",
"a",
",",
"b",
":",
"a",
"+",
"join_symbol",
"+",
"b",
")",
")"
] | Flatten dict with defined key join symbol.
:param dct: dict to flatten
:param join_symbol: default value is " "
:return: | [
"Flatten",
"dict",
"with",
"defined",
"key",
"join",
"symbol",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L128-L135 | train | 51,531 |
mjirik/io3d | io3d/dili.py | list_contains | def list_contains(list_of_strings, substring, return_true_false_array=False):
""" Get strings in list which contains substring.
"""
key_tf = [keyi.find(substring) != -1 for keyi in list_of_strings]
if return_true_false_array:
return key_tf
keys_to_remove = list_of_strings[key_tf]
return keys_to_remove | python | def list_contains(list_of_strings, substring, return_true_false_array=False):
""" Get strings in list which contains substring.
"""
key_tf = [keyi.find(substring) != -1 for keyi in list_of_strings]
if return_true_false_array:
return key_tf
keys_to_remove = list_of_strings[key_tf]
return keys_to_remove | [
"def",
"list_contains",
"(",
"list_of_strings",
",",
"substring",
",",
"return_true_false_array",
"=",
"False",
")",
":",
"key_tf",
"=",
"[",
"keyi",
".",
"find",
"(",
"substring",
")",
"!=",
"-",
"1",
"for",
"keyi",
"in",
"list_of_strings",
"]",
"if",
"re... | Get strings in list which contains substring. | [
"Get",
"strings",
"in",
"list",
"which",
"contains",
"substring",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L176-L184 | train | 51,532 |
mjirik/io3d | io3d/dili.py | df_drop_duplicates | def df_drop_duplicates(df, ignore_key_pattern="time"):
"""
Drop duplicates from dataframe ignore columns with keys containing defined pattern.
:param df:
:param noinfo_key_pattern:
:return:
"""
keys_to_remove = list_contains(df.keys(), ignore_key_pattern)
#key_tf = [key.find(noinfo_key_pattern) != -1 for key in df.keys()]
# keys_to_remove
# remove duplicates
ks = copy.copy(list(df.keys()))
for key in keys_to_remove:
ks.remove(key)
df = df.drop_duplicates(ks)
return df | python | def df_drop_duplicates(df, ignore_key_pattern="time"):
"""
Drop duplicates from dataframe ignore columns with keys containing defined pattern.
:param df:
:param noinfo_key_pattern:
:return:
"""
keys_to_remove = list_contains(df.keys(), ignore_key_pattern)
#key_tf = [key.find(noinfo_key_pattern) != -1 for key in df.keys()]
# keys_to_remove
# remove duplicates
ks = copy.copy(list(df.keys()))
for key in keys_to_remove:
ks.remove(key)
df = df.drop_duplicates(ks)
return df | [
"def",
"df_drop_duplicates",
"(",
"df",
",",
"ignore_key_pattern",
"=",
"\"time\"",
")",
":",
"keys_to_remove",
"=",
"list_contains",
"(",
"df",
".",
"keys",
"(",
")",
",",
"ignore_key_pattern",
")",
"#key_tf = [key.find(noinfo_key_pattern) != -1 for key in df.keys()]",
... | Drop duplicates from dataframe ignore columns with keys containing defined pattern.
:param df:
:param noinfo_key_pattern:
:return: | [
"Drop",
"duplicates",
"from",
"dataframe",
"ignore",
"columns",
"with",
"keys",
"containing",
"defined",
"pattern",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L187-L205 | train | 51,533 |
mjirik/io3d | io3d/dili.py | ndarray_to_list_in_structure | def ndarray_to_list_in_structure(item, squeeze=True):
""" Change ndarray in structure of lists and dicts into lists.
"""
tp = type(item)
if tp == np.ndarray:
if squeeze:
item = item.squeeze()
item = item.tolist()
elif tp == list:
for i in range(len(item)):
item[i] = ndarray_to_list_in_structure(item[i])
elif tp == dict:
for lab in item:
item[lab] = ndarray_to_list_in_structure(item[lab])
return item | python | def ndarray_to_list_in_structure(item, squeeze=True):
""" Change ndarray in structure of lists and dicts into lists.
"""
tp = type(item)
if tp == np.ndarray:
if squeeze:
item = item.squeeze()
item = item.tolist()
elif tp == list:
for i in range(len(item)):
item[i] = ndarray_to_list_in_structure(item[i])
elif tp == dict:
for lab in item:
item[lab] = ndarray_to_list_in_structure(item[lab])
return item | [
"def",
"ndarray_to_list_in_structure",
"(",
"item",
",",
"squeeze",
"=",
"True",
")",
":",
"tp",
"=",
"type",
"(",
"item",
")",
"if",
"tp",
"==",
"np",
".",
"ndarray",
":",
"if",
"squeeze",
":",
"item",
"=",
"item",
".",
"squeeze",
"(",
")",
"item",
... | Change ndarray in structure of lists and dicts into lists. | [
"Change",
"ndarray",
"in",
"structure",
"of",
"lists",
"and",
"dicts",
"into",
"lists",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L208-L224 | train | 51,534 |
mjirik/io3d | io3d/dili.py | dict_find_key | def dict_find_key(dd, value):
""" Find first suitable key in dict.
:param dd:
:param value:
:return:
"""
key = next(key for key, val in dd.items() if val == value)
return key | python | def dict_find_key(dd, value):
""" Find first suitable key in dict.
:param dd:
:param value:
:return:
"""
key = next(key for key, val in dd.items() if val == value)
return key | [
"def",
"dict_find_key",
"(",
"dd",
",",
"value",
")",
":",
"key",
"=",
"next",
"(",
"key",
"for",
"key",
",",
"val",
"in",
"dd",
".",
"items",
"(",
")",
"if",
"val",
"==",
"value",
")",
"return",
"key"
] | Find first suitable key in dict.
:param dd:
:param value:
:return: | [
"Find",
"first",
"suitable",
"key",
"in",
"dict",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L227-L235 | train | 51,535 |
mjirik/io3d | io3d/dili.py | sort_list_of_dicts | def sort_list_of_dicts(lst_of_dct, keys, reverse=False, **sort_args):
"""
Sort list of dicts by one or multiple keys.
If the key is not available, sort these to the end.
:param lst_of_dct: input structure. List of dicts.
:param keys: one or more keys in list
:param reverse:
:param sort_args:
:return:
"""
if type(keys) != list:
keys = [keys]
# dcmdir = lst_of_dct[:]
# lst_of_dct.sort(key=lambda x: [x[key] for key in keys], reverse=reverse, **sort_args)
lst_of_dct.sort(key=lambda x: [((False, x[key]) if key in x else (True, 0)) for key in keys], reverse=reverse, **sort_args)
return lst_of_dct | python | def sort_list_of_dicts(lst_of_dct, keys, reverse=False, **sort_args):
"""
Sort list of dicts by one or multiple keys.
If the key is not available, sort these to the end.
:param lst_of_dct: input structure. List of dicts.
:param keys: one or more keys in list
:param reverse:
:param sort_args:
:return:
"""
if type(keys) != list:
keys = [keys]
# dcmdir = lst_of_dct[:]
# lst_of_dct.sort(key=lambda x: [x[key] for key in keys], reverse=reverse, **sort_args)
lst_of_dct.sort(key=lambda x: [((False, x[key]) if key in x else (True, 0)) for key in keys], reverse=reverse, **sort_args)
return lst_of_dct | [
"def",
"sort_list_of_dicts",
"(",
"lst_of_dct",
",",
"keys",
",",
"reverse",
"=",
"False",
",",
"*",
"*",
"sort_args",
")",
":",
"if",
"type",
"(",
"keys",
")",
"!=",
"list",
":",
"keys",
"=",
"[",
"keys",
"]",
"# dcmdir = lst_of_dct[:]",
"# lst_of_dct.sor... | Sort list of dicts by one or multiple keys.
If the key is not available, sort these to the end.
:param lst_of_dct: input structure. List of dicts.
:param keys: one or more keys in list
:param reverse:
:param sort_args:
:return: | [
"Sort",
"list",
"of",
"dicts",
"by",
"one",
"or",
"multiple",
"keys",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L238-L256 | train | 51,536 |
mjirik/io3d | io3d/dili.py | ordered_dict_to_dict | def ordered_dict_to_dict(config):
"""
Use dict instead of ordered dict in structure.
"""
if type(config) == collections.OrderedDict:
config = dict(config)
if type(config) == list:
for i in range(0, len(config)):
config[i] = ordered_dict_to_dict(config[i])
elif type(config) == dict:
for key in config:
config[key] = ordered_dict_to_dict(config[key])
return config | python | def ordered_dict_to_dict(config):
"""
Use dict instead of ordered dict in structure.
"""
if type(config) == collections.OrderedDict:
config = dict(config)
if type(config) == list:
for i in range(0, len(config)):
config[i] = ordered_dict_to_dict(config[i])
elif type(config) == dict:
for key in config:
config[key] = ordered_dict_to_dict(config[key])
return config | [
"def",
"ordered_dict_to_dict",
"(",
"config",
")",
":",
"if",
"type",
"(",
"config",
")",
"==",
"collections",
".",
"OrderedDict",
":",
"config",
"=",
"dict",
"(",
"config",
")",
"if",
"type",
"(",
"config",
")",
"==",
"list",
":",
"for",
"i",
"in",
... | Use dict instead of ordered dict in structure. | [
"Use",
"dict",
"instead",
"of",
"ordered",
"dict",
"in",
"structure",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L258-L272 | train | 51,537 |
SetBased/py-stratum | pystratum/Connection.py | Connection._get_option | def _get_option(config, supplement, section, option, fallback=None):
"""
Reads an option for a configuration file.
:param configparser.ConfigParser config: The main config file.
:param configparser.ConfigParser supplement: The supplement config file.
:param str section: The name of the section op the option.
:param str option: The name of the option.
:param str|None fallback: The fallback value of the option if it is not set in either configuration files.
:rtype: str
:raise KeyError:
"""
if supplement:
return_value = supplement.get(section, option, fallback=config.get(section, option, fallback=fallback))
else:
return_value = config.get(section, option, fallback=fallback)
if fallback is None and return_value is None:
raise KeyError("Option '{0!s}' is not found in section '{1!s}'.".format(option, section))
return return_value | python | def _get_option(config, supplement, section, option, fallback=None):
"""
Reads an option for a configuration file.
:param configparser.ConfigParser config: The main config file.
:param configparser.ConfigParser supplement: The supplement config file.
:param str section: The name of the section op the option.
:param str option: The name of the option.
:param str|None fallback: The fallback value of the option if it is not set in either configuration files.
:rtype: str
:raise KeyError:
"""
if supplement:
return_value = supplement.get(section, option, fallback=config.get(section, option, fallback=fallback))
else:
return_value = config.get(section, option, fallback=fallback)
if fallback is None and return_value is None:
raise KeyError("Option '{0!s}' is not found in section '{1!s}'.".format(option, section))
return return_value | [
"def",
"_get_option",
"(",
"config",
",",
"supplement",
",",
"section",
",",
"option",
",",
"fallback",
"=",
"None",
")",
":",
"if",
"supplement",
":",
"return_value",
"=",
"supplement",
".",
"get",
"(",
"section",
",",
"option",
",",
"fallback",
"=",
"c... | Reads an option for a configuration file.
:param configparser.ConfigParser config: The main config file.
:param configparser.ConfigParser supplement: The supplement config file.
:param str section: The name of the section op the option.
:param str option: The name of the option.
:param str|None fallback: The fallback value of the option if it is not set in either configuration files.
:rtype: str
:raise KeyError: | [
"Reads",
"an",
"option",
"for",
"a",
"configuration",
"file",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/Connection.py#L28-L50 | train | 51,538 |
SetBased/py-stratum | pystratum/Connection.py | Connection._read_configuration | def _read_configuration(config_filename):
"""
Checks the supplement file.
:param str config_filename: The name of the configuration file.
:rtype: (configparser.ConfigParser,configparser.ConfigParser)
"""
config = ConfigParser()
config.read(config_filename)
if 'supplement' in config['database']:
path = os.path.dirname(config_filename) + '/' + config.get('database', 'supplement')
config_supplement = ConfigParser()
config_supplement.read(path)
else:
config_supplement = None
return config, config_supplement | python | def _read_configuration(config_filename):
"""
Checks the supplement file.
:param str config_filename: The name of the configuration file.
:rtype: (configparser.ConfigParser,configparser.ConfigParser)
"""
config = ConfigParser()
config.read(config_filename)
if 'supplement' in config['database']:
path = os.path.dirname(config_filename) + '/' + config.get('database', 'supplement')
config_supplement = ConfigParser()
config_supplement.read(path)
else:
config_supplement = None
return config, config_supplement | [
"def",
"_read_configuration",
"(",
"config_filename",
")",
":",
"config",
"=",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"config_filename",
")",
"if",
"'supplement'",
"in",
"config",
"[",
"'database'",
"]",
":",
"path",
"=",
"os",
".",
"path",
... | Checks the supplement file.
:param str config_filename: The name of the configuration file.
:rtype: (configparser.ConfigParser,configparser.ConfigParser) | [
"Checks",
"the",
"supplement",
"file",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/Connection.py#L54-L72 | train | 51,539 |
vsoch/helpme | helpme/action/record.py | record_asciinema | def record_asciinema():
'''a wrapper around generation of an asciinema.api.Api and a custom
recorder to pull out the input arguments to the Record from argparse.
The function generates a filename in advance and a return code
so we can check the final status.
'''
import asciinema.config as aconfig
from asciinema.api import Api
# Load the API class
cfg = aconfig.load()
api = Api(cfg.api_url, os.environ.get("USER"), cfg.install_id)
# Create dummy class to pass in as args
recorder = HelpMeRecord(api)
code = recorder.execute()
if code == 0 and os.path.exists(recorder.filename):
return recorder.filename
print('Problem generating %s, return code %s' %(recorder.filename, code)) | python | def record_asciinema():
'''a wrapper around generation of an asciinema.api.Api and a custom
recorder to pull out the input arguments to the Record from argparse.
The function generates a filename in advance and a return code
so we can check the final status.
'''
import asciinema.config as aconfig
from asciinema.api import Api
# Load the API class
cfg = aconfig.load()
api = Api(cfg.api_url, os.environ.get("USER"), cfg.install_id)
# Create dummy class to pass in as args
recorder = HelpMeRecord(api)
code = recorder.execute()
if code == 0 and os.path.exists(recorder.filename):
return recorder.filename
print('Problem generating %s, return code %s' %(recorder.filename, code)) | [
"def",
"record_asciinema",
"(",
")",
":",
"import",
"asciinema",
".",
"config",
"as",
"aconfig",
"from",
"asciinema",
".",
"api",
"import",
"Api",
"# Load the API class",
"cfg",
"=",
"aconfig",
".",
"load",
"(",
")",
"api",
"=",
"Api",
"(",
"cfg",
".",
"... | a wrapper around generation of an asciinema.api.Api and a custom
recorder to pull out the input arguments to the Record from argparse.
The function generates a filename in advance and a return code
so we can check the final status. | [
"a",
"wrapper",
"around",
"generation",
"of",
"an",
"asciinema",
".",
"api",
".",
"Api",
"and",
"a",
"custom",
"recorder",
"to",
"pull",
"out",
"the",
"input",
"arguments",
"to",
"the",
"Record",
"from",
"argparse",
".",
"The",
"function",
"generates",
"a"... | e609172260b10cddadb2d2023ab26da8082a9feb | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/action/record.py#L80-L101 | train | 51,540 |
bpannier/simpletr64 | simpletr64/actions/fritz.py | Fritz.sendWakeOnLan | def sendWakeOnLan(self, macAddress, lanInterfaceId=1, timeout=1):
"""Send a wake up package to a device specified by its MAC address.
:param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might
be case sensitive, depending on the router
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: the amount of known hosts.
:rtype: int
.. seealso:: :meth:`~simpletr64.actions.Lan.getHostDetailsByMACAddress`
"""
namespace = Fritz.getServiceType("sendWakeOnLan") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "X_AVM-DE_WakeOnLANByMACAddress", timeout=timeout,
NewMACAddress=macAddress) | python | def sendWakeOnLan(self, macAddress, lanInterfaceId=1, timeout=1):
"""Send a wake up package to a device specified by its MAC address.
:param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might
be case sensitive, depending on the router
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: the amount of known hosts.
:rtype: int
.. seealso:: :meth:`~simpletr64.actions.Lan.getHostDetailsByMACAddress`
"""
namespace = Fritz.getServiceType("sendWakeOnLan") + str(lanInterfaceId)
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "X_AVM-DE_WakeOnLANByMACAddress", timeout=timeout,
NewMACAddress=macAddress) | [
"def",
"sendWakeOnLan",
"(",
"self",
",",
"macAddress",
",",
"lanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Fritz",
".",
"getServiceType",
"(",
"\"sendWakeOnLan\"",
")",
"+",
"str",
"(",
"lanInterfaceId",
")",
"uri",
"="... | Send a wake up package to a device specified by its MAC address.
:param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might
be case sensitive, depending on the router
:param int lanInterfaceId: the id of the LAN interface
:param float timeout: the timeout to wait for the action to be executed
:return: the amount of known hosts.
:rtype: int
.. seealso:: :meth:`~simpletr64.actions.Lan.getHostDetailsByMACAddress` | [
"Send",
"a",
"wake",
"up",
"package",
"to",
"a",
"device",
"specified",
"by",
"its",
"MAC",
"address",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L91-L107 | train | 51,541 |
bpannier/simpletr64 | simpletr64/actions/fritz.py | Fritz.doUpdate | def doUpdate(self, timeout=1):
"""Do a software update of the Fritz Box if available.
:param float timeout: the timeout to wait for the action to be executed
:return: a list of if an update was available and the update state (bool, str)
:rtype: tuple(bool, str)
"""
namespace = Fritz.getServiceType("doUpdate")
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "X_AVM-DE_DoUpdate", timeout=timeout)
return results["NewUpgradeAvailable"], results["NewX_AVM-DE_UpdateState"] | python | def doUpdate(self, timeout=1):
"""Do a software update of the Fritz Box if available.
:param float timeout: the timeout to wait for the action to be executed
:return: a list of if an update was available and the update state (bool, str)
:rtype: tuple(bool, str)
"""
namespace = Fritz.getServiceType("doUpdate")
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "X_AVM-DE_DoUpdate", timeout=timeout)
return results["NewUpgradeAvailable"], results["NewX_AVM-DE_UpdateState"] | [
"def",
"doUpdate",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Fritz",
".",
"getServiceType",
"(",
"\"doUpdate\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
"(",
... | Do a software update of the Fritz Box if available.
:param float timeout: the timeout to wait for the action to be executed
:return: a list of if an update was available and the update state (bool, str)
:rtype: tuple(bool, str) | [
"Do",
"a",
"software",
"update",
"of",
"the",
"Fritz",
"Box",
"if",
"available",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L109-L121 | train | 51,542 |
bpannier/simpletr64 | simpletr64/actions/fritz.py | Fritz.isOptimizedForIPTV | def isOptimizedForIPTV(self, wifiInterfaceId=1, timeout=1):
"""Return if the Wifi interface is optimized for IP TV
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
:return: if the Wifi interface is optimized for IP TV
:rtype: bool
.. seealso:: :meth:`~simpletr64.actions.Fritz.setOptimizedForIPTV`
"""
namespace = Fritz.getServiceType("isOptimizedForIPTV") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "X_AVM-DE_GetIPTVOptimized", timeout=timeout)
return bool(int(results["NewX_AVM-DE_IPTVoptimize"])) | python | def isOptimizedForIPTV(self, wifiInterfaceId=1, timeout=1):
"""Return if the Wifi interface is optimized for IP TV
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
:return: if the Wifi interface is optimized for IP TV
:rtype: bool
.. seealso:: :meth:`~simpletr64.actions.Fritz.setOptimizedForIPTV`
"""
namespace = Fritz.getServiceType("isOptimizedForIPTV") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "X_AVM-DE_GetIPTVOptimized", timeout=timeout)
return bool(int(results["NewX_AVM-DE_IPTVoptimize"])) | [
"def",
"isOptimizedForIPTV",
"(",
"self",
",",
"wifiInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Fritz",
".",
"getServiceType",
"(",
"\"isOptimizedForIPTV\"",
")",
"+",
"str",
"(",
"wifiInterfaceId",
")",
"uri",
"=",
"self",... | Return if the Wifi interface is optimized for IP TV
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
:return: if the Wifi interface is optimized for IP TV
:rtype: bool
.. seealso:: :meth:`~simpletr64.actions.Fritz.setOptimizedForIPTV` | [
"Return",
"if",
"the",
"Wifi",
"interface",
"is",
"optimized",
"for",
"IP",
"TV"
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L123-L138 | train | 51,543 |
bpannier/simpletr64 | simpletr64/actions/fritz.py | Fritz.setOptimizedForIPTV | def setOptimizedForIPTV(self, status, wifiInterfaceId=1, timeout=1):
"""Set if the Wifi interface is optimized for IP TV
:param bool status: set if Wifi interface should be optimized
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
.. seealso:: :meth:`~simpletr64.actions.Fritz.isOptimizedForIPTV`
"""
namespace = Fritz.getServiceType("setOptimizedForIPTV") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
arguments = {"timeout": timeout, "NewX_AVM-DE_IPTVoptimize": setStatus}
self.execute(uri, namespace, "X_AVM-DE_SetIPTVOptimized", **arguments) | python | def setOptimizedForIPTV(self, status, wifiInterfaceId=1, timeout=1):
"""Set if the Wifi interface is optimized for IP TV
:param bool status: set if Wifi interface should be optimized
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
.. seealso:: :meth:`~simpletr64.actions.Fritz.isOptimizedForIPTV`
"""
namespace = Fritz.getServiceType("setOptimizedForIPTV") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
arguments = {"timeout": timeout, "NewX_AVM-DE_IPTVoptimize": setStatus}
self.execute(uri, namespace, "X_AVM-DE_SetIPTVOptimized", **arguments) | [
"def",
"setOptimizedForIPTV",
"(",
"self",
",",
"status",
",",
"wifiInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Fritz",
".",
"getServiceType",
"(",
"\"setOptimizedForIPTV\"",
")",
"+",
"str",
"(",
"wifiInterfaceId",
")",
"u... | Set if the Wifi interface is optimized for IP TV
:param bool status: set if Wifi interface should be optimized
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
.. seealso:: :meth:`~simpletr64.actions.Fritz.isOptimizedForIPTV` | [
"Set",
"if",
"the",
"Wifi",
"interface",
"is",
"optimized",
"for",
"IP",
"TV"
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L140-L159 | train | 51,544 |
bpannier/simpletr64 | simpletr64/actions/fritz.py | Fritz.getCallList | def getCallList(self, timeout=1):
"""Get the list of phone calls made
Example of a phone call result:
::
[{'Count': None, 'Name': None, 'CalledNumber': '030868709971', 'Numbertype': 'sip', 'Duration': '0:01',
'Caller': '015155255399', 'Called': 'SIP: 030868729971', 'Date': '02.01.14 13:14',
'Device': 'Anrufbeantworter','Path': None, 'Port': '40', 'Type': '1', 'Id': '15'}]
Types:
* 1 - answered
* 2 - missed
* 3 - outgoing
:param float timeout: the timeout to wait for the action to be executed
:return: the list of made phone calls
:rtype: list[dict[str: str]]
"""
namespace = Fritz.getServiceType("getCallList")
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetCallList")
# setup proxies
proxies = {}
if self.httpProxy:
proxies = {"https": self.httpProxy}
if self.httpsProxy:
proxies = {"http": self.httpsProxy}
# get the content
request = requests.get(results["NewCallListURL"], proxies=proxies, timeout=float(timeout))
if request.status_code != 200:
errorStr = DeviceTR64._extractErrorString(request)
raise ValueError('Could not get CPE definitions "' + results["NewCallListURL"] + '" : ' +
str(request.status_code) + ' - ' + request.reason + " -- " + errorStr)
# parse xml
try:
root = ET.fromstring(request.text.encode('utf-8'))
except Exception as e:
raise ValueError("Could not parse call list '" + results["NewCallListURL"] + "': " + str(e))
calls = []
for child in root.getchildren():
if child.tag.lower() == "call":
callParameters = {}
for callChild in child.getchildren():
callParameters[callChild.tag] = callChild.text
calls.append(callParameters)
return calls | python | def getCallList(self, timeout=1):
"""Get the list of phone calls made
Example of a phone call result:
::
[{'Count': None, 'Name': None, 'CalledNumber': '030868709971', 'Numbertype': 'sip', 'Duration': '0:01',
'Caller': '015155255399', 'Called': 'SIP: 030868729971', 'Date': '02.01.14 13:14',
'Device': 'Anrufbeantworter','Path': None, 'Port': '40', 'Type': '1', 'Id': '15'}]
Types:
* 1 - answered
* 2 - missed
* 3 - outgoing
:param float timeout: the timeout to wait for the action to be executed
:return: the list of made phone calls
:rtype: list[dict[str: str]]
"""
namespace = Fritz.getServiceType("getCallList")
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetCallList")
# setup proxies
proxies = {}
if self.httpProxy:
proxies = {"https": self.httpProxy}
if self.httpsProxy:
proxies = {"http": self.httpsProxy}
# get the content
request = requests.get(results["NewCallListURL"], proxies=proxies, timeout=float(timeout))
if request.status_code != 200:
errorStr = DeviceTR64._extractErrorString(request)
raise ValueError('Could not get CPE definitions "' + results["NewCallListURL"] + '" : ' +
str(request.status_code) + ' - ' + request.reason + " -- " + errorStr)
# parse xml
try:
root = ET.fromstring(request.text.encode('utf-8'))
except Exception as e:
raise ValueError("Could not parse call list '" + results["NewCallListURL"] + "': " + str(e))
calls = []
for child in root.getchildren():
if child.tag.lower() == "call":
callParameters = {}
for callChild in child.getchildren():
callParameters[callChild.tag] = callChild.text
calls.append(callParameters)
return calls | [
"def",
"getCallList",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Fritz",
".",
"getServiceType",
"(",
"\"getCallList\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
... | Get the list of phone calls made
Example of a phone call result:
::
[{'Count': None, 'Name': None, 'CalledNumber': '030868709971', 'Numbertype': 'sip', 'Duration': '0:01',
'Caller': '015155255399', 'Called': 'SIP: 030868729971', 'Date': '02.01.14 13:14',
'Device': 'Anrufbeantworter','Path': None, 'Port': '40', 'Type': '1', 'Id': '15'}]
Types:
* 1 - answered
* 2 - missed
* 3 - outgoing
:param float timeout: the timeout to wait for the action to be executed
:return: the list of made phone calls
:rtype: list[dict[str: str]] | [
"Get",
"the",
"list",
"of",
"phone",
"calls",
"made"
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L161-L221 | train | 51,545 |
metachris/RPIO | fabfile.py | upload_to_pypi | def upload_to_pypi():
""" Upload sdist and bdist_eggs to pypi """
# One more safety input and then we are ready to go :)
x = prompt("Are you sure to upload the current version to pypi?")
if not x or not x.lower() in ["y", "yes"]:
return
local("rm -rf dist")
local("python setup.py sdist")
version = _get_cur_version()
fn = "RPIO-%s.tar.gz" % version
put("dist/%s" % fn, "/tmp/")
with cd("/tmp"):
run("tar -xf /tmp/%s" % fn)
with cd("/tmp/RPIO-%s" % version):
run("python2.6 setup.py bdist_egg upload")
run("python2.7 setup.py bdist_egg upload")
run("python3.2 setup.py bdist_egg upload")
local("python setup.py sdist upload") | python | def upload_to_pypi():
""" Upload sdist and bdist_eggs to pypi """
# One more safety input and then we are ready to go :)
x = prompt("Are you sure to upload the current version to pypi?")
if not x or not x.lower() in ["y", "yes"]:
return
local("rm -rf dist")
local("python setup.py sdist")
version = _get_cur_version()
fn = "RPIO-%s.tar.gz" % version
put("dist/%s" % fn, "/tmp/")
with cd("/tmp"):
run("tar -xf /tmp/%s" % fn)
with cd("/tmp/RPIO-%s" % version):
run("python2.6 setup.py bdist_egg upload")
run("python2.7 setup.py bdist_egg upload")
run("python3.2 setup.py bdist_egg upload")
local("python setup.py sdist upload") | [
"def",
"upload_to_pypi",
"(",
")",
":",
"# One more safety input and then we are ready to go :)",
"x",
"=",
"prompt",
"(",
"\"Are you sure to upload the current version to pypi?\"",
")",
"if",
"not",
"x",
"or",
"not",
"x",
".",
"lower",
"(",
")",
"in",
"[",
"\"y\"",
... | Upload sdist and bdist_eggs to pypi | [
"Upload",
"sdist",
"and",
"bdist_eggs",
"to",
"pypi"
] | be1942a69b2592ddacd9dc833d2668a19aafd8d2 | https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/fabfile.py#L181-L199 | train | 51,546 |
metachris/RPIO | source/RPIO/_RPIO.py | _threaded_callback | def _threaded_callback(callback, *args):
"""
Internal wrapper to start a callback in threaded mode. Using the
daemon mode to not block the main thread from exiting.
"""
t = Thread(target=callback, args=args)
t.daemon = True
t.start() | python | def _threaded_callback(callback, *args):
"""
Internal wrapper to start a callback in threaded mode. Using the
daemon mode to not block the main thread from exiting.
"""
t = Thread(target=callback, args=args)
t.daemon = True
t.start() | [
"def",
"_threaded_callback",
"(",
"callback",
",",
"*",
"args",
")",
":",
"t",
"=",
"Thread",
"(",
"target",
"=",
"callback",
",",
"args",
"=",
"args",
")",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
")"
] | Internal wrapper to start a callback in threaded mode. Using the
daemon mode to not block the main thread from exiting. | [
"Internal",
"wrapper",
"to",
"start",
"a",
"callback",
"in",
"threaded",
"mode",
".",
"Using",
"the",
"daemon",
"mode",
"to",
"not",
"block",
"the",
"main",
"thread",
"from",
"exiting",
"."
] | be1942a69b2592ddacd9dc833d2668a19aafd8d2 | https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L48-L55 | train | 51,547 |
metachris/RPIO | source/RPIO/_RPIO.py | Interruptor.del_interrupt_callback | def del_interrupt_callback(self, gpio_id):
""" Delete all interrupt callbacks from a certain gpio """
debug("- removing interrupts on gpio %s" % gpio_id)
gpio_id = _GPIO.channel_to_gpio(gpio_id)
fileno = self._map_gpioid_to_fileno[gpio_id]
# 1. Remove from epoll
self._epoll.unregister(fileno)
# 2. Cache the file
f = self._map_fileno_to_file[fileno]
# 3. Remove from maps
del self._map_fileno_to_file[fileno]
del self._map_fileno_to_gpioid[fileno]
del self._map_fileno_to_options[fileno]
del self._map_gpioid_to_fileno[gpio_id]
del self._map_gpioid_to_callbacks[gpio_id]
# 4. Close file last in case of IOError
f.close() | python | def del_interrupt_callback(self, gpio_id):
""" Delete all interrupt callbacks from a certain gpio """
debug("- removing interrupts on gpio %s" % gpio_id)
gpio_id = _GPIO.channel_to_gpio(gpio_id)
fileno = self._map_gpioid_to_fileno[gpio_id]
# 1. Remove from epoll
self._epoll.unregister(fileno)
# 2. Cache the file
f = self._map_fileno_to_file[fileno]
# 3. Remove from maps
del self._map_fileno_to_file[fileno]
del self._map_fileno_to_gpioid[fileno]
del self._map_fileno_to_options[fileno]
del self._map_gpioid_to_fileno[gpio_id]
del self._map_gpioid_to_callbacks[gpio_id]
# 4. Close file last in case of IOError
f.close() | [
"def",
"del_interrupt_callback",
"(",
"self",
",",
"gpio_id",
")",
":",
"debug",
"(",
"\"- removing interrupts on gpio %s\"",
"%",
"gpio_id",
")",
"gpio_id",
"=",
"_GPIO",
".",
"channel_to_gpio",
"(",
"gpio_id",
")",
"fileno",
"=",
"self",
".",
"_map_gpioid_to_fil... | Delete all interrupt callbacks from a certain gpio | [
"Delete",
"all",
"interrupt",
"callbacks",
"from",
"a",
"certain",
"gpio"
] | be1942a69b2592ddacd9dc833d2668a19aafd8d2 | https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L219-L239 | train | 51,548 |
metachris/RPIO | source/RPIO/_RPIO.py | Interruptor._handle_interrupt | def _handle_interrupt(self, fileno, val):
""" Internally distributes interrupts to all attached callbacks """
val = int(val)
# Filter invalid edge values (sometimes 1 comes in when edge=falling)
edge = self._map_fileno_to_options[fileno]["edge"]
if (edge == 'rising' and val == 0) or (edge == 'falling' and val == 1):
return
# If user activated debounce for this callback, check timing now
debounce = self._map_fileno_to_options[fileno]["debounce_timeout_s"]
if debounce:
t = time.time()
t_last = self._map_fileno_to_options[fileno]["interrupt_last"]
if t - t_last < debounce:
debug("- don't start interrupt callback due to debouncing")
return
self._map_fileno_to_options[fileno]["interrupt_last"] = t
# Start the callback(s) now
gpio_id = self._map_fileno_to_gpioid[fileno]
if gpio_id in self._map_gpioid_to_callbacks:
for cb in self._map_gpioid_to_callbacks[gpio_id]:
cb(gpio_id, val) | python | def _handle_interrupt(self, fileno, val):
""" Internally distributes interrupts to all attached callbacks """
val = int(val)
# Filter invalid edge values (sometimes 1 comes in when edge=falling)
edge = self._map_fileno_to_options[fileno]["edge"]
if (edge == 'rising' and val == 0) or (edge == 'falling' and val == 1):
return
# If user activated debounce for this callback, check timing now
debounce = self._map_fileno_to_options[fileno]["debounce_timeout_s"]
if debounce:
t = time.time()
t_last = self._map_fileno_to_options[fileno]["interrupt_last"]
if t - t_last < debounce:
debug("- don't start interrupt callback due to debouncing")
return
self._map_fileno_to_options[fileno]["interrupt_last"] = t
# Start the callback(s) now
gpio_id = self._map_fileno_to_gpioid[fileno]
if gpio_id in self._map_gpioid_to_callbacks:
for cb in self._map_gpioid_to_callbacks[gpio_id]:
cb(gpio_id, val) | [
"def",
"_handle_interrupt",
"(",
"self",
",",
"fileno",
",",
"val",
")",
":",
"val",
"=",
"int",
"(",
"val",
")",
"# Filter invalid edge values (sometimes 1 comes in when edge=falling)",
"edge",
"=",
"self",
".",
"_map_fileno_to_options",
"[",
"fileno",
"]",
"[",
... | Internally distributes interrupts to all attached callbacks | [
"Internally",
"distributes",
"interrupts",
"to",
"all",
"attached",
"callbacks"
] | be1942a69b2592ddacd9dc833d2668a19aafd8d2 | https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L241-L264 | train | 51,549 |
metachris/RPIO | source/RPIO/_RPIO.py | Interruptor.cleanup_tcpsockets | def cleanup_tcpsockets(self):
"""
Closes all TCP connections and then the socket servers
"""
for fileno in self._tcp_client_sockets.keys():
self.close_tcp_client(fileno)
for fileno, items in self._tcp_server_sockets.items():
socket, cb = items
debug("- _cleanup server socket connection (fd %s)" % fileno)
self._epoll.unregister(fileno)
socket.close()
self._tcp_server_sockets = {} | python | def cleanup_tcpsockets(self):
"""
Closes all TCP connections and then the socket servers
"""
for fileno in self._tcp_client_sockets.keys():
self.close_tcp_client(fileno)
for fileno, items in self._tcp_server_sockets.items():
socket, cb = items
debug("- _cleanup server socket connection (fd %s)" % fileno)
self._epoll.unregister(fileno)
socket.close()
self._tcp_server_sockets = {} | [
"def",
"cleanup_tcpsockets",
"(",
"self",
")",
":",
"for",
"fileno",
"in",
"self",
".",
"_tcp_client_sockets",
".",
"keys",
"(",
")",
":",
"self",
".",
"close_tcp_client",
"(",
"fileno",
")",
"for",
"fileno",
",",
"items",
"in",
"self",
".",
"_tcp_server_s... | Closes all TCP connections and then the socket servers | [
"Closes",
"all",
"TCP",
"connections",
"and",
"then",
"the",
"socket",
"servers"
] | be1942a69b2592ddacd9dc833d2668a19aafd8d2 | https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L349-L360 | train | 51,550 |
metachris/RPIO | source/RPIO/PWM/__init__.py | add_channel_pulse | def add_channel_pulse(dma_channel, gpio, start, width):
"""
Add a pulse for a specific GPIO to a dma channel subcycle. `start` and
`width` are multiples of the pulse-width increment granularity.
"""
return _PWM.add_channel_pulse(dma_channel, gpio, start, width) | python | def add_channel_pulse(dma_channel, gpio, start, width):
"""
Add a pulse for a specific GPIO to a dma channel subcycle. `start` and
`width` are multiples of the pulse-width increment granularity.
"""
return _PWM.add_channel_pulse(dma_channel, gpio, start, width) | [
"def",
"add_channel_pulse",
"(",
"dma_channel",
",",
"gpio",
",",
"start",
",",
"width",
")",
":",
"return",
"_PWM",
".",
"add_channel_pulse",
"(",
"dma_channel",
",",
"gpio",
",",
"start",
",",
"width",
")"
] | Add a pulse for a specific GPIO to a dma channel subcycle. `start` and
`width` are multiples of the pulse-width increment granularity. | [
"Add",
"a",
"pulse",
"for",
"a",
"specific",
"GPIO",
"to",
"a",
"dma",
"channel",
"subcycle",
".",
"start",
"and",
"width",
"are",
"multiples",
"of",
"the",
"pulse",
"-",
"width",
"increment",
"granularity",
"."
] | be1942a69b2592ddacd9dc833d2668a19aafd8d2 | https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/PWM/__init__.py#L110-L115 | train | 51,551 |
macbre/sql-metadata | sql_metadata.py | unique | def unique(_list):
"""
Makes the list have unique items only and maintains the order
list(set()) won't provide that
:type _list list
:rtype: list
"""
ret = []
for item in _list:
if item not in ret:
ret.append(item)
return ret | python | def unique(_list):
"""
Makes the list have unique items only and maintains the order
list(set()) won't provide that
:type _list list
:rtype: list
"""
ret = []
for item in _list:
if item not in ret:
ret.append(item)
return ret | [
"def",
"unique",
"(",
"_list",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"item",
"in",
"_list",
":",
"if",
"item",
"not",
"in",
"ret",
":",
"ret",
".",
"append",
"(",
"item",
")",
"return",
"ret"
] | Makes the list have unique items only and maintains the order
list(set()) won't provide that
:type _list list
:rtype: list | [
"Makes",
"the",
"list",
"have",
"unique",
"items",
"only",
"and",
"maintains",
"the",
"order"
] | 4b7b4ae0a961d568075aefe78535cf5aee74583c | https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L12-L27 | train | 51,552 |
macbre/sql-metadata | sql_metadata.py | preprocess_query | def preprocess_query(query):
"""
Perform initial query cleanup
:type query str
:rtype str
"""
# 1. remove aliases
# FROM `dimension_wikis` `dw`
# INNER JOIN `fact_wam_scores` `fwN`
query = re.sub(r'(\s(FROM|JOIN)\s`[^`]+`)\s`[^`]+`', r'\1', query, flags=re.IGNORECASE)
# 2. `database`.`table` notation -> database.table
query = re.sub(r'`([^`]+)`\.`([^`]+)`', r'\1.\2', query)
# 2. database.table notation -> table
# query = re.sub(r'([a-z_0-9]+)\.([a-z_0-9]+)', r'\2', query, flags=re.IGNORECASE)
return query | python | def preprocess_query(query):
"""
Perform initial query cleanup
:type query str
:rtype str
"""
# 1. remove aliases
# FROM `dimension_wikis` `dw`
# INNER JOIN `fact_wam_scores` `fwN`
query = re.sub(r'(\s(FROM|JOIN)\s`[^`]+`)\s`[^`]+`', r'\1', query, flags=re.IGNORECASE)
# 2. `database`.`table` notation -> database.table
query = re.sub(r'`([^`]+)`\.`([^`]+)`', r'\1.\2', query)
# 2. database.table notation -> table
# query = re.sub(r'([a-z_0-9]+)\.([a-z_0-9]+)', r'\2', query, flags=re.IGNORECASE)
return query | [
"def",
"preprocess_query",
"(",
"query",
")",
":",
"# 1. remove aliases",
"# FROM `dimension_wikis` `dw`",
"# INNER JOIN `fact_wam_scores` `fwN`",
"query",
"=",
"re",
".",
"sub",
"(",
"r'(\\s(FROM|JOIN)\\s`[^`]+`)\\s`[^`]+`'",
",",
"r'\\1'",
",",
"query",
",",
"flags",
"=... | Perform initial query cleanup
:type query str
:rtype str | [
"Perform",
"initial",
"query",
"cleanup"
] | 4b7b4ae0a961d568075aefe78535cf5aee74583c | https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L30-L48 | train | 51,553 |
macbre/sql-metadata | sql_metadata.py | normalize_likes | def normalize_likes(sql):
"""
Normalize and wrap LIKE statements
:type sql str
:rtype: str
"""
sql = sql.replace('%', '')
# LIKE '%bot'
sql = re.sub(r"LIKE '[^\']+'", 'LIKE X', sql)
# or all_groups LIKE X or all_groups LIKE X
matches = re.finditer(r'(or|and) [^\s]+ LIKE X', sql, flags=re.IGNORECASE)
matches = [match.group(0) for match in matches] if matches else None
if matches:
for match in set(matches):
sql = re.sub(r'(\s?' + re.escape(match) + ')+', ' ' + match + ' ...', sql)
return sql | python | def normalize_likes(sql):
"""
Normalize and wrap LIKE statements
:type sql str
:rtype: str
"""
sql = sql.replace('%', '')
# LIKE '%bot'
sql = re.sub(r"LIKE '[^\']+'", 'LIKE X', sql)
# or all_groups LIKE X or all_groups LIKE X
matches = re.finditer(r'(or|and) [^\s]+ LIKE X', sql, flags=re.IGNORECASE)
matches = [match.group(0) for match in matches] if matches else None
if matches:
for match in set(matches):
sql = re.sub(r'(\s?' + re.escape(match) + ')+', ' ' + match + ' ...', sql)
return sql | [
"def",
"normalize_likes",
"(",
"sql",
")",
":",
"sql",
"=",
"sql",
".",
"replace",
"(",
"'%'",
",",
"''",
")",
"# LIKE '%bot'",
"sql",
"=",
"re",
".",
"sub",
"(",
"r\"LIKE '[^\\']+'\"",
",",
"'LIKE X'",
",",
"sql",
")",
"# or all_groups LIKE X or all_groups ... | Normalize and wrap LIKE statements
:type sql str
:rtype: str | [
"Normalize",
"and",
"wrap",
"LIKE",
"statements"
] | 4b7b4ae0a961d568075aefe78535cf5aee74583c | https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L236-L256 | train | 51,554 |
macbre/sql-metadata | sql_metadata.py | generalize_sql | def generalize_sql(sql):
"""
Removes most variables from an SQL query and replaces them with X or N for numbers.
Based on Mediawiki's DatabaseBase::generalizeSQL
:type sql str|None
:rtype: str
"""
if sql is None:
return None
# multiple spaces
sql = re.sub(r'\s{2,}', ' ', sql)
# MW comments
# e.g. /* CategoryDataService::getMostVisited N.N.N.N */
sql = remove_comments_from_sql(sql)
# handle LIKE statements
sql = normalize_likes(sql)
sql = re.sub(r"\\\\", '', sql)
sql = re.sub(r"\\'", '', sql)
sql = re.sub(r'\\"', '', sql)
sql = re.sub(r"'[^\']*'", 'X', sql)
sql = re.sub(r'"[^\"]*"', 'X', sql)
# All newlines, tabs, etc replaced by single space
sql = re.sub(r'\s+', ' ', sql)
# All numbers => N
sql = re.sub(r'-?[0-9]+', 'N', sql)
# WHERE foo IN ('880987','882618','708228','522330')
sql = re.sub(r' (IN|VALUES)\s*\([^,]+,[^)]+\)', ' \\1 (XYZ)', sql, flags=re.IGNORECASE)
return sql.strip() | python | def generalize_sql(sql):
"""
Removes most variables from an SQL query and replaces them with X or N for numbers.
Based on Mediawiki's DatabaseBase::generalizeSQL
:type sql str|None
:rtype: str
"""
if sql is None:
return None
# multiple spaces
sql = re.sub(r'\s{2,}', ' ', sql)
# MW comments
# e.g. /* CategoryDataService::getMostVisited N.N.N.N */
sql = remove_comments_from_sql(sql)
# handle LIKE statements
sql = normalize_likes(sql)
sql = re.sub(r"\\\\", '', sql)
sql = re.sub(r"\\'", '', sql)
sql = re.sub(r'\\"', '', sql)
sql = re.sub(r"'[^\']*'", 'X', sql)
sql = re.sub(r'"[^\"]*"', 'X', sql)
# All newlines, tabs, etc replaced by single space
sql = re.sub(r'\s+', ' ', sql)
# All numbers => N
sql = re.sub(r'-?[0-9]+', 'N', sql)
# WHERE foo IN ('880987','882618','708228','522330')
sql = re.sub(r' (IN|VALUES)\s*\([^,]+,[^)]+\)', ' \\1 (XYZ)', sql, flags=re.IGNORECASE)
return sql.strip() | [
"def",
"generalize_sql",
"(",
"sql",
")",
":",
"if",
"sql",
"is",
"None",
":",
"return",
"None",
"# multiple spaces",
"sql",
"=",
"re",
".",
"sub",
"(",
"r'\\s{2,}'",
",",
"' '",
",",
"sql",
")",
"# MW comments",
"# e.g. /* CategoryDataService::getMostVisited N.... | Removes most variables from an SQL query and replaces them with X or N for numbers.
Based on Mediawiki's DatabaseBase::generalizeSQL
:type sql str|None
:rtype: str | [
"Removes",
"most",
"variables",
"from",
"an",
"SQL",
"query",
"and",
"replaces",
"them",
"with",
"X",
"or",
"N",
"for",
"numbers",
"."
] | 4b7b4ae0a961d568075aefe78535cf5aee74583c | https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L269-L306 | train | 51,555 |
biocore/deblur | deblur/parallel_deblur.py | deblur_system_call | def deblur_system_call(params, input_fp):
"""Build deblur command for subprocess.
Parameters
----------
params: list of str
parameter settings to pass to deblur CLI
input_fp : str
name of the input fasta file to deblur
Returns
-------
stdout: string
process output directed to standard output
stderr: string
process output directed to standard error
return_value: integer
return code from process
"""
logger = logging.getLogger(__name__)
logger.debug('[%s] deblur system call params %s, input_fp %s' %
(mp.current_process().name, params, input_fp))
# construct command
script_name = "deblur"
script_subprogram = "workflow"
command = [script_name,
script_subprogram,
'--seqs-fp', input_fp,
'--is-worker-thread',
'--keep-tmp-files']
command.extend(params)
logger.debug('[%s] running command %s' % (mp.current_process().name,
command))
return _system_call(command) | python | def deblur_system_call(params, input_fp):
"""Build deblur command for subprocess.
Parameters
----------
params: list of str
parameter settings to pass to deblur CLI
input_fp : str
name of the input fasta file to deblur
Returns
-------
stdout: string
process output directed to standard output
stderr: string
process output directed to standard error
return_value: integer
return code from process
"""
logger = logging.getLogger(__name__)
logger.debug('[%s] deblur system call params %s, input_fp %s' %
(mp.current_process().name, params, input_fp))
# construct command
script_name = "deblur"
script_subprogram = "workflow"
command = [script_name,
script_subprogram,
'--seqs-fp', input_fp,
'--is-worker-thread',
'--keep-tmp-files']
command.extend(params)
logger.debug('[%s] running command %s' % (mp.current_process().name,
command))
return _system_call(command) | [
"def",
"deblur_system_call",
"(",
"params",
",",
"input_fp",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'[%s] deblur system call params %s, input_fp %s'",
"%",
"(",
"mp",
".",
"current_process",
"(",
... | Build deblur command for subprocess.
Parameters
----------
params: list of str
parameter settings to pass to deblur CLI
input_fp : str
name of the input fasta file to deblur
Returns
-------
stdout: string
process output directed to standard output
stderr: string
process output directed to standard error
return_value: integer
return code from process | [
"Build",
"deblur",
"command",
"for",
"subprocess",
"."
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/parallel_deblur.py#L17-L53 | train | 51,556 |
biocore/deblur | deblur/parallel_deblur.py | run_functor | def run_functor(functor, *args, **kwargs):
"""
Given a functor, run it and return its result. We can use this with
multiprocessing.map and map it over a list of job functors to do them.
Handles getting more than multiprocessing's pitiful exception output
This function was derived from:
http://stackoverflow.com/a/16618842/19741
This code was adopted from the American Gut project:
https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py
"""
try:
# This is where you do your actual work
return functor(*args, **kwargs)
except Exception:
# Put all exception text into an exception and raise that
raise Exception("".join(traceback.format_exception(*sys.exc_info()))) | python | def run_functor(functor, *args, **kwargs):
"""
Given a functor, run it and return its result. We can use this with
multiprocessing.map and map it over a list of job functors to do them.
Handles getting more than multiprocessing's pitiful exception output
This function was derived from:
http://stackoverflow.com/a/16618842/19741
This code was adopted from the American Gut project:
https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py
"""
try:
# This is where you do your actual work
return functor(*args, **kwargs)
except Exception:
# Put all exception text into an exception and raise that
raise Exception("".join(traceback.format_exception(*sys.exc_info()))) | [
"def",
"run_functor",
"(",
"functor",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# This is where you do your actual work",
"return",
"functor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"# Put all exce... | Given a functor, run it and return its result. We can use this with
multiprocessing.map and map it over a list of job functors to do them.
Handles getting more than multiprocessing's pitiful exception output
This function was derived from:
http://stackoverflow.com/a/16618842/19741
This code was adopted from the American Gut project:
https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py | [
"Given",
"a",
"functor",
"run",
"it",
"and",
"return",
"its",
"result",
".",
"We",
"can",
"use",
"this",
"with",
"multiprocessing",
".",
"map",
"and",
"map",
"it",
"over",
"a",
"list",
"of",
"job",
"functors",
"to",
"do",
"them",
"."
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/parallel_deblur.py#L56-L74 | train | 51,557 |
biocore/deblur | deblur/parallel_deblur.py | parallel_deblur | def parallel_deblur(inputs, params,
pos_ref_db_fp, neg_ref_dp_fp, jobs_to_start=1):
"""Dispatch execution over a pool of processors
This code was adopted from the American Gut project:
https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py
Parameters
----------
inputs : iterable of str
File paths to input per-sample sequence files
params : list of str
list of CLI parameters supplied to the deblur workflow
(argv - first 2 are 'deblur','workflow' and are ignored)
pos_ref_db_fp : list of str
the indexed positive (16s) sortmerna database
(created in the main thread)
neg_ref_db_fp : list of str
the indexed negative (artifacts) sortmerna database
(created in the main thread)
jobs_to_start : int, optional
The number of processors on the local system to use
Returns
-------
all_result_paths : list
list of expected output files
"""
logger = logging.getLogger(__name__)
logger.info('parallel deblur started for %d inputs' % len(inputs))
# remove the irrelevant parameters
remove_param_list = ['-O', '--jobs-to-start', '--seqs-fp',
'--pos-ref-db-fp', '--neg-ref-db-fp']
skipnext = False
newparams = []
for carg in params[2:]:
if skipnext:
skipnext = False
continue
if carg in remove_param_list:
skipnext = True
continue
newparams.append(carg)
# add the ref_db_fp (since it may be not present in the
# original command parameters)
if pos_ref_db_fp:
new_pos_ref_db_fp = ','.join(pos_ref_db_fp)
newparams.append('--pos-ref-db-fp')
newparams.append(new_pos_ref_db_fp)
if neg_ref_dp_fp:
new_neg_ref_db_fp = ','.join(neg_ref_dp_fp)
newparams.append('--neg-ref-db-fp')
newparams.append(new_neg_ref_db_fp)
logger.debug('ready for functor %s' % newparams)
functor = partial(run_functor, deblur_system_call, newparams)
logger.debug('ready for pool %d jobs' % jobs_to_start)
pool = mp.Pool(processes=jobs_to_start)
logger.debug('almost running...')
for stdout, stderr, es in pool.map(functor, inputs):
if es != 0:
raise RuntimeError("stdout: %s\nstderr: %s\nexit: %d" % (stdout,
stderr,
es)) | python | def parallel_deblur(inputs, params,
pos_ref_db_fp, neg_ref_dp_fp, jobs_to_start=1):
"""Dispatch execution over a pool of processors
This code was adopted from the American Gut project:
https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py
Parameters
----------
inputs : iterable of str
File paths to input per-sample sequence files
params : list of str
list of CLI parameters supplied to the deblur workflow
(argv - first 2 are 'deblur','workflow' and are ignored)
pos_ref_db_fp : list of str
the indexed positive (16s) sortmerna database
(created in the main thread)
neg_ref_db_fp : list of str
the indexed negative (artifacts) sortmerna database
(created in the main thread)
jobs_to_start : int, optional
The number of processors on the local system to use
Returns
-------
all_result_paths : list
list of expected output files
"""
logger = logging.getLogger(__name__)
logger.info('parallel deblur started for %d inputs' % len(inputs))
# remove the irrelevant parameters
remove_param_list = ['-O', '--jobs-to-start', '--seqs-fp',
'--pos-ref-db-fp', '--neg-ref-db-fp']
skipnext = False
newparams = []
for carg in params[2:]:
if skipnext:
skipnext = False
continue
if carg in remove_param_list:
skipnext = True
continue
newparams.append(carg)
# add the ref_db_fp (since it may be not present in the
# original command parameters)
if pos_ref_db_fp:
new_pos_ref_db_fp = ','.join(pos_ref_db_fp)
newparams.append('--pos-ref-db-fp')
newparams.append(new_pos_ref_db_fp)
if neg_ref_dp_fp:
new_neg_ref_db_fp = ','.join(neg_ref_dp_fp)
newparams.append('--neg-ref-db-fp')
newparams.append(new_neg_ref_db_fp)
logger.debug('ready for functor %s' % newparams)
functor = partial(run_functor, deblur_system_call, newparams)
logger.debug('ready for pool %d jobs' % jobs_to_start)
pool = mp.Pool(processes=jobs_to_start)
logger.debug('almost running...')
for stdout, stderr, es in pool.map(functor, inputs):
if es != 0:
raise RuntimeError("stdout: %s\nstderr: %s\nexit: %d" % (stdout,
stderr,
es)) | [
"def",
"parallel_deblur",
"(",
"inputs",
",",
"params",
",",
"pos_ref_db_fp",
",",
"neg_ref_dp_fp",
",",
"jobs_to_start",
"=",
"1",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"info",
"(",
"'parallel deblur starte... | Dispatch execution over a pool of processors
This code was adopted from the American Gut project:
https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py
Parameters
----------
inputs : iterable of str
File paths to input per-sample sequence files
params : list of str
list of CLI parameters supplied to the deblur workflow
(argv - first 2 are 'deblur','workflow' and are ignored)
pos_ref_db_fp : list of str
the indexed positive (16s) sortmerna database
(created in the main thread)
neg_ref_db_fp : list of str
the indexed negative (artifacts) sortmerna database
(created in the main thread)
jobs_to_start : int, optional
The number of processors on the local system to use
Returns
-------
all_result_paths : list
list of expected output files | [
"Dispatch",
"execution",
"over",
"a",
"pool",
"of",
"processors"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/parallel_deblur.py#L77-L142 | train | 51,558 |
biocore/deblur | deblur/workflow.py | trim_seqs | def trim_seqs(input_seqs, trim_len, left_trim_len):
"""Trim FASTA sequences to specified length.
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format
trim_len : int
Sequence trimming length. Specify a value of -1 to disable trimming.
left_trim_len : int
Sequence trimming from the 5' end. A value of 0 will disable this trim.
Returns
-------
Generator of (str, str)
The trimmed sequences in (label, sequence) format
"""
# counters for the number of trimmed and total sequences
logger = logging.getLogger(__name__)
okseqs = 0
totseqs = 0
if trim_len < -1:
raise ValueError("Invalid trim_len: %d" % trim_len)
for label, seq in input_seqs:
totseqs += 1
if trim_len == -1:
okseqs += 1
yield label, seq
elif len(seq) >= trim_len:
okseqs += 1
yield label, seq[left_trim_len:trim_len]
if okseqs < 0.01*totseqs:
logger = logging.getLogger(__name__)
errmsg = 'Vast majority of sequences (%d / %d) are shorter ' \
'than the trim length (%d). ' \
'Are you using the correct -t trim length?' \
% (totseqs-okseqs, totseqs, trim_len)
logger.warn(errmsg)
warnings.warn(errmsg, UserWarning)
else:
logger.debug('trimmed to length %d (%d / %d remaining)'
% (trim_len, okseqs, totseqs)) | python | def trim_seqs(input_seqs, trim_len, left_trim_len):
"""Trim FASTA sequences to specified length.
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format
trim_len : int
Sequence trimming length. Specify a value of -1 to disable trimming.
left_trim_len : int
Sequence trimming from the 5' end. A value of 0 will disable this trim.
Returns
-------
Generator of (str, str)
The trimmed sequences in (label, sequence) format
"""
# counters for the number of trimmed and total sequences
logger = logging.getLogger(__name__)
okseqs = 0
totseqs = 0
if trim_len < -1:
raise ValueError("Invalid trim_len: %d" % trim_len)
for label, seq in input_seqs:
totseqs += 1
if trim_len == -1:
okseqs += 1
yield label, seq
elif len(seq) >= trim_len:
okseqs += 1
yield label, seq[left_trim_len:trim_len]
if okseqs < 0.01*totseqs:
logger = logging.getLogger(__name__)
errmsg = 'Vast majority of sequences (%d / %d) are shorter ' \
'than the trim length (%d). ' \
'Are you using the correct -t trim length?' \
% (totseqs-okseqs, totseqs, trim_len)
logger.warn(errmsg)
warnings.warn(errmsg, UserWarning)
else:
logger.debug('trimmed to length %d (%d / %d remaining)'
% (trim_len, okseqs, totseqs)) | [
"def",
"trim_seqs",
"(",
"input_seqs",
",",
"trim_len",
",",
"left_trim_len",
")",
":",
"# counters for the number of trimmed and total sequences",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"okseqs",
"=",
"0",
"totseqs",
"=",
"0",
"if",
"tr... | Trim FASTA sequences to specified length.
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format
trim_len : int
Sequence trimming length. Specify a value of -1 to disable trimming.
left_trim_len : int
Sequence trimming from the 5' end. A value of 0 will disable this trim.
Returns
-------
Generator of (str, str)
The trimmed sequences in (label, sequence) format | [
"Trim",
"FASTA",
"sequences",
"to",
"specified",
"length",
"."
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L103-L150 | train | 51,559 |
biocore/deblur | deblur/workflow.py | dereplicate_seqs | def dereplicate_seqs(seqs_fp,
output_fp,
min_size=2,
use_log=False,
threads=1):
"""Dereplicate FASTA sequences and remove singletons using VSEARCH.
Parameters
----------
seqs_fp : string
filepath to FASTA sequence file
output_fp : string
file path to dereplicated sequences (FASTA format)
min_size : integer, optional
discard sequences with an abundance value smaller
than integer
use_log: boolean, optional
save the vsearch logfile as well (to output_fp.log)
default=False
threads : int, optional
number of threads to use (0 for all available)
"""
logger = logging.getLogger(__name__)
logger.info('dereplicate seqs file %s' % seqs_fp)
log_name = "%s.log" % output_fp
params = ['vsearch', '--derep_fulllength', seqs_fp,
'--output', output_fp, '--sizeout',
'--fasta_width', '0', '--minuniquesize', str(min_size),
'--quiet', '--threads', str(threads)]
if use_log:
params.extend(['--log', log_name])
sout, serr, res = _system_call(params)
if not res == 0:
logger.error('Problem running vsearch dereplication on file %s' %
seqs_fp)
logger.debug('parameters used:\n%s' % params)
logger.debug('stdout: %s' % sout)
logger.debug('stderr: %s' % serr)
return | python | def dereplicate_seqs(seqs_fp,
output_fp,
min_size=2,
use_log=False,
threads=1):
"""Dereplicate FASTA sequences and remove singletons using VSEARCH.
Parameters
----------
seqs_fp : string
filepath to FASTA sequence file
output_fp : string
file path to dereplicated sequences (FASTA format)
min_size : integer, optional
discard sequences with an abundance value smaller
than integer
use_log: boolean, optional
save the vsearch logfile as well (to output_fp.log)
default=False
threads : int, optional
number of threads to use (0 for all available)
"""
logger = logging.getLogger(__name__)
logger.info('dereplicate seqs file %s' % seqs_fp)
log_name = "%s.log" % output_fp
params = ['vsearch', '--derep_fulllength', seqs_fp,
'--output', output_fp, '--sizeout',
'--fasta_width', '0', '--minuniquesize', str(min_size),
'--quiet', '--threads', str(threads)]
if use_log:
params.extend(['--log', log_name])
sout, serr, res = _system_call(params)
if not res == 0:
logger.error('Problem running vsearch dereplication on file %s' %
seqs_fp)
logger.debug('parameters used:\n%s' % params)
logger.debug('stdout: %s' % sout)
logger.debug('stderr: %s' % serr)
return | [
"def",
"dereplicate_seqs",
"(",
"seqs_fp",
",",
"output_fp",
",",
"min_size",
"=",
"2",
",",
"use_log",
"=",
"False",
",",
"threads",
"=",
"1",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"info",
"(",
"'de... | Dereplicate FASTA sequences and remove singletons using VSEARCH.
Parameters
----------
seqs_fp : string
filepath to FASTA sequence file
output_fp : string
file path to dereplicated sequences (FASTA format)
min_size : integer, optional
discard sequences with an abundance value smaller
than integer
use_log: boolean, optional
save the vsearch logfile as well (to output_fp.log)
default=False
threads : int, optional
number of threads to use (0 for all available) | [
"Dereplicate",
"FASTA",
"sequences",
"and",
"remove",
"singletons",
"using",
"VSEARCH",
"."
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L153-L193 | train | 51,560 |
biocore/deblur | deblur/workflow.py | build_index_sortmerna | def build_index_sortmerna(ref_fp, working_dir):
"""Build a SortMeRNA index for all reference databases.
Parameters
----------
ref_fp: tuple
filepaths to FASTA reference databases
working_dir: string
working directory path where to store the indexed database
Returns
-------
all_db: tuple
filepaths to SortMeRNA indexed reference databases
"""
logger = logging.getLogger(__name__)
logger.info('build_index_sortmerna files %s to'
' dir %s' % (ref_fp, working_dir))
all_db = []
for db in ref_fp:
fasta_dir, fasta_filename = split(db)
index_basename = splitext(fasta_filename)[0]
db_output = join(working_dir, index_basename)
logger.debug('processing file %s into location %s' % (db, db_output))
params = ['indexdb_rna', '--ref', '%s,%s' %
(db, db_output), '--tmpdir', working_dir]
sout, serr, res = _system_call(params)
if not res == 0:
logger.error('Problem running indexdb_rna on file %s to dir %s. '
'database not indexed' % (db, db_output))
logger.debug('stdout: %s' % sout)
logger.debug('stderr: %s' % serr)
logger.critical('execution halted')
raise RuntimeError('Cannot index database file %s' % db)
logger.debug('file %s indexed' % db)
all_db.append(db_output)
return all_db | python | def build_index_sortmerna(ref_fp, working_dir):
"""Build a SortMeRNA index for all reference databases.
Parameters
----------
ref_fp: tuple
filepaths to FASTA reference databases
working_dir: string
working directory path where to store the indexed database
Returns
-------
all_db: tuple
filepaths to SortMeRNA indexed reference databases
"""
logger = logging.getLogger(__name__)
logger.info('build_index_sortmerna files %s to'
' dir %s' % (ref_fp, working_dir))
all_db = []
for db in ref_fp:
fasta_dir, fasta_filename = split(db)
index_basename = splitext(fasta_filename)[0]
db_output = join(working_dir, index_basename)
logger.debug('processing file %s into location %s' % (db, db_output))
params = ['indexdb_rna', '--ref', '%s,%s' %
(db, db_output), '--tmpdir', working_dir]
sout, serr, res = _system_call(params)
if not res == 0:
logger.error('Problem running indexdb_rna on file %s to dir %s. '
'database not indexed' % (db, db_output))
logger.debug('stdout: %s' % sout)
logger.debug('stderr: %s' % serr)
logger.critical('execution halted')
raise RuntimeError('Cannot index database file %s' % db)
logger.debug('file %s indexed' % db)
all_db.append(db_output)
return all_db | [
"def",
"build_index_sortmerna",
"(",
"ref_fp",
",",
"working_dir",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"info",
"(",
"'build_index_sortmerna files %s to'",
"' dir %s'",
"%",
"(",
"ref_fp",
",",
"working_dir",
... | Build a SortMeRNA index for all reference databases.
Parameters
----------
ref_fp: tuple
filepaths to FASTA reference databases
working_dir: string
working directory path where to store the indexed database
Returns
-------
all_db: tuple
filepaths to SortMeRNA indexed reference databases | [
"Build",
"a",
"SortMeRNA",
"index",
"for",
"all",
"reference",
"databases",
"."
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L196-L232 | train | 51,561 |
biocore/deblur | deblur/workflow.py | filter_minreads_samples_from_table | def filter_minreads_samples_from_table(table, minreads=1, inplace=True):
"""Filter samples from biom table that have less than
minreads reads total
Paraneters
----------
table : biom.Table
the biom table to filter
minreads : int (optional)
the minimal number of reads in a sample in order to keep it
inplace : bool (optional)
if True, filter the biom table in place, if false create a new copy
Returns
-------
table : biom.Table
the filtered biom table
"""
logger = logging.getLogger(__name__)
logger.debug('filter_minreads_started. minreads=%d' % minreads)
samp_sum = table.sum(axis='sample')
samp_ids = table.ids(axis='sample')
bad_samples = samp_ids[samp_sum < minreads]
if len(bad_samples) > 0:
logger.warn('removed %d samples with reads per sample<%d'
% (len(bad_samples), minreads))
table = table.filter(bad_samples, axis='sample',
inplace=inplace, invert=True)
else:
logger.debug('all samples contain > %d reads' % minreads)
return table | python | def filter_minreads_samples_from_table(table, minreads=1, inplace=True):
"""Filter samples from biom table that have less than
minreads reads total
Paraneters
----------
table : biom.Table
the biom table to filter
minreads : int (optional)
the minimal number of reads in a sample in order to keep it
inplace : bool (optional)
if True, filter the biom table in place, if false create a new copy
Returns
-------
table : biom.Table
the filtered biom table
"""
logger = logging.getLogger(__name__)
logger.debug('filter_minreads_started. minreads=%d' % minreads)
samp_sum = table.sum(axis='sample')
samp_ids = table.ids(axis='sample')
bad_samples = samp_ids[samp_sum < minreads]
if len(bad_samples) > 0:
logger.warn('removed %d samples with reads per sample<%d'
% (len(bad_samples), minreads))
table = table.filter(bad_samples, axis='sample',
inplace=inplace, invert=True)
else:
logger.debug('all samples contain > %d reads' % minreads)
return table | [
"def",
"filter_minreads_samples_from_table",
"(",
"table",
",",
"minreads",
"=",
"1",
",",
"inplace",
"=",
"True",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'filter_minreads_started. minreads=%d'",
... | Filter samples from biom table that have less than
minreads reads total
Paraneters
----------
table : biom.Table
the biom table to filter
minreads : int (optional)
the minimal number of reads in a sample in order to keep it
inplace : bool (optional)
if True, filter the biom table in place, if false create a new copy
Returns
-------
table : biom.Table
the filtered biom table | [
"Filter",
"samples",
"from",
"biom",
"table",
"that",
"have",
"less",
"than",
"minreads",
"reads",
"total"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L235-L265 | train | 51,562 |
biocore/deblur | deblur/workflow.py | fasta_from_biom | def fasta_from_biom(table, fasta_file_name):
'''Save sequences from a biom table to a fasta file
Parameters
----------
table : biom.Table
The biom table containing the sequences
fasta_file_name : str
Name of the fasta output file
'''
logger = logging.getLogger(__name__)
logger.debug('saving biom table sequences to fasta file %s' % fasta_file_name)
with open(fasta_file_name, 'w') as f:
for cseq in table.ids(axis='observation'):
f.write('>%s\n%s\n' % (cseq, cseq))
logger.info('saved biom table sequences to fasta file %s' % fasta_file_name) | python | def fasta_from_biom(table, fasta_file_name):
'''Save sequences from a biom table to a fasta file
Parameters
----------
table : biom.Table
The biom table containing the sequences
fasta_file_name : str
Name of the fasta output file
'''
logger = logging.getLogger(__name__)
logger.debug('saving biom table sequences to fasta file %s' % fasta_file_name)
with open(fasta_file_name, 'w') as f:
for cseq in table.ids(axis='observation'):
f.write('>%s\n%s\n' % (cseq, cseq))
logger.info('saved biom table sequences to fasta file %s' % fasta_file_name) | [
"def",
"fasta_from_biom",
"(",
"table",
",",
"fasta_file_name",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'saving biom table sequences to fasta file %s'",
"%",
"fasta_file_name",
")",
"with",
"open",
... | Save sequences from a biom table to a fasta file
Parameters
----------
table : biom.Table
The biom table containing the sequences
fasta_file_name : str
Name of the fasta output file | [
"Save",
"sequences",
"from",
"a",
"biom",
"table",
"to",
"a",
"fasta",
"file"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L268-L284 | train | 51,563 |
biocore/deblur | deblur/workflow.py | remove_artifacts_from_biom_table | def remove_artifacts_from_biom_table(table_filename,
fasta_filename,
ref_fp,
biom_table_dir,
ref_db_fp,
threads=1,
verbose=False,
sim_thresh=None,
coverage_thresh=None):
"""Remove artifacts from a biom table using SortMeRNA
Parameters
----------
table : str
name of the biom table file
fasta_filename : str
the fasta file containing all the sequences of the biom table
Returns
-------
tmp_files : list of str
The temp files created during the artifact removal step
"""
logger = logging.getLogger(__name__)
logger.info('getting 16s sequences from the biom table')
# remove artifacts from the fasta file. output is in clean_fp fasta file
clean_fp, num_seqs_left, tmp_files = remove_artifacts_seqs(fasta_filename, ref_fp,
working_dir=biom_table_dir,
ref_db_fp=ref_db_fp,
negate=False, threads=threads,
verbose=verbose,
sim_thresh=sim_thresh,
coverage_thresh=coverage_thresh)
if clean_fp is None:
logger.warn("No clean sequences in %s" % fasta_filename)
return tmp_files
logger.debug('removed artifacts from sequences input %s'
' to output %s' % (fasta_filename, clean_fp))
# read the clean fasta file
good_seqs = {s for _, s in sequence_generator(clean_fp)}
logger.debug('loaded %d sequences from cleaned biom table'
' fasta file' % len(good_seqs))
logger.debug('loading biom table %s' % table_filename)
table = load_table(table_filename)
# filter and save the artifact biom table
artifact_table = table.filter(list(good_seqs),
axis='observation', inplace=False,
invert=True)
# remove the samples with 0 reads
filter_minreads_samples_from_table(artifact_table)
output_nomatch_fp = join(biom_table_dir, 'reference-non-hit.biom')
write_biom_table(artifact_table, output_nomatch_fp)
logger.info('wrote artifact only filtered biom table to %s'
% output_nomatch_fp)
# and save the reference-non-hit fasta file
output_nomatch_fasta_fp = join(biom_table_dir, 'reference-non-hit.seqs.fa')
fasta_from_biom(artifact_table, output_nomatch_fasta_fp)
# filter and save the only 16s biom table
table.filter(list(good_seqs), axis='observation')
# remove the samples with 0 reads
filter_minreads_samples_from_table(table)
output_fp = join(biom_table_dir, 'reference-hit.biom')
write_biom_table(table, output_fp)
logger.info('wrote 16s filtered biom table to %s' % output_fp)
# and save the reference-non-hit fasta file
output_match_fasta_fp = join(biom_table_dir, 'reference-hit.seqs.fa')
fasta_from_biom(table, output_match_fasta_fp)
# we also don't need the cleaned fasta file
tmp_files.append(clean_fp)
return tmp_files | python | def remove_artifacts_from_biom_table(table_filename,
fasta_filename,
ref_fp,
biom_table_dir,
ref_db_fp,
threads=1,
verbose=False,
sim_thresh=None,
coverage_thresh=None):
"""Remove artifacts from a biom table using SortMeRNA
Parameters
----------
table : str
name of the biom table file
fasta_filename : str
the fasta file containing all the sequences of the biom table
Returns
-------
tmp_files : list of str
The temp files created during the artifact removal step
"""
logger = logging.getLogger(__name__)
logger.info('getting 16s sequences from the biom table')
# remove artifacts from the fasta file. output is in clean_fp fasta file
clean_fp, num_seqs_left, tmp_files = remove_artifacts_seqs(fasta_filename, ref_fp,
working_dir=biom_table_dir,
ref_db_fp=ref_db_fp,
negate=False, threads=threads,
verbose=verbose,
sim_thresh=sim_thresh,
coverage_thresh=coverage_thresh)
if clean_fp is None:
logger.warn("No clean sequences in %s" % fasta_filename)
return tmp_files
logger.debug('removed artifacts from sequences input %s'
' to output %s' % (fasta_filename, clean_fp))
# read the clean fasta file
good_seqs = {s for _, s in sequence_generator(clean_fp)}
logger.debug('loaded %d sequences from cleaned biom table'
' fasta file' % len(good_seqs))
logger.debug('loading biom table %s' % table_filename)
table = load_table(table_filename)
# filter and save the artifact biom table
artifact_table = table.filter(list(good_seqs),
axis='observation', inplace=False,
invert=True)
# remove the samples with 0 reads
filter_minreads_samples_from_table(artifact_table)
output_nomatch_fp = join(biom_table_dir, 'reference-non-hit.biom')
write_biom_table(artifact_table, output_nomatch_fp)
logger.info('wrote artifact only filtered biom table to %s'
% output_nomatch_fp)
# and save the reference-non-hit fasta file
output_nomatch_fasta_fp = join(biom_table_dir, 'reference-non-hit.seqs.fa')
fasta_from_biom(artifact_table, output_nomatch_fasta_fp)
# filter and save the only 16s biom table
table.filter(list(good_seqs), axis='observation')
# remove the samples with 0 reads
filter_minreads_samples_from_table(table)
output_fp = join(biom_table_dir, 'reference-hit.biom')
write_biom_table(table, output_fp)
logger.info('wrote 16s filtered biom table to %s' % output_fp)
# and save the reference-non-hit fasta file
output_match_fasta_fp = join(biom_table_dir, 'reference-hit.seqs.fa')
fasta_from_biom(table, output_match_fasta_fp)
# we also don't need the cleaned fasta file
tmp_files.append(clean_fp)
return tmp_files | [
"def",
"remove_artifacts_from_biom_table",
"(",
"table_filename",
",",
"fasta_filename",
",",
"ref_fp",
",",
"biom_table_dir",
",",
"ref_db_fp",
",",
"threads",
"=",
"1",
",",
"verbose",
"=",
"False",
",",
"sim_thresh",
"=",
"None",
",",
"coverage_thresh",
"=",
... | Remove artifacts from a biom table using SortMeRNA
Parameters
----------
table : str
name of the biom table file
fasta_filename : str
the fasta file containing all the sequences of the biom table
Returns
-------
tmp_files : list of str
The temp files created during the artifact removal step | [
"Remove",
"artifacts",
"from",
"a",
"biom",
"table",
"using",
"SortMeRNA"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L287-L363 | train | 51,564 |
biocore/deblur | deblur/workflow.py | remove_artifacts_seqs | def remove_artifacts_seqs(seqs_fp,
ref_fp,
working_dir,
ref_db_fp,
negate=False,
threads=1,
verbose=False,
sim_thresh=None,
coverage_thresh=None):
"""Remove artifacts from FASTA file using SortMeRNA.
Parameters
----------
seqs_fp: string
file path to FASTA input sequence file
ref_fp: tuple
file path(s) to FASTA database file
working_dir: string
working directory path
ref_db_fp: tuple
file path(s) to indexed FASTA database
negate: boolean, optional
if True, discard all input sequences aligning
to reference database
threads: integer, optional
number of threads to use for SortMeRNA
verbose: boolean, optional
If true, output SortMeRNA errors
sim_thresh: float, optional
The minimal similarity threshold (between 0 and 1)
for keeping the sequence
if None, the default values used are 0.65 for negate=False,
0.95 for negate=True
coverage_thresh: float, optional
The minimal coverage threshold (between 0 and 1)
for alignments for keeping the sequence
if None, the default values used are 0.5 for negate=False,
0.95 for negate=True
Returns
-------
output_fp : str
Name of the artifact removed fasta file
okseqs : int
The number of sequences left after artifact removal
tmp_files : list of str
Names of the tmp files created
"""
logger = logging.getLogger(__name__)
logger.info('remove_artifacts_seqs file %s' % seqs_fp)
if stat(seqs_fp).st_size == 0:
logger.warn('file %s has size 0, continuing' % seqs_fp)
return None, 0, []
if coverage_thresh is None:
if negate:
coverage_thresh = 0.95 * 100
else:
coverage_thresh = 0.5 * 100
if sim_thresh is None:
if negate:
sim_thresh = 0.95 * 100
else:
sim_thresh = 0.65 * 100
# the minimal average bitscore per nucleotide
bitscore_thresh = 0.65
output_fp = join(working_dir,
"%s.no_artifacts" % basename(seqs_fp))
blast_output = join(working_dir,
'%s.sortmerna' % basename(seqs_fp))
aligned_seq_ids = set()
for i, db in enumerate(ref_fp):
logger.debug('running on ref_fp %s working dir %s refdb_fp %s seqs %s'
% (db, working_dir, ref_db_fp[i], seqs_fp))
# run SortMeRNA
# we use -e 100 to remove E-value based filtering by sortmerna
# since we use bitscore/identity/coverage filtering instead
params = ['sortmerna', '--reads', seqs_fp, '--ref', '%s,%s' %
(db, ref_db_fp[i]),
'--aligned', blast_output, '--blast', '3', '--best', '1',
'--print_all_reads', '-v', '-e', '100']
sout, serr, res = _system_call(params)
if not res == 0:
logger.error('sortmerna error on file %s' % seqs_fp)
logger.error('stdout : %s' % sout)
logger.error('stderr : %s' % serr)
return output_fp, 0, []
blast_output_filename = '%s.blast' % blast_output
with open(blast_output_filename, 'r') as bfl:
for line in bfl:
line = line.strip().split('\t')
# if * means no match
if line[1] == '*':
continue
# check if % identity[2] and coverage[13] are large enough
if (float(line[2]) >= sim_thresh) and \
(float(line[13]) >= coverage_thresh) and \
(float(line[11]) >= bitscore_thresh * len(line[0])):
aligned_seq_ids.add(line[0])
if negate:
def op(x): return x not in aligned_seq_ids
else:
def op(x): return x in aligned_seq_ids
# if negate = False, only output sequences
# matching to at least one of the databases
totalseqs = 0
okseqs = 0
badseqs = 0
with open(output_fp, 'w') as out_f:
for label, seq in sequence_generator(seqs_fp):
totalseqs += 1
label = label.split()[0]
if op(label):
out_f.write(">%s\n%s\n" % (label, seq))
okseqs += 1
else:
badseqs += 1
logger.info('total sequences %d, passing sequences %d, '
'failing sequences %d' % (totalseqs, okseqs, badseqs))
return output_fp, okseqs, [blast_output_filename] | python | def remove_artifacts_seqs(seqs_fp,
ref_fp,
working_dir,
ref_db_fp,
negate=False,
threads=1,
verbose=False,
sim_thresh=None,
coverage_thresh=None):
"""Remove artifacts from FASTA file using SortMeRNA.
Parameters
----------
seqs_fp: string
file path to FASTA input sequence file
ref_fp: tuple
file path(s) to FASTA database file
working_dir: string
working directory path
ref_db_fp: tuple
file path(s) to indexed FASTA database
negate: boolean, optional
if True, discard all input sequences aligning
to reference database
threads: integer, optional
number of threads to use for SortMeRNA
verbose: boolean, optional
If true, output SortMeRNA errors
sim_thresh: float, optional
The minimal similarity threshold (between 0 and 1)
for keeping the sequence
if None, the default values used are 0.65 for negate=False,
0.95 for negate=True
coverage_thresh: float, optional
The minimal coverage threshold (between 0 and 1)
for alignments for keeping the sequence
if None, the default values used are 0.5 for negate=False,
0.95 for negate=True
Returns
-------
output_fp : str
Name of the artifact removed fasta file
okseqs : int
The number of sequences left after artifact removal
tmp_files : list of str
Names of the tmp files created
"""
logger = logging.getLogger(__name__)
logger.info('remove_artifacts_seqs file %s' % seqs_fp)
if stat(seqs_fp).st_size == 0:
logger.warn('file %s has size 0, continuing' % seqs_fp)
return None, 0, []
if coverage_thresh is None:
if negate:
coverage_thresh = 0.95 * 100
else:
coverage_thresh = 0.5 * 100
if sim_thresh is None:
if negate:
sim_thresh = 0.95 * 100
else:
sim_thresh = 0.65 * 100
# the minimal average bitscore per nucleotide
bitscore_thresh = 0.65
output_fp = join(working_dir,
"%s.no_artifacts" % basename(seqs_fp))
blast_output = join(working_dir,
'%s.sortmerna' % basename(seqs_fp))
aligned_seq_ids = set()
for i, db in enumerate(ref_fp):
logger.debug('running on ref_fp %s working dir %s refdb_fp %s seqs %s'
% (db, working_dir, ref_db_fp[i], seqs_fp))
# run SortMeRNA
# we use -e 100 to remove E-value based filtering by sortmerna
# since we use bitscore/identity/coverage filtering instead
params = ['sortmerna', '--reads', seqs_fp, '--ref', '%s,%s' %
(db, ref_db_fp[i]),
'--aligned', blast_output, '--blast', '3', '--best', '1',
'--print_all_reads', '-v', '-e', '100']
sout, serr, res = _system_call(params)
if not res == 0:
logger.error('sortmerna error on file %s' % seqs_fp)
logger.error('stdout : %s' % sout)
logger.error('stderr : %s' % serr)
return output_fp, 0, []
blast_output_filename = '%s.blast' % blast_output
with open(blast_output_filename, 'r') as bfl:
for line in bfl:
line = line.strip().split('\t')
# if * means no match
if line[1] == '*':
continue
# check if % identity[2] and coverage[13] are large enough
if (float(line[2]) >= sim_thresh) and \
(float(line[13]) >= coverage_thresh) and \
(float(line[11]) >= bitscore_thresh * len(line[0])):
aligned_seq_ids.add(line[0])
if negate:
def op(x): return x not in aligned_seq_ids
else:
def op(x): return x in aligned_seq_ids
# if negate = False, only output sequences
# matching to at least one of the databases
totalseqs = 0
okseqs = 0
badseqs = 0
with open(output_fp, 'w') as out_f:
for label, seq in sequence_generator(seqs_fp):
totalseqs += 1
label = label.split()[0]
if op(label):
out_f.write(">%s\n%s\n" % (label, seq))
okseqs += 1
else:
badseqs += 1
logger.info('total sequences %d, passing sequences %d, '
'failing sequences %d' % (totalseqs, okseqs, badseqs))
return output_fp, okseqs, [blast_output_filename] | [
"def",
"remove_artifacts_seqs",
"(",
"seqs_fp",
",",
"ref_fp",
",",
"working_dir",
",",
"ref_db_fp",
",",
"negate",
"=",
"False",
",",
"threads",
"=",
"1",
",",
"verbose",
"=",
"False",
",",
"sim_thresh",
"=",
"None",
",",
"coverage_thresh",
"=",
"None",
"... | Remove artifacts from FASTA file using SortMeRNA.
Parameters
----------
seqs_fp: string
file path to FASTA input sequence file
ref_fp: tuple
file path(s) to FASTA database file
working_dir: string
working directory path
ref_db_fp: tuple
file path(s) to indexed FASTA database
negate: boolean, optional
if True, discard all input sequences aligning
to reference database
threads: integer, optional
number of threads to use for SortMeRNA
verbose: boolean, optional
If true, output SortMeRNA errors
sim_thresh: float, optional
The minimal similarity threshold (between 0 and 1)
for keeping the sequence
if None, the default values used are 0.65 for negate=False,
0.95 for negate=True
coverage_thresh: float, optional
The minimal coverage threshold (between 0 and 1)
for alignments for keeping the sequence
if None, the default values used are 0.5 for negate=False,
0.95 for negate=True
Returns
-------
output_fp : str
Name of the artifact removed fasta file
okseqs : int
The number of sequences left after artifact removal
tmp_files : list of str
Names of the tmp files created | [
"Remove",
"artifacts",
"from",
"FASTA",
"file",
"using",
"SortMeRNA",
"."
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L366-L493 | train | 51,565 |
biocore/deblur | deblur/workflow.py | multiple_sequence_alignment | def multiple_sequence_alignment(seqs_fp, threads=1):
"""Perform multiple sequence alignment on FASTA file using MAFFT.
Parameters
----------
seqs_fp: string
filepath to FASTA file for multiple sequence alignment
threads: integer, optional
number of threads to use. 0 to use all threads
Returns
-------
msa_fp : str
name of output alignment file or None if error encountered
"""
logger = logging.getLogger(__name__)
logger.info('multiple_sequence_alignment seqs file %s' % seqs_fp)
# for mafft we use -1 to denote all threads and not 0
if threads == 0:
threads = -1
if stat(seqs_fp).st_size == 0:
logger.warning('msa failed. file %s has no reads' % seqs_fp)
return None
msa_fp = seqs_fp + '.msa'
params = ['mafft', '--quiet', '--preservecase', '--parttree', '--auto',
'--thread', str(threads), seqs_fp]
sout, serr, res = _system_call(params, stdoutfilename=msa_fp)
if not res == 0:
logger.info('msa failed for file %s (maybe only 1 read?)' % seqs_fp)
logger.debug('stderr : %s' % serr)
return None
return msa_fp | python | def multiple_sequence_alignment(seqs_fp, threads=1):
"""Perform multiple sequence alignment on FASTA file using MAFFT.
Parameters
----------
seqs_fp: string
filepath to FASTA file for multiple sequence alignment
threads: integer, optional
number of threads to use. 0 to use all threads
Returns
-------
msa_fp : str
name of output alignment file or None if error encountered
"""
logger = logging.getLogger(__name__)
logger.info('multiple_sequence_alignment seqs file %s' % seqs_fp)
# for mafft we use -1 to denote all threads and not 0
if threads == 0:
threads = -1
if stat(seqs_fp).st_size == 0:
logger.warning('msa failed. file %s has no reads' % seqs_fp)
return None
msa_fp = seqs_fp + '.msa'
params = ['mafft', '--quiet', '--preservecase', '--parttree', '--auto',
'--thread', str(threads), seqs_fp]
sout, serr, res = _system_call(params, stdoutfilename=msa_fp)
if not res == 0:
logger.info('msa failed for file %s (maybe only 1 read?)' % seqs_fp)
logger.debug('stderr : %s' % serr)
return None
return msa_fp | [
"def",
"multiple_sequence_alignment",
"(",
"seqs_fp",
",",
"threads",
"=",
"1",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"info",
"(",
"'multiple_sequence_alignment seqs file %s'",
"%",
"seqs_fp",
")",
"# for mafft ... | Perform multiple sequence alignment on FASTA file using MAFFT.
Parameters
----------
seqs_fp: string
filepath to FASTA file for multiple sequence alignment
threads: integer, optional
number of threads to use. 0 to use all threads
Returns
-------
msa_fp : str
name of output alignment file or None if error encountered | [
"Perform",
"multiple",
"sequence",
"alignment",
"on",
"FASTA",
"file",
"using",
"MAFFT",
"."
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L496-L529 | train | 51,566 |
biocore/deblur | deblur/workflow.py | split_sequence_file_on_sample_ids_to_files | def split_sequence_file_on_sample_ids_to_files(seqs,
outdir):
"""Split FASTA file on sample IDs.
Parameters
----------
seqs: file handler
file handler to demultiplexed FASTA file
outdir: string
dirpath to output split FASTA files
"""
logger = logging.getLogger(__name__)
logger.info('split_sequence_file_on_sample_ids_to_files'
' for file %s into dir %s' % (seqs, outdir))
outputs = {}
for bits in sequence_generator(seqs):
sample = sample_id_from_read_id(bits[0])
if sample not in outputs:
outputs[sample] = open(join(outdir, sample + '.fasta'), 'w')
outputs[sample].write(">%s\n%s\n" % (bits[0], bits[1]))
for sample in outputs:
outputs[sample].close()
logger.info('split to %d files' % len(outputs)) | python | def split_sequence_file_on_sample_ids_to_files(seqs,
outdir):
"""Split FASTA file on sample IDs.
Parameters
----------
seqs: file handler
file handler to demultiplexed FASTA file
outdir: string
dirpath to output split FASTA files
"""
logger = logging.getLogger(__name__)
logger.info('split_sequence_file_on_sample_ids_to_files'
' for file %s into dir %s' % (seqs, outdir))
outputs = {}
for bits in sequence_generator(seqs):
sample = sample_id_from_read_id(bits[0])
if sample not in outputs:
outputs[sample] = open(join(outdir, sample + '.fasta'), 'w')
outputs[sample].write(">%s\n%s\n" % (bits[0], bits[1]))
for sample in outputs:
outputs[sample].close()
logger.info('split to %d files' % len(outputs)) | [
"def",
"split_sequence_file_on_sample_ids_to_files",
"(",
"seqs",
",",
"outdir",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"info",
"(",
"'split_sequence_file_on_sample_ids_to_files'",
"' for file %s into dir %s'",
"%",
"(... | Split FASTA file on sample IDs.
Parameters
----------
seqs: file handler
file handler to demultiplexed FASTA file
outdir: string
dirpath to output split FASTA files | [
"Split",
"FASTA",
"file",
"on",
"sample",
"IDs",
"."
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L596-L621 | train | 51,567 |
biocore/deblur | deblur/workflow.py | write_biom_table | def write_biom_table(table, biom_fp):
"""Write BIOM table to file.
Parameters
----------
table: biom.table
an instance of a BIOM table
biom_fp: string
filepath to output BIOM table
"""
logger = logging.getLogger(__name__)
logger.debug('write_biom_table to file %s' % biom_fp)
with biom_open(biom_fp, 'w') as f:
table.to_hdf5(h5grp=f, generated_by="deblur")
logger.debug('wrote to BIOM file %s' % biom_fp) | python | def write_biom_table(table, biom_fp):
"""Write BIOM table to file.
Parameters
----------
table: biom.table
an instance of a BIOM table
biom_fp: string
filepath to output BIOM table
"""
logger = logging.getLogger(__name__)
logger.debug('write_biom_table to file %s' % biom_fp)
with biom_open(biom_fp, 'w') as f:
table.to_hdf5(h5grp=f, generated_by="deblur")
logger.debug('wrote to BIOM file %s' % biom_fp) | [
"def",
"write_biom_table",
"(",
"table",
",",
"biom_fp",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'write_biom_table to file %s'",
"%",
"biom_fp",
")",
"with",
"biom_open",
"(",
"biom_fp",
",",
... | Write BIOM table to file.
Parameters
----------
table: biom.table
an instance of a BIOM table
biom_fp: string
filepath to output BIOM table | [
"Write",
"BIOM",
"table",
"to",
"file",
"."
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L624-L638 | train | 51,568 |
biocore/deblur | deblur/workflow.py | get_files_for_table | def get_files_for_table(input_dir,
file_end='.trim.derep.no_artifacts'
'.msa.deblur.no_chimeras'):
"""Get a list of files to add to the output table
Parameters:
-----------
input_dir : string
name of the directory containing the deblurred fasta files
file_end : string
the ending of all the fasta files to be added to the table
(default '.fasta.trim.derep.no_artifacts.msa.deblur.no_chimeras')
Returns
-------
names : list of tuples of (string,string)
list of tuples of:
name of fasta files to be added to the biom table
sampleid (file names without the file_end and path)
"""
logger = logging.getLogger(__name__)
logger.debug('get_files_for_table input dir %s, '
'file-ending %s' % (input_dir, file_end))
names = []
for cfile in glob(join(input_dir, "*%s" % file_end)):
if not isfile(cfile):
continue
sample_id = basename(cfile)[:-len(file_end)]
sample_id = os.path.splitext(sample_id)[0]
names.append((cfile, sample_id))
logger.debug('found %d files' % len(names))
return names | python | def get_files_for_table(input_dir,
file_end='.trim.derep.no_artifacts'
'.msa.deblur.no_chimeras'):
"""Get a list of files to add to the output table
Parameters:
-----------
input_dir : string
name of the directory containing the deblurred fasta files
file_end : string
the ending of all the fasta files to be added to the table
(default '.fasta.trim.derep.no_artifacts.msa.deblur.no_chimeras')
Returns
-------
names : list of tuples of (string,string)
list of tuples of:
name of fasta files to be added to the biom table
sampleid (file names without the file_end and path)
"""
logger = logging.getLogger(__name__)
logger.debug('get_files_for_table input dir %s, '
'file-ending %s' % (input_dir, file_end))
names = []
for cfile in glob(join(input_dir, "*%s" % file_end)):
if not isfile(cfile):
continue
sample_id = basename(cfile)[:-len(file_end)]
sample_id = os.path.splitext(sample_id)[0]
names.append((cfile, sample_id))
logger.debug('found %d files' % len(names))
return names | [
"def",
"get_files_for_table",
"(",
"input_dir",
",",
"file_end",
"=",
"'.trim.derep.no_artifacts'",
"'.msa.deblur.no_chimeras'",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'get_files_for_table input dir %s, ... | Get a list of files to add to the output table
Parameters:
-----------
input_dir : string
name of the directory containing the deblurred fasta files
file_end : string
the ending of all the fasta files to be added to the table
(default '.fasta.trim.derep.no_artifacts.msa.deblur.no_chimeras')
Returns
-------
names : list of tuples of (string,string)
list of tuples of:
name of fasta files to be added to the biom table
sampleid (file names without the file_end and path) | [
"Get",
"a",
"list",
"of",
"files",
"to",
"add",
"to",
"the",
"output",
"table"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L641-L673 | train | 51,569 |
biocore/deblur | deblur/workflow.py | launch_workflow | def launch_workflow(seqs_fp, working_dir, mean_error, error_dist,
indel_prob, indel_max, trim_length, left_trim_length,
min_size, ref_fp, ref_db_fp, threads_per_sample=1,
sim_thresh=None, coverage_thresh=None):
"""Launch full deblur workflow for a single post split-libraries fasta file
Parameters
----------
seqs_fp: string
a post split library fasta file for debluring
working_dir: string
working directory path
mean_error: float
mean error for original sequence estimate
error_dist: list
list of error probabilities for each hamming distance
indel_prob: float
insertion/deletion (indel) probability
indel_max: integer
maximal indel number
trim_length: integer
sequence trim length
left_trim_length: integer
trim the first n reads
min_size: integer
upper limit on sequence abundance (discard sequences below limit)
ref_fp: tuple
filepath(s) to FASTA reference database for artifact removal
ref_db_fp: tuple
filepath(s) to SortMeRNA indexed database for artifact removal
threads_per_sample: integer, optional
number of threads to use for SortMeRNA/mafft/vsearch
(0 for max available)
sim_thresh: float, optional
the minimal similarity for a sequence to the database.
if None, take the defaults (0.65 for negate=False,
0.95 for negate=True)
coverage_thresh: float, optional
the minimal coverage for alignment of a sequence to the database.
if None, take the defaults (0.3 for negate=False, 0.95 for negate=True)
Return
------
output_no_chimers_fp : string
filepath to fasta file with no chimeras of None if error encountered
"""
logger = logging.getLogger(__name__)
logger.info('--------------------------------------------------------')
logger.info('launch_workflow for file %s' % seqs_fp)
# Step 1: Trim sequences to specified length
output_trim_fp = join(working_dir, "%s.trim" % basename(seqs_fp))
with open(output_trim_fp, 'w') as out_f:
for label, seq in trim_seqs(
input_seqs=sequence_generator(seqs_fp),
trim_len=trim_length,
left_trim_len=left_trim_length):
out_f.write(">%s\n%s\n" % (label, seq))
# Step 2: Dereplicate sequences
output_derep_fp = join(working_dir,
"%s.derep" % basename(output_trim_fp))
dereplicate_seqs(seqs_fp=output_trim_fp,
output_fp=output_derep_fp,
min_size=min_size, threads=threads_per_sample)
# Step 3: Remove artifacts
output_artif_fp, num_seqs_left, _ = remove_artifacts_seqs(seqs_fp=output_derep_fp,
ref_fp=ref_fp,
working_dir=working_dir,
ref_db_fp=ref_db_fp,
negate=True,
threads=threads_per_sample,
sim_thresh=sim_thresh)
if not output_artif_fp:
warnings.warn('Problem removing artifacts from file %s' %
seqs_fp, UserWarning)
logger.warning('remove artifacts failed, aborting')
return None
# Step 4: Multiple sequence alignment
if num_seqs_left > 1:
output_msa_fp = join(working_dir,
"%s.msa" % basename(output_artif_fp))
alignment = multiple_sequence_alignment(seqs_fp=output_artif_fp,
threads=threads_per_sample)
if not alignment:
warnings.warn('Problem performing multiple sequence alignment '
'on file %s' % seqs_fp, UserWarning)
logger.warning('msa failed. aborting')
return None
elif num_seqs_left == 1:
# only one sequence after remove artifacts (but could be many reads)
# no need to run MSA - just use the pre-msa file as input for next step
output_msa_fp = output_artif_fp
else:
err_msg = ('No sequences left after artifact removal in '
'file %s' % seqs_fp)
warnings.warn(err_msg, UserWarning)
logger.warning(err_msg)
return None
# Step 5: Launch deblur
output_deblur_fp = join(working_dir,
"%s.deblur" % basename(output_msa_fp))
with open(output_deblur_fp, 'w') as f:
seqs = deblur(sequence_generator(output_msa_fp), mean_error,
error_dist, indel_prob, indel_max)
if seqs is None:
warnings.warn('multiple sequence alignment file %s contains '
'no sequences' % output_msa_fp, UserWarning)
logger.warn('no sequences returned from deblur for file %s' %
output_msa_fp)
return None
for s in seqs:
# remove '-' from aligned sequences
s.sequence = s.sequence.replace('-', '')
f.write(s.to_fasta())
# Step 6: Chimera removal
output_no_chimeras_fp = remove_chimeras_denovo_from_seqs(
output_deblur_fp, working_dir, threads=threads_per_sample)
logger.info('finished processing file')
return output_no_chimeras_fp | python | def launch_workflow(seqs_fp, working_dir, mean_error, error_dist,
indel_prob, indel_max, trim_length, left_trim_length,
min_size, ref_fp, ref_db_fp, threads_per_sample=1,
sim_thresh=None, coverage_thresh=None):
"""Launch full deblur workflow for a single post split-libraries fasta file
Parameters
----------
seqs_fp: string
a post split library fasta file for debluring
working_dir: string
working directory path
mean_error: float
mean error for original sequence estimate
error_dist: list
list of error probabilities for each hamming distance
indel_prob: float
insertion/deletion (indel) probability
indel_max: integer
maximal indel number
trim_length: integer
sequence trim length
left_trim_length: integer
trim the first n reads
min_size: integer
upper limit on sequence abundance (discard sequences below limit)
ref_fp: tuple
filepath(s) to FASTA reference database for artifact removal
ref_db_fp: tuple
filepath(s) to SortMeRNA indexed database for artifact removal
threads_per_sample: integer, optional
number of threads to use for SortMeRNA/mafft/vsearch
(0 for max available)
sim_thresh: float, optional
the minimal similarity for a sequence to the database.
if None, take the defaults (0.65 for negate=False,
0.95 for negate=True)
coverage_thresh: float, optional
the minimal coverage for alignment of a sequence to the database.
if None, take the defaults (0.3 for negate=False, 0.95 for negate=True)
Return
------
output_no_chimers_fp : string
filepath to fasta file with no chimeras of None if error encountered
"""
logger = logging.getLogger(__name__)
logger.info('--------------------------------------------------------')
logger.info('launch_workflow for file %s' % seqs_fp)
# Step 1: Trim sequences to specified length
output_trim_fp = join(working_dir, "%s.trim" % basename(seqs_fp))
with open(output_trim_fp, 'w') as out_f:
for label, seq in trim_seqs(
input_seqs=sequence_generator(seqs_fp),
trim_len=trim_length,
left_trim_len=left_trim_length):
out_f.write(">%s\n%s\n" % (label, seq))
# Step 2: Dereplicate sequences
output_derep_fp = join(working_dir,
"%s.derep" % basename(output_trim_fp))
dereplicate_seqs(seqs_fp=output_trim_fp,
output_fp=output_derep_fp,
min_size=min_size, threads=threads_per_sample)
# Step 3: Remove artifacts
output_artif_fp, num_seqs_left, _ = remove_artifacts_seqs(seqs_fp=output_derep_fp,
ref_fp=ref_fp,
working_dir=working_dir,
ref_db_fp=ref_db_fp,
negate=True,
threads=threads_per_sample,
sim_thresh=sim_thresh)
if not output_artif_fp:
warnings.warn('Problem removing artifacts from file %s' %
seqs_fp, UserWarning)
logger.warning('remove artifacts failed, aborting')
return None
# Step 4: Multiple sequence alignment
if num_seqs_left > 1:
output_msa_fp = join(working_dir,
"%s.msa" % basename(output_artif_fp))
alignment = multiple_sequence_alignment(seqs_fp=output_artif_fp,
threads=threads_per_sample)
if not alignment:
warnings.warn('Problem performing multiple sequence alignment '
'on file %s' % seqs_fp, UserWarning)
logger.warning('msa failed. aborting')
return None
elif num_seqs_left == 1:
# only one sequence after remove artifacts (but could be many reads)
# no need to run MSA - just use the pre-msa file as input for next step
output_msa_fp = output_artif_fp
else:
err_msg = ('No sequences left after artifact removal in '
'file %s' % seqs_fp)
warnings.warn(err_msg, UserWarning)
logger.warning(err_msg)
return None
# Step 5: Launch deblur
output_deblur_fp = join(working_dir,
"%s.deblur" % basename(output_msa_fp))
with open(output_deblur_fp, 'w') as f:
seqs = deblur(sequence_generator(output_msa_fp), mean_error,
error_dist, indel_prob, indel_max)
if seqs is None:
warnings.warn('multiple sequence alignment file %s contains '
'no sequences' % output_msa_fp, UserWarning)
logger.warn('no sequences returned from deblur for file %s' %
output_msa_fp)
return None
for s in seqs:
# remove '-' from aligned sequences
s.sequence = s.sequence.replace('-', '')
f.write(s.to_fasta())
# Step 6: Chimera removal
output_no_chimeras_fp = remove_chimeras_denovo_from_seqs(
output_deblur_fp, working_dir, threads=threads_per_sample)
logger.info('finished processing file')
return output_no_chimeras_fp | [
"def",
"launch_workflow",
"(",
"seqs_fp",
",",
"working_dir",
",",
"mean_error",
",",
"error_dist",
",",
"indel_prob",
",",
"indel_max",
",",
"trim_length",
",",
"left_trim_length",
",",
"min_size",
",",
"ref_fp",
",",
"ref_db_fp",
",",
"threads_per_sample",
"=",
... | Launch full deblur workflow for a single post split-libraries fasta file
Parameters
----------
seqs_fp: string
a post split library fasta file for debluring
working_dir: string
working directory path
mean_error: float
mean error for original sequence estimate
error_dist: list
list of error probabilities for each hamming distance
indel_prob: float
insertion/deletion (indel) probability
indel_max: integer
maximal indel number
trim_length: integer
sequence trim length
left_trim_length: integer
trim the first n reads
min_size: integer
upper limit on sequence abundance (discard sequences below limit)
ref_fp: tuple
filepath(s) to FASTA reference database for artifact removal
ref_db_fp: tuple
filepath(s) to SortMeRNA indexed database for artifact removal
threads_per_sample: integer, optional
number of threads to use for SortMeRNA/mafft/vsearch
(0 for max available)
sim_thresh: float, optional
the minimal similarity for a sequence to the database.
if None, take the defaults (0.65 for negate=False,
0.95 for negate=True)
coverage_thresh: float, optional
the minimal coverage for alignment of a sequence to the database.
if None, take the defaults (0.3 for negate=False, 0.95 for negate=True)
Return
------
output_no_chimers_fp : string
filepath to fasta file with no chimeras of None if error encountered | [
"Launch",
"full",
"deblur",
"workflow",
"for",
"a",
"single",
"post",
"split",
"-",
"libraries",
"fasta",
"file"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L777-L895 | train | 51,570 |
biocore/deblur | deblur/workflow.py | start_log | def start_log(level=logging.DEBUG, filename=None):
"""start the logger for the run
Parameters
----------
level : int, optional
logging.DEBUG, logging.INFO etc. for the log level (between 0-50).
filename : str, optional
name of the filename to save the log to or
None (default) to use deblur.log.TIMESTAMP
"""
if filename is None:
tstr = time.ctime()
tstr = tstr.replace(' ', '.')
tstr = tstr.replace(':', '.')
filename = 'deblur.log.%s' % tstr
logging.basicConfig(filename=filename, level=level,
format='%(levelname)s(%(thread)d)'
'%(asctime)s:%(message)s')
logger = logging.getLogger(__name__)
logger.info('*************************')
logger.info('deblurring started') | python | def start_log(level=logging.DEBUG, filename=None):
"""start the logger for the run
Parameters
----------
level : int, optional
logging.DEBUG, logging.INFO etc. for the log level (between 0-50).
filename : str, optional
name of the filename to save the log to or
None (default) to use deblur.log.TIMESTAMP
"""
if filename is None:
tstr = time.ctime()
tstr = tstr.replace(' ', '.')
tstr = tstr.replace(':', '.')
filename = 'deblur.log.%s' % tstr
logging.basicConfig(filename=filename, level=level,
format='%(levelname)s(%(thread)d)'
'%(asctime)s:%(message)s')
logger = logging.getLogger(__name__)
logger.info('*************************')
logger.info('deblurring started') | [
"def",
"start_log",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"tstr",
"=",
"time",
".",
"ctime",
"(",
")",
"tstr",
"=",
"tstr",
".",
"replace",
"(",
"' '",
",",
"'.'",
... | start the logger for the run
Parameters
----------
level : int, optional
logging.DEBUG, logging.INFO etc. for the log level (between 0-50).
filename : str, optional
name of the filename to save the log to or
None (default) to use deblur.log.TIMESTAMP | [
"start",
"the",
"logger",
"for",
"the",
"run"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L898-L919 | train | 51,571 |
biocore/deblur | deblur/deblurring.py | get_sequences | def get_sequences(input_seqs):
"""Returns a list of Sequences
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format
Returns
-------
list of Sequence
Raises
------
ValueError
If no sequences where found in `input_seqs`
If all the sequences do not have the same length either aligned or
unaligned.
"""
try:
seqs = [Sequence(id, seq) for id, seq in input_seqs]
except Exception:
seqs = []
if len(seqs) == 0:
logger = logging.getLogger(__name__)
logger.warn('No sequences found in fasta file!')
return None
# Check that all the sequence lengths (aligned and unaligned are the same)
aligned_lengths = set(s.length for s in seqs)
unaligned_lengths = set(s.unaligned_length for s in seqs)
if len(aligned_lengths) != 1 or len(unaligned_lengths) != 1:
raise ValueError(
"Not all sequence have the same length. Aligned lengths: %s, "
"sequence lengths: %s"
% (", ".join(map(str, aligned_lengths)),
", ".join(map(str, unaligned_lengths))))
seqs = sorted(seqs, key=attrgetter('frequency'), reverse=True)
return seqs | python | def get_sequences(input_seqs):
"""Returns a list of Sequences
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format
Returns
-------
list of Sequence
Raises
------
ValueError
If no sequences where found in `input_seqs`
If all the sequences do not have the same length either aligned or
unaligned.
"""
try:
seqs = [Sequence(id, seq) for id, seq in input_seqs]
except Exception:
seqs = []
if len(seqs) == 0:
logger = logging.getLogger(__name__)
logger.warn('No sequences found in fasta file!')
return None
# Check that all the sequence lengths (aligned and unaligned are the same)
aligned_lengths = set(s.length for s in seqs)
unaligned_lengths = set(s.unaligned_length for s in seqs)
if len(aligned_lengths) != 1 or len(unaligned_lengths) != 1:
raise ValueError(
"Not all sequence have the same length. Aligned lengths: %s, "
"sequence lengths: %s"
% (", ".join(map(str, aligned_lengths)),
", ".join(map(str, unaligned_lengths))))
seqs = sorted(seqs, key=attrgetter('frequency'), reverse=True)
return seqs | [
"def",
"get_sequences",
"(",
"input_seqs",
")",
":",
"try",
":",
"seqs",
"=",
"[",
"Sequence",
"(",
"id",
",",
"seq",
")",
"for",
"id",
",",
"seq",
"in",
"input_seqs",
"]",
"except",
"Exception",
":",
"seqs",
"=",
"[",
"]",
"if",
"len",
"(",
"seqs"... | Returns a list of Sequences
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format
Returns
-------
list of Sequence
Raises
------
ValueError
If no sequences where found in `input_seqs`
If all the sequences do not have the same length either aligned or
unaligned. | [
"Returns",
"a",
"list",
"of",
"Sequences"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/deblurring.py#L27-L68 | train | 51,572 |
biocore/deblur | deblur/deblurring.py | deblur | def deblur(input_seqs, mean_error=0.005,
error_dist=None,
indel_prob=0.01, indel_max=3):
"""Deblur the reads
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format. The label
should include the sequence count in the 'size=X' format.
mean_error : float, optional
The mean illumina error, used for original sequence estimate.
Default: 0.005
error_dist : list of float, optional
A list of error probabilities. The length of the list determines the
amount of hamming distances taken into account. Default: None, use
the default error profile (from get_default_error_profile() )
indel_prob : float, optional
Indel probability (same for N indels). Default: 0.01
indel_max : int, optional
The maximal number of indels expected by errors. Default: 3
Results
-------
list of Sequence
The deblurred sequences
Notes
-----
mean_error is used only for normalizing the peak height before deblurring.
The array 'error_dist' represents the error distribution, where
Xi = max frequency of error hamming. The length of this array - 1 limits
the hamming distance taken into account, i.e. if the length if `error_dist`
is 10, sequences up to 10 - 1 = 9 hamming distance will be taken into
account
"""
logger = logging.getLogger(__name__)
if error_dist is None:
error_dist = get_default_error_profile()
logger.debug('Using error profile %s' % error_dist)
# Get the sequences
seqs = get_sequences(input_seqs)
if seqs is None:
logger.warn('no sequences deblurred')
return None
logger.info('deblurring %d sequences' % len(seqs))
# fix the original frequencies of each read error using the
# mean error profile
mod_factor = pow((1 - mean_error), seqs[0].unaligned_length)
error_dist = np.array(error_dist) / mod_factor
max_h_dist = len(error_dist) - 1
for seq_i in seqs:
# no need to remove neighbors if freq. is <=0
if seq_i.frequency <= 0:
continue
# Correct for the fact that many reads are expected to be mutated
num_err = error_dist * seq_i.frequency
# if it's low level, just continue
if num_err[1] < 0.1:
continue
# Compare to all other sequences and calculate hamming dist
seq_i_len = len(seq_i.sequence.rstrip('-'))
for seq_j in seqs:
# Ignore current sequence
if seq_i == seq_j:
continue
# Calculate the hamming distance
h_dist = np.count_nonzero(np.not_equal(seq_i.np_sequence,
seq_j.np_sequence))
# If far away, don't need to correct
if h_dist > max_h_dist:
continue
# Close, so lets calculate exact distance
# We stop checking in the shortest sequence after removing trailing
# indels. We need to do this in order to avoid double counting
# the insertions/deletions
length = min(seq_i_len, len(seq_j.sequence.rstrip('-')))
sub_seq_i = seq_i.np_sequence[:length]
sub_seq_j = seq_j.np_sequence[:length]
mask = (sub_seq_i != sub_seq_j)
# find all indels
mut_is_indel = np.logical_or(sub_seq_i[mask] == 4,
sub_seq_j[mask] == 4)
num_indels = mut_is_indel.sum()
if num_indels > 0:
# need to account for indel in one sequence not solved in the other
# (so we have '-' at the end. Need to ignore it in the total count)
h_dist = np.count_nonzero(np.not_equal(seq_i.np_sequence[:length],
seq_j.np_sequence[:length]))
num_substitutions = h_dist - num_indels
correction_value = num_err[num_substitutions]
if num_indels > indel_max:
correction_value = 0
elif num_indels > 0:
# remove errors due to (PCR?) indels (saw in 22 mock mixture)
correction_value = correction_value * indel_prob
# met all the criteria - so correct the frequency of the neighbor
seq_j.frequency -= correction_value
result = [s for s in seqs if round(s.frequency) > 0]
logger.info('%d unique sequences left following deblurring' % len(result))
return result | python | def deblur(input_seqs, mean_error=0.005,
error_dist=None,
indel_prob=0.01, indel_max=3):
"""Deblur the reads
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format. The label
should include the sequence count in the 'size=X' format.
mean_error : float, optional
The mean illumina error, used for original sequence estimate.
Default: 0.005
error_dist : list of float, optional
A list of error probabilities. The length of the list determines the
amount of hamming distances taken into account. Default: None, use
the default error profile (from get_default_error_profile() )
indel_prob : float, optional
Indel probability (same for N indels). Default: 0.01
indel_max : int, optional
The maximal number of indels expected by errors. Default: 3
Results
-------
list of Sequence
The deblurred sequences
Notes
-----
mean_error is used only for normalizing the peak height before deblurring.
The array 'error_dist' represents the error distribution, where
Xi = max frequency of error hamming. The length of this array - 1 limits
the hamming distance taken into account, i.e. if the length if `error_dist`
is 10, sequences up to 10 - 1 = 9 hamming distance will be taken into
account
"""
logger = logging.getLogger(__name__)
if error_dist is None:
error_dist = get_default_error_profile()
logger.debug('Using error profile %s' % error_dist)
# Get the sequences
seqs = get_sequences(input_seqs)
if seqs is None:
logger.warn('no sequences deblurred')
return None
logger.info('deblurring %d sequences' % len(seqs))
# fix the original frequencies of each read error using the
# mean error profile
mod_factor = pow((1 - mean_error), seqs[0].unaligned_length)
error_dist = np.array(error_dist) / mod_factor
max_h_dist = len(error_dist) - 1
for seq_i in seqs:
# no need to remove neighbors if freq. is <=0
if seq_i.frequency <= 0:
continue
# Correct for the fact that many reads are expected to be mutated
num_err = error_dist * seq_i.frequency
# if it's low level, just continue
if num_err[1] < 0.1:
continue
# Compare to all other sequences and calculate hamming dist
seq_i_len = len(seq_i.sequence.rstrip('-'))
for seq_j in seqs:
# Ignore current sequence
if seq_i == seq_j:
continue
# Calculate the hamming distance
h_dist = np.count_nonzero(np.not_equal(seq_i.np_sequence,
seq_j.np_sequence))
# If far away, don't need to correct
if h_dist > max_h_dist:
continue
# Close, so lets calculate exact distance
# We stop checking in the shortest sequence after removing trailing
# indels. We need to do this in order to avoid double counting
# the insertions/deletions
length = min(seq_i_len, len(seq_j.sequence.rstrip('-')))
sub_seq_i = seq_i.np_sequence[:length]
sub_seq_j = seq_j.np_sequence[:length]
mask = (sub_seq_i != sub_seq_j)
# find all indels
mut_is_indel = np.logical_or(sub_seq_i[mask] == 4,
sub_seq_j[mask] == 4)
num_indels = mut_is_indel.sum()
if num_indels > 0:
# need to account for indel in one sequence not solved in the other
# (so we have '-' at the end. Need to ignore it in the total count)
h_dist = np.count_nonzero(np.not_equal(seq_i.np_sequence[:length],
seq_j.np_sequence[:length]))
num_substitutions = h_dist - num_indels
correction_value = num_err[num_substitutions]
if num_indels > indel_max:
correction_value = 0
elif num_indels > 0:
# remove errors due to (PCR?) indels (saw in 22 mock mixture)
correction_value = correction_value * indel_prob
# met all the criteria - so correct the frequency of the neighbor
seq_j.frequency -= correction_value
result = [s for s in seqs if round(s.frequency) > 0]
logger.info('%d unique sequences left following deblurring' % len(result))
return result | [
"def",
"deblur",
"(",
"input_seqs",
",",
"mean_error",
"=",
"0.005",
",",
"error_dist",
"=",
"None",
",",
"indel_prob",
"=",
"0.01",
",",
"indel_max",
"=",
"3",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"error_dist... | Deblur the reads
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format. The label
should include the sequence count in the 'size=X' format.
mean_error : float, optional
The mean illumina error, used for original sequence estimate.
Default: 0.005
error_dist : list of float, optional
A list of error probabilities. The length of the list determines the
amount of hamming distances taken into account. Default: None, use
the default error profile (from get_default_error_profile() )
indel_prob : float, optional
Indel probability (same for N indels). Default: 0.01
indel_max : int, optional
The maximal number of indels expected by errors. Default: 3
Results
-------
list of Sequence
The deblurred sequences
Notes
-----
mean_error is used only for normalizing the peak height before deblurring.
The array 'error_dist' represents the error distribution, where
Xi = max frequency of error hamming. The length of this array - 1 limits
the hamming distance taken into account, i.e. if the length if `error_dist`
is 10, sequences up to 10 - 1 = 9 hamming distance will be taken into
account | [
"Deblur",
"the",
"reads"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/deblurring.py#L71-L189 | train | 51,573 |
biocore/deblur | deblur/sequence.py | Sequence.to_fasta | def to_fasta(self):
"""Returns a string with the sequence in fasta format
Returns
-------
str
The FASTA representation of the sequence
"""
prefix, suffix = re.split('(?<=size=)\w+', self.label, maxsplit=1)
new_count = int(round(self.frequency))
new_label = "%s%d%s" % (prefix, new_count, suffix)
return ">%s\n%s\n" % (new_label, self.sequence) | python | def to_fasta(self):
"""Returns a string with the sequence in fasta format
Returns
-------
str
The FASTA representation of the sequence
"""
prefix, suffix = re.split('(?<=size=)\w+', self.label, maxsplit=1)
new_count = int(round(self.frequency))
new_label = "%s%d%s" % (prefix, new_count, suffix)
return ">%s\n%s\n" % (new_label, self.sequence) | [
"def",
"to_fasta",
"(",
"self",
")",
":",
"prefix",
",",
"suffix",
"=",
"re",
".",
"split",
"(",
"'(?<=size=)\\w+'",
",",
"self",
".",
"label",
",",
"maxsplit",
"=",
"1",
")",
"new_count",
"=",
"int",
"(",
"round",
"(",
"self",
".",
"frequency",
")",... | Returns a string with the sequence in fasta format
Returns
-------
str
The FASTA representation of the sequence | [
"Returns",
"a",
"string",
"with",
"the",
"sequence",
"in",
"fasta",
"format"
] | 4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b | https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/sequence.py#L58-L69 | train | 51,574 |
asyncee/django-easy-select2 | easy_select2/widgets.py | Select2Mixin.render_select2_options_code | def render_select2_options_code(self, options, id_):
"""Render options for select2."""
output = []
for key, value in options.items():
if isinstance(value, (dict, list)):
value = json.dumps(value)
output.append("data-{name}='{value}'".format(
name=key,
value=mark_safe(value)))
return mark_safe(' '.join(output)) | python | def render_select2_options_code(self, options, id_):
"""Render options for select2."""
output = []
for key, value in options.items():
if isinstance(value, (dict, list)):
value = json.dumps(value)
output.append("data-{name}='{value}'".format(
name=key,
value=mark_safe(value)))
return mark_safe(' '.join(output)) | [
"def",
"render_select2_options_code",
"(",
"self",
",",
"options",
",",
"id_",
")",
":",
"output",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"options",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"dict",
",",
"list... | Render options for select2. | [
"Render",
"options",
"for",
"select2",
"."
] | f81bbaa91d0266029be7ef6d075d85f13273e3a5 | https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/easy_select2/widgets.py#L76-L85 | train | 51,575 |
asyncee/django-easy-select2 | easy_select2/widgets.py | Select2Mixin.render_js_code | def render_js_code(self, id_, *args, **kwargs):
"""Render html container for Select2 widget with options."""
if id_:
options = self.render_select2_options_code(
dict(self.get_options()), id_)
return mark_safe(self.html.format(id=id_, options=options))
return u'' | python | def render_js_code(self, id_, *args, **kwargs):
"""Render html container for Select2 widget with options."""
if id_:
options = self.render_select2_options_code(
dict(self.get_options()), id_)
return mark_safe(self.html.format(id=id_, options=options))
return u'' | [
"def",
"render_js_code",
"(",
"self",
",",
"id_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id_",
":",
"options",
"=",
"self",
".",
"render_select2_options_code",
"(",
"dict",
"(",
"self",
".",
"get_options",
"(",
")",
")",
",",
"id... | Render html container for Select2 widget with options. | [
"Render",
"html",
"container",
"for",
"Select2",
"widget",
"with",
"options",
"."
] | f81bbaa91d0266029be7ef6d075d85f13273e3a5 | https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/easy_select2/widgets.py#L87-L93 | train | 51,576 |
asyncee/django-easy-select2 | easy_select2/widgets.py | Select2Mixin.render | def render(self, name, value, attrs=None, **kwargs):
"""
Extend base class's `render` method by appending
javascript inline text to html output.
"""
output = super(Select2Mixin, self).render(
name, value, attrs=attrs, **kwargs)
id_ = attrs['id']
output += self.render_js_code(
id_, name, value, attrs=attrs, **kwargs)
return mark_safe(output) | python | def render(self, name, value, attrs=None, **kwargs):
"""
Extend base class's `render` method by appending
javascript inline text to html output.
"""
output = super(Select2Mixin, self).render(
name, value, attrs=attrs, **kwargs)
id_ = attrs['id']
output += self.render_js_code(
id_, name, value, attrs=attrs, **kwargs)
return mark_safe(output) | [
"def",
"render",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"output",
"=",
"super",
"(",
"Select2Mixin",
",",
"self",
")",
".",
"render",
"(",
"name",
",",
"value",
",",
"attrs",
"=",
"at... | Extend base class's `render` method by appending
javascript inline text to html output. | [
"Extend",
"base",
"class",
"s",
"render",
"method",
"by",
"appending",
"javascript",
"inline",
"text",
"to",
"html",
"output",
"."
] | f81bbaa91d0266029be7ef6d075d85f13273e3a5 | https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/easy_select2/widgets.py#L95-L105 | train | 51,577 |
asyncee/django-easy-select2 | easy_select2/utils.py | select2_modelform | def select2_modelform(
model, attrs=None, form_class=es2_forms.FixedModelForm):
"""
Return ModelForm class for model with select2 widgets.
Arguments:
attrs: select2 widget attributes (width, for example) of type `dict`.
form_class: modelform base class, `forms.ModelForm` by default.
::
SomeModelForm = select2_modelform(models.SomeModelBanner)
is the same like::
class SomeModelForm(forms.ModelForm):
Meta = select2_modelform_meta(models.SomeModelForm)
"""
classname = '%sForm' % model._meta.object_name
meta = select2_modelform_meta(model, attrs=attrs)
return type(classname, (form_class,), {'Meta': meta}) | python | def select2_modelform(
model, attrs=None, form_class=es2_forms.FixedModelForm):
"""
Return ModelForm class for model with select2 widgets.
Arguments:
attrs: select2 widget attributes (width, for example) of type `dict`.
form_class: modelform base class, `forms.ModelForm` by default.
::
SomeModelForm = select2_modelform(models.SomeModelBanner)
is the same like::
class SomeModelForm(forms.ModelForm):
Meta = select2_modelform_meta(models.SomeModelForm)
"""
classname = '%sForm' % model._meta.object_name
meta = select2_modelform_meta(model, attrs=attrs)
return type(classname, (form_class,), {'Meta': meta}) | [
"def",
"select2_modelform",
"(",
"model",
",",
"attrs",
"=",
"None",
",",
"form_class",
"=",
"es2_forms",
".",
"FixedModelForm",
")",
":",
"classname",
"=",
"'%sForm'",
"%",
"model",
".",
"_meta",
".",
"object_name",
"meta",
"=",
"select2_modelform_meta",
"(",... | Return ModelForm class for model with select2 widgets.
Arguments:
attrs: select2 widget attributes (width, for example) of type `dict`.
form_class: modelform base class, `forms.ModelForm` by default.
::
SomeModelForm = select2_modelform(models.SomeModelBanner)
is the same like::
class SomeModelForm(forms.ModelForm):
Meta = select2_modelform_meta(models.SomeModelForm) | [
"Return",
"ModelForm",
"class",
"for",
"model",
"with",
"select2",
"widgets",
"."
] | f81bbaa91d0266029be7ef6d075d85f13273e3a5 | https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/easy_select2/utils.py#L52-L72 | train | 51,578 |
scour-project/scour | scour/svg_transform.py | SVGTransformationParser.parse | def parse(self, text):
""" Parse a string of SVG transform="" data.
"""
gen = self.lexer.lex(text)
next_val_fn = partial(next, *(gen,))
commands = []
token = next_val_fn()
while token[0] is not EOF:
command, token = self.rule_svg_transform(next_val_fn, token)
commands.append(command)
return commands | python | def parse(self, text):
""" Parse a string of SVG transform="" data.
"""
gen = self.lexer.lex(text)
next_val_fn = partial(next, *(gen,))
commands = []
token = next_val_fn()
while token[0] is not EOF:
command, token = self.rule_svg_transform(next_val_fn, token)
commands.append(command)
return commands | [
"def",
"parse",
"(",
"self",
",",
"text",
")",
":",
"gen",
"=",
"self",
".",
"lexer",
".",
"lex",
"(",
"text",
")",
"next_val_fn",
"=",
"partial",
"(",
"next",
",",
"*",
"(",
"gen",
",",
")",
")",
"commands",
"=",
"[",
"]",
"token",
"=",
"next_... | Parse a string of SVG transform="" data. | [
"Parse",
"a",
"string",
"of",
"SVG",
"transform",
"=",
"data",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/svg_transform.py#L154-L165 | train | 51,579 |
scour-project/scour | scour/scour.py | findElementsWithId | def findElementsWithId(node, elems=None):
"""
Returns all elements with id attributes
"""
if elems is None:
elems = {}
id = node.getAttribute('id')
if id != '':
elems[id] = node
if node.hasChildNodes():
for child in node.childNodes:
# from http://www.w3.org/TR/DOM-Level-2-Core/idl-definitions.html
# we are only really interested in nodes of type Element (1)
if child.nodeType == Node.ELEMENT_NODE:
findElementsWithId(child, elems)
return elems | python | def findElementsWithId(node, elems=None):
"""
Returns all elements with id attributes
"""
if elems is None:
elems = {}
id = node.getAttribute('id')
if id != '':
elems[id] = node
if node.hasChildNodes():
for child in node.childNodes:
# from http://www.w3.org/TR/DOM-Level-2-Core/idl-definitions.html
# we are only really interested in nodes of type Element (1)
if child.nodeType == Node.ELEMENT_NODE:
findElementsWithId(child, elems)
return elems | [
"def",
"findElementsWithId",
"(",
"node",
",",
"elems",
"=",
"None",
")",
":",
"if",
"elems",
"is",
"None",
":",
"elems",
"=",
"{",
"}",
"id",
"=",
"node",
".",
"getAttribute",
"(",
"'id'",
")",
"if",
"id",
"!=",
"''",
":",
"elems",
"[",
"id",
"]... | Returns all elements with id attributes | [
"Returns",
"all",
"elements",
"with",
"id",
"attributes"
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L524-L539 | train | 51,580 |
scour-project/scour | scour/scour.py | findReferencedElements | def findReferencedElements(node, ids=None):
"""
Returns IDs of all referenced elements
- node is the node at which to start the search.
- returns a map which has the id as key and
each value is is a list of nodes
Currently looks at 'xlink:href' and all attributes in 'referencingProps'
"""
global referencingProps
if ids is None:
ids = {}
# TODO: input argument ids is clunky here (see below how it is called)
# GZ: alternative to passing dict, use **kwargs
# if this node is a style element, parse its text into CSS
if node.nodeName == 'style' and node.namespaceURI == NS['SVG']:
# one stretch of text, please! (we could use node.normalize(), but
# this actually modifies the node, and we don't want to keep
# whitespace around if there's any)
stylesheet = "".join([child.nodeValue for child in node.childNodes])
if stylesheet != '':
cssRules = parseCssString(stylesheet)
for rule in cssRules:
for propname in rule['properties']:
propval = rule['properties'][propname]
findReferencingProperty(node, propname, propval, ids)
return ids
# else if xlink:href is set, then grab the id
href = node.getAttributeNS(NS['XLINK'], 'href')
if href != '' and len(href) > 1 and href[0] == '#':
# we remove the hash mark from the beginning of the id
id = href[1:]
if id in ids:
ids[id].append(node)
else:
ids[id] = [node]
# now get all style properties and the fill, stroke, filter attributes
styles = node.getAttribute('style').split(';')
for style in styles:
propval = style.split(':')
if len(propval) == 2:
prop = propval[0].strip()
val = propval[1].strip()
findReferencingProperty(node, prop, val, ids)
for attr in referencingProps:
val = node.getAttribute(attr).strip()
if not val:
continue
findReferencingProperty(node, attr, val, ids)
if node.hasChildNodes():
for child in node.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
findReferencedElements(child, ids)
return ids | python | def findReferencedElements(node, ids=None):
"""
Returns IDs of all referenced elements
- node is the node at which to start the search.
- returns a map which has the id as key and
each value is is a list of nodes
Currently looks at 'xlink:href' and all attributes in 'referencingProps'
"""
global referencingProps
if ids is None:
ids = {}
# TODO: input argument ids is clunky here (see below how it is called)
# GZ: alternative to passing dict, use **kwargs
# if this node is a style element, parse its text into CSS
if node.nodeName == 'style' and node.namespaceURI == NS['SVG']:
# one stretch of text, please! (we could use node.normalize(), but
# this actually modifies the node, and we don't want to keep
# whitespace around if there's any)
stylesheet = "".join([child.nodeValue for child in node.childNodes])
if stylesheet != '':
cssRules = parseCssString(stylesheet)
for rule in cssRules:
for propname in rule['properties']:
propval = rule['properties'][propname]
findReferencingProperty(node, propname, propval, ids)
return ids
# else if xlink:href is set, then grab the id
href = node.getAttributeNS(NS['XLINK'], 'href')
if href != '' and len(href) > 1 and href[0] == '#':
# we remove the hash mark from the beginning of the id
id = href[1:]
if id in ids:
ids[id].append(node)
else:
ids[id] = [node]
# now get all style properties and the fill, stroke, filter attributes
styles = node.getAttribute('style').split(';')
for style in styles:
propval = style.split(':')
if len(propval) == 2:
prop = propval[0].strip()
val = propval[1].strip()
findReferencingProperty(node, prop, val, ids)
for attr in referencingProps:
val = node.getAttribute(attr).strip()
if not val:
continue
findReferencingProperty(node, attr, val, ids)
if node.hasChildNodes():
for child in node.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
findReferencedElements(child, ids)
return ids | [
"def",
"findReferencedElements",
"(",
"node",
",",
"ids",
"=",
"None",
")",
":",
"global",
"referencingProps",
"if",
"ids",
"is",
"None",
":",
"ids",
"=",
"{",
"}",
"# TODO: input argument ids is clunky here (see below how it is called)",
"# GZ: alternative to passing dic... | Returns IDs of all referenced elements
- node is the node at which to start the search.
- returns a map which has the id as key and
each value is is a list of nodes
Currently looks at 'xlink:href' and all attributes in 'referencingProps' | [
"Returns",
"IDs",
"of",
"all",
"referenced",
"elements",
"-",
"node",
"is",
"the",
"node",
"at",
"which",
"to",
"start",
"the",
"search",
".",
"-",
"returns",
"a",
"map",
"which",
"has",
"the",
"id",
"as",
"key",
"and",
"each",
"value",
"is",
"is",
"... | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L545-L604 | train | 51,581 |
scour-project/scour | scour/scour.py | shortenIDs | def shortenIDs(doc, prefix, unprotectedElements=None):
"""
Shortens ID names used in the document. ID names referenced the most often are assigned the
shortest ID names.
If the list unprotectedElements is provided, only IDs from this list will be shortened.
Returns the number of bytes saved by shortening ID names in the document.
"""
num = 0
identifiedElements = findElementsWithId(doc.documentElement)
if unprotectedElements is None:
unprotectedElements = identifiedElements
referencedIDs = findReferencedElements(doc.documentElement)
# Make idList (list of idnames) sorted by reference count
# descending, so the highest reference count is first.
# First check that there's actually a defining element for the current ID name.
# (Cyn: I've seen documents with #id references but no element with that ID!)
idList = [(len(referencedIDs[rid]), rid) for rid in referencedIDs
if rid in unprotectedElements]
idList.sort(reverse=True)
idList = [rid for count, rid in idList]
# Add unreferenced IDs to end of idList in arbitrary order
idList.extend([rid for rid in unprotectedElements if rid not in idList])
curIdNum = 1
for rid in idList:
curId = intToID(curIdNum, prefix)
# First make sure that *this* element isn't already using
# the ID name we want to give it.
if curId != rid:
# Then, skip ahead if the new ID is already in identifiedElement.
while curId in identifiedElements:
curIdNum += 1
curId = intToID(curIdNum, prefix)
# Then go rename it.
num += renameID(doc, rid, curId, identifiedElements, referencedIDs)
curIdNum += 1
return num | python | def shortenIDs(doc, prefix, unprotectedElements=None):
"""
Shortens ID names used in the document. ID names referenced the most often are assigned the
shortest ID names.
If the list unprotectedElements is provided, only IDs from this list will be shortened.
Returns the number of bytes saved by shortening ID names in the document.
"""
num = 0
identifiedElements = findElementsWithId(doc.documentElement)
if unprotectedElements is None:
unprotectedElements = identifiedElements
referencedIDs = findReferencedElements(doc.documentElement)
# Make idList (list of idnames) sorted by reference count
# descending, so the highest reference count is first.
# First check that there's actually a defining element for the current ID name.
# (Cyn: I've seen documents with #id references but no element with that ID!)
idList = [(len(referencedIDs[rid]), rid) for rid in referencedIDs
if rid in unprotectedElements]
idList.sort(reverse=True)
idList = [rid for count, rid in idList]
# Add unreferenced IDs to end of idList in arbitrary order
idList.extend([rid for rid in unprotectedElements if rid not in idList])
curIdNum = 1
for rid in idList:
curId = intToID(curIdNum, prefix)
# First make sure that *this* element isn't already using
# the ID name we want to give it.
if curId != rid:
# Then, skip ahead if the new ID is already in identifiedElement.
while curId in identifiedElements:
curIdNum += 1
curId = intToID(curIdNum, prefix)
# Then go rename it.
num += renameID(doc, rid, curId, identifiedElements, referencedIDs)
curIdNum += 1
return num | [
"def",
"shortenIDs",
"(",
"doc",
",",
"prefix",
",",
"unprotectedElements",
"=",
"None",
")",
":",
"num",
"=",
"0",
"identifiedElements",
"=",
"findElementsWithId",
"(",
"doc",
".",
"documentElement",
")",
"if",
"unprotectedElements",
"is",
"None",
":",
"unpro... | Shortens ID names used in the document. ID names referenced the most often are assigned the
shortest ID names.
If the list unprotectedElements is provided, only IDs from this list will be shortened.
Returns the number of bytes saved by shortening ID names in the document. | [
"Shortens",
"ID",
"names",
"used",
"in",
"the",
"document",
".",
"ID",
"names",
"referenced",
"the",
"most",
"often",
"are",
"assigned",
"the",
"shortest",
"ID",
"names",
".",
"If",
"the",
"list",
"unprotectedElements",
"is",
"provided",
"only",
"IDs",
"from... | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L693-L735 | train | 51,582 |
scour-project/scour | scour/scour.py | intToID | def intToID(idnum, prefix):
"""
Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z,
then from aa to az, ba to bz, etc., until zz.
"""
rid = ''
while idnum > 0:
idnum -= 1
rid = chr((idnum % 26) + ord('a')) + rid
idnum = int(idnum / 26)
return prefix + rid | python | def intToID(idnum, prefix):
"""
Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z,
then from aa to az, ba to bz, etc., until zz.
"""
rid = ''
while idnum > 0:
idnum -= 1
rid = chr((idnum % 26) + ord('a')) + rid
idnum = int(idnum / 26)
return prefix + rid | [
"def",
"intToID",
"(",
"idnum",
",",
"prefix",
")",
":",
"rid",
"=",
"''",
"while",
"idnum",
">",
"0",
":",
"idnum",
"-=",
"1",
"rid",
"=",
"chr",
"(",
"(",
"idnum",
"%",
"26",
")",
"+",
"ord",
"(",
"'a'",
")",
")",
"+",
"rid",
"idnum",
"=",
... | Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z,
then from aa to az, ba to bz, etc., until zz. | [
"Returns",
"the",
"ID",
"name",
"for",
"the",
"given",
"ID",
"number",
"spreadsheet",
"-",
"style",
"i",
".",
"e",
".",
"from",
"a",
"to",
"z",
"then",
"from",
"aa",
"to",
"az",
"ba",
"to",
"bz",
"etc",
".",
"until",
"zz",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L738-L750 | train | 51,583 |
scour-project/scour | scour/scour.py | renameID | def renameID(doc, idFrom, idTo, identifiedElements, referencedIDs):
"""
Changes the ID name from idFrom to idTo, on the declaring element
as well as all references in the document doc.
Updates identifiedElements and referencedIDs.
Does not handle the case where idTo is already the ID name
of another element in doc.
Returns the number of bytes saved by this replacement.
"""
num = 0
definingNode = identifiedElements[idFrom]
definingNode.setAttribute("id", idTo)
del identifiedElements[idFrom]
identifiedElements[idTo] = definingNode
num += len(idFrom) - len(idTo)
# Update references to renamed node
referringNodes = referencedIDs.get(idFrom)
if referringNodes is not None:
# Look for the idFrom ID name in each of the referencing elements,
# exactly like findReferencedElements would.
# Cyn: Duplicated processing!
for node in referringNodes:
# if this node is a style element, parse its text into CSS
if node.nodeName == 'style' and node.namespaceURI == NS['SVG']:
# node.firstChild will be either a CDATA or a Text node now
if node.firstChild is not None:
# concatenate the value of all children, in case
# there's a CDATASection node surrounded by whitespace
# nodes
# (node.normalize() will NOT work here, it only acts on Text nodes)
oldValue = "".join([child.nodeValue for child in node.childNodes])
# not going to reparse the whole thing
newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')')
newValue = newValue.replace("url(#'" + idFrom + "')", 'url(#' + idTo + ')')
newValue = newValue.replace('url(#"' + idFrom + '")', 'url(#' + idTo + ')')
# and now replace all the children with this new stylesheet.
# again, this is in case the stylesheet was a CDATASection
node.childNodes[:] = [node.ownerDocument.createTextNode(newValue)]
num += len(oldValue) - len(newValue)
# if xlink:href is set to #idFrom, then change the id
href = node.getAttributeNS(NS['XLINK'], 'href')
if href == '#' + idFrom:
node.setAttributeNS(NS['XLINK'], 'href', '#' + idTo)
num += len(idFrom) - len(idTo)
# if the style has url(#idFrom), then change the id
styles = node.getAttribute('style')
if styles != '':
newValue = styles.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')')
newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')')
newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')')
node.setAttribute('style', newValue)
num += len(styles) - len(newValue)
# now try the fill, stroke, filter attributes
for attr in referencingProps:
oldValue = node.getAttribute(attr)
if oldValue != '':
newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')')
newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')')
newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')')
node.setAttribute(attr, newValue)
num += len(oldValue) - len(newValue)
del referencedIDs[idFrom]
referencedIDs[idTo] = referringNodes
return num | python | def renameID(doc, idFrom, idTo, identifiedElements, referencedIDs):
"""
Changes the ID name from idFrom to idTo, on the declaring element
as well as all references in the document doc.
Updates identifiedElements and referencedIDs.
Does not handle the case where idTo is already the ID name
of another element in doc.
Returns the number of bytes saved by this replacement.
"""
num = 0
definingNode = identifiedElements[idFrom]
definingNode.setAttribute("id", idTo)
del identifiedElements[idFrom]
identifiedElements[idTo] = definingNode
num += len(idFrom) - len(idTo)
# Update references to renamed node
referringNodes = referencedIDs.get(idFrom)
if referringNodes is not None:
# Look for the idFrom ID name in each of the referencing elements,
# exactly like findReferencedElements would.
# Cyn: Duplicated processing!
for node in referringNodes:
# if this node is a style element, parse its text into CSS
if node.nodeName == 'style' and node.namespaceURI == NS['SVG']:
# node.firstChild will be either a CDATA or a Text node now
if node.firstChild is not None:
# concatenate the value of all children, in case
# there's a CDATASection node surrounded by whitespace
# nodes
# (node.normalize() will NOT work here, it only acts on Text nodes)
oldValue = "".join([child.nodeValue for child in node.childNodes])
# not going to reparse the whole thing
newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')')
newValue = newValue.replace("url(#'" + idFrom + "')", 'url(#' + idTo + ')')
newValue = newValue.replace('url(#"' + idFrom + '")', 'url(#' + idTo + ')')
# and now replace all the children with this new stylesheet.
# again, this is in case the stylesheet was a CDATASection
node.childNodes[:] = [node.ownerDocument.createTextNode(newValue)]
num += len(oldValue) - len(newValue)
# if xlink:href is set to #idFrom, then change the id
href = node.getAttributeNS(NS['XLINK'], 'href')
if href == '#' + idFrom:
node.setAttributeNS(NS['XLINK'], 'href', '#' + idTo)
num += len(idFrom) - len(idTo)
# if the style has url(#idFrom), then change the id
styles = node.getAttribute('style')
if styles != '':
newValue = styles.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')')
newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')')
newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')')
node.setAttribute('style', newValue)
num += len(styles) - len(newValue)
# now try the fill, stroke, filter attributes
for attr in referencingProps:
oldValue = node.getAttribute(attr)
if oldValue != '':
newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')')
newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')')
newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')')
node.setAttribute(attr, newValue)
num += len(oldValue) - len(newValue)
del referencedIDs[idFrom]
referencedIDs[idTo] = referringNodes
return num | [
"def",
"renameID",
"(",
"doc",
",",
"idFrom",
",",
"idTo",
",",
"identifiedElements",
",",
"referencedIDs",
")",
":",
"num",
"=",
"0",
"definingNode",
"=",
"identifiedElements",
"[",
"idFrom",
"]",
"definingNode",
".",
"setAttribute",
"(",
"\"id\"",
",",
"id... | Changes the ID name from idFrom to idTo, on the declaring element
as well as all references in the document doc.
Updates identifiedElements and referencedIDs.
Does not handle the case where idTo is already the ID name
of another element in doc.
Returns the number of bytes saved by this replacement. | [
"Changes",
"the",
"ID",
"name",
"from",
"idFrom",
"to",
"idTo",
"on",
"the",
"declaring",
"element",
"as",
"well",
"as",
"all",
"references",
"in",
"the",
"document",
"doc",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L753-L828 | train | 51,584 |
scour-project/scour | scour/scour.py | unprotected_ids | def unprotected_ids(doc, options):
u"""Returns a list of unprotected IDs within the document doc."""
identifiedElements = findElementsWithId(doc.documentElement)
if not (options.protect_ids_noninkscape or
options.protect_ids_list or
options.protect_ids_prefix):
return identifiedElements
if options.protect_ids_list:
protect_ids_list = options.protect_ids_list.split(",")
if options.protect_ids_prefix:
protect_ids_prefixes = options.protect_ids_prefix.split(",")
for id in list(identifiedElements):
protected = False
if options.protect_ids_noninkscape and not id[-1].isdigit():
protected = True
if options.protect_ids_list and id in protect_ids_list:
protected = True
if options.protect_ids_prefix:
for prefix in protect_ids_prefixes:
if id.startswith(prefix):
protected = True
if protected:
del identifiedElements[id]
return identifiedElements | python | def unprotected_ids(doc, options):
u"""Returns a list of unprotected IDs within the document doc."""
identifiedElements = findElementsWithId(doc.documentElement)
if not (options.protect_ids_noninkscape or
options.protect_ids_list or
options.protect_ids_prefix):
return identifiedElements
if options.protect_ids_list:
protect_ids_list = options.protect_ids_list.split(",")
if options.protect_ids_prefix:
protect_ids_prefixes = options.protect_ids_prefix.split(",")
for id in list(identifiedElements):
protected = False
if options.protect_ids_noninkscape and not id[-1].isdigit():
protected = True
if options.protect_ids_list and id in protect_ids_list:
protected = True
if options.protect_ids_prefix:
for prefix in protect_ids_prefixes:
if id.startswith(prefix):
protected = True
if protected:
del identifiedElements[id]
return identifiedElements | [
"def",
"unprotected_ids",
"(",
"doc",
",",
"options",
")",
":",
"identifiedElements",
"=",
"findElementsWithId",
"(",
"doc",
".",
"documentElement",
")",
"if",
"not",
"(",
"options",
".",
"protect_ids_noninkscape",
"or",
"options",
".",
"protect_ids_list",
"or",
... | u"""Returns a list of unprotected IDs within the document doc. | [
"u",
"Returns",
"a",
"list",
"of",
"unprotected",
"IDs",
"within",
"the",
"document",
"doc",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L831-L854 | train | 51,585 |
scour-project/scour | scour/scour.py | removeUnreferencedIDs | def removeUnreferencedIDs(referencedIDs, identifiedElements):
"""
Removes the unreferenced ID attributes.
Returns the number of ID attributes removed
"""
global _num_ids_removed
keepTags = ['font']
num = 0
for id in identifiedElements:
node = identifiedElements[id]
if id not in referencedIDs and node.nodeName not in keepTags:
node.removeAttribute('id')
_num_ids_removed += 1
num += 1
return num | python | def removeUnreferencedIDs(referencedIDs, identifiedElements):
"""
Removes the unreferenced ID attributes.
Returns the number of ID attributes removed
"""
global _num_ids_removed
keepTags = ['font']
num = 0
for id in identifiedElements:
node = identifiedElements[id]
if id not in referencedIDs and node.nodeName not in keepTags:
node.removeAttribute('id')
_num_ids_removed += 1
num += 1
return num | [
"def",
"removeUnreferencedIDs",
"(",
"referencedIDs",
",",
"identifiedElements",
")",
":",
"global",
"_num_ids_removed",
"keepTags",
"=",
"[",
"'font'",
"]",
"num",
"=",
"0",
"for",
"id",
"in",
"identifiedElements",
":",
"node",
"=",
"identifiedElements",
"[",
"... | Removes the unreferenced ID attributes.
Returns the number of ID attributes removed | [
"Removes",
"the",
"unreferenced",
"ID",
"attributes",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L857-L872 | train | 51,586 |
scour-project/scour | scour/scour.py | moveCommonAttributesToParentGroup | def moveCommonAttributesToParentGroup(elem, referencedElements):
"""
This recursively calls this function on all children of the passed in element
and then iterates over all child elements and removes common inheritable attributes
from the children and places them in the parent group. But only if the parent contains
nothing but element children and whitespace. The attributes are only removed from the
children if the children are not referenced by other elements in the document.
"""
num = 0
childElements = []
# recurse first into the children (depth-first)
for child in elem.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
# only add and recurse if the child is not referenced elsewhere
if not child.getAttribute('id') in referencedElements:
childElements.append(child)
num += moveCommonAttributesToParentGroup(child, referencedElements)
# else if the parent has non-whitespace text children, do not
# try to move common attributes
elif child.nodeType == Node.TEXT_NODE and child.nodeValue.strip():
return num
# only process the children if there are more than one element
if len(childElements) <= 1:
return num
commonAttrs = {}
# add all inheritable properties of the first child element
# FIXME: Note there is a chance that the first child is a set/animate in which case
# its fill attribute is not what we want to look at, we should look for the first
# non-animate/set element
attrList = childElements[0].attributes
for index in range(attrList.length):
attr = attrList.item(index)
# this is most of the inheritable properties from http://www.w3.org/TR/SVG11/propidx.html
# and http://www.w3.org/TR/SVGTiny12/attributeTable.html
if attr.nodeName in ['clip-rule',
'display-align',
'fill', 'fill-opacity', 'fill-rule',
'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch',
'font-style', 'font-variant', 'font-weight',
'letter-spacing',
'pointer-events', 'shape-rendering',
'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
'stroke-miterlimit', 'stroke-opacity', 'stroke-width',
'text-anchor', 'text-decoration', 'text-rendering', 'visibility',
'word-spacing', 'writing-mode']:
# we just add all the attributes from the first child
commonAttrs[attr.nodeName] = attr.nodeValue
# for each subsequent child element
for childNum in range(len(childElements)):
# skip first child
if childNum == 0:
continue
child = childElements[childNum]
# if we are on an animateXXX/set element, ignore it (due to the 'fill' attribute)
if child.localName in ['set', 'animate', 'animateColor', 'animateTransform', 'animateMotion']:
continue
distinctAttrs = []
# loop through all current 'common' attributes
for name in commonAttrs:
# if this child doesn't match that attribute, schedule it for removal
if child.getAttribute(name) != commonAttrs[name]:
distinctAttrs.append(name)
# remove those attributes which are not common
for name in distinctAttrs:
del commonAttrs[name]
# commonAttrs now has all the inheritable attributes which are common among all child elements
for name in commonAttrs:
for child in childElements:
child.removeAttribute(name)
elem.setAttribute(name, commonAttrs[name])
# update our statistic (we remove N*M attributes and add back in M attributes)
num += (len(childElements) - 1) * len(commonAttrs)
return num | python | def moveCommonAttributesToParentGroup(elem, referencedElements):
"""
This recursively calls this function on all children of the passed in element
and then iterates over all child elements and removes common inheritable attributes
from the children and places them in the parent group. But only if the parent contains
nothing but element children and whitespace. The attributes are only removed from the
children if the children are not referenced by other elements in the document.
"""
num = 0
childElements = []
# recurse first into the children (depth-first)
for child in elem.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
# only add and recurse if the child is not referenced elsewhere
if not child.getAttribute('id') in referencedElements:
childElements.append(child)
num += moveCommonAttributesToParentGroup(child, referencedElements)
# else if the parent has non-whitespace text children, do not
# try to move common attributes
elif child.nodeType == Node.TEXT_NODE and child.nodeValue.strip():
return num
# only process the children if there are more than one element
if len(childElements) <= 1:
return num
commonAttrs = {}
# add all inheritable properties of the first child element
# FIXME: Note there is a chance that the first child is a set/animate in which case
# its fill attribute is not what we want to look at, we should look for the first
# non-animate/set element
attrList = childElements[0].attributes
for index in range(attrList.length):
attr = attrList.item(index)
# this is most of the inheritable properties from http://www.w3.org/TR/SVG11/propidx.html
# and http://www.w3.org/TR/SVGTiny12/attributeTable.html
if attr.nodeName in ['clip-rule',
'display-align',
'fill', 'fill-opacity', 'fill-rule',
'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch',
'font-style', 'font-variant', 'font-weight',
'letter-spacing',
'pointer-events', 'shape-rendering',
'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
'stroke-miterlimit', 'stroke-opacity', 'stroke-width',
'text-anchor', 'text-decoration', 'text-rendering', 'visibility',
'word-spacing', 'writing-mode']:
# we just add all the attributes from the first child
commonAttrs[attr.nodeName] = attr.nodeValue
# for each subsequent child element
for childNum in range(len(childElements)):
# skip first child
if childNum == 0:
continue
child = childElements[childNum]
# if we are on an animateXXX/set element, ignore it (due to the 'fill' attribute)
if child.localName in ['set', 'animate', 'animateColor', 'animateTransform', 'animateMotion']:
continue
distinctAttrs = []
# loop through all current 'common' attributes
for name in commonAttrs:
# if this child doesn't match that attribute, schedule it for removal
if child.getAttribute(name) != commonAttrs[name]:
distinctAttrs.append(name)
# remove those attributes which are not common
for name in distinctAttrs:
del commonAttrs[name]
# commonAttrs now has all the inheritable attributes which are common among all child elements
for name in commonAttrs:
for child in childElements:
child.removeAttribute(name)
elem.setAttribute(name, commonAttrs[name])
# update our statistic (we remove N*M attributes and add back in M attributes)
num += (len(childElements) - 1) * len(commonAttrs)
return num | [
"def",
"moveCommonAttributesToParentGroup",
"(",
"elem",
",",
"referencedElements",
")",
":",
"num",
"=",
"0",
"childElements",
"=",
"[",
"]",
"# recurse first into the children (depth-first)",
"for",
"child",
"in",
"elem",
".",
"childNodes",
":",
"if",
"child",
"."... | This recursively calls this function on all children of the passed in element
and then iterates over all child elements and removes common inheritable attributes
from the children and places them in the parent group. But only if the parent contains
nothing but element children and whitespace. The attributes are only removed from the
children if the children are not referenced by other elements in the document. | [
"This",
"recursively",
"calls",
"this",
"function",
"on",
"all",
"children",
"of",
"the",
"passed",
"in",
"element",
"and",
"then",
"iterates",
"over",
"all",
"child",
"elements",
"and",
"removes",
"common",
"inheritable",
"attributes",
"from",
"the",
"children"... | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L983-L1063 | train | 51,587 |
scour-project/scour | scour/scour.py | removeUnusedAttributesOnParent | def removeUnusedAttributesOnParent(elem):
"""
This recursively calls this function on all children of the element passed in,
then removes any unused attributes on this elem if none of the children inherit it
"""
num = 0
childElements = []
# recurse first into the children (depth-first)
for child in elem.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
childElements.append(child)
num += removeUnusedAttributesOnParent(child)
# only process the children if there are more than one element
if len(childElements) <= 1:
return num
# get all attribute values on this parent
attrList = elem.attributes
unusedAttrs = {}
for index in range(attrList.length):
attr = attrList.item(index)
if attr.nodeName in ['clip-rule',
'display-align',
'fill', 'fill-opacity', 'fill-rule',
'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch',
'font-style', 'font-variant', 'font-weight',
'letter-spacing',
'pointer-events', 'shape-rendering',
'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
'stroke-miterlimit', 'stroke-opacity', 'stroke-width',
'text-anchor', 'text-decoration', 'text-rendering', 'visibility',
'word-spacing', 'writing-mode']:
unusedAttrs[attr.nodeName] = attr.nodeValue
# for each child, if at least one child inherits the parent's attribute, then remove
for childNum in range(len(childElements)):
child = childElements[childNum]
inheritedAttrs = []
for name in unusedAttrs:
val = child.getAttribute(name)
if val == '' or val is None or val == 'inherit':
inheritedAttrs.append(name)
for a in inheritedAttrs:
del unusedAttrs[a]
# unusedAttrs now has all the parent attributes that are unused
for name in unusedAttrs:
elem.removeAttribute(name)
num += 1
return num | python | def removeUnusedAttributesOnParent(elem):
"""
This recursively calls this function on all children of the element passed in,
then removes any unused attributes on this elem if none of the children inherit it
"""
num = 0
childElements = []
# recurse first into the children (depth-first)
for child in elem.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
childElements.append(child)
num += removeUnusedAttributesOnParent(child)
# only process the children if there are more than one element
if len(childElements) <= 1:
return num
# get all attribute values on this parent
attrList = elem.attributes
unusedAttrs = {}
for index in range(attrList.length):
attr = attrList.item(index)
if attr.nodeName in ['clip-rule',
'display-align',
'fill', 'fill-opacity', 'fill-rule',
'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch',
'font-style', 'font-variant', 'font-weight',
'letter-spacing',
'pointer-events', 'shape-rendering',
'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
'stroke-miterlimit', 'stroke-opacity', 'stroke-width',
'text-anchor', 'text-decoration', 'text-rendering', 'visibility',
'word-spacing', 'writing-mode']:
unusedAttrs[attr.nodeName] = attr.nodeValue
# for each child, if at least one child inherits the parent's attribute, then remove
for childNum in range(len(childElements)):
child = childElements[childNum]
inheritedAttrs = []
for name in unusedAttrs:
val = child.getAttribute(name)
if val == '' or val is None or val == 'inherit':
inheritedAttrs.append(name)
for a in inheritedAttrs:
del unusedAttrs[a]
# unusedAttrs now has all the parent attributes that are unused
for name in unusedAttrs:
elem.removeAttribute(name)
num += 1
return num | [
"def",
"removeUnusedAttributesOnParent",
"(",
"elem",
")",
":",
"num",
"=",
"0",
"childElements",
"=",
"[",
"]",
"# recurse first into the children (depth-first)",
"for",
"child",
"in",
"elem",
".",
"childNodes",
":",
"if",
"child",
".",
"nodeType",
"==",
"Node",
... | This recursively calls this function on all children of the element passed in,
then removes any unused attributes on this elem if none of the children inherit it | [
"This",
"recursively",
"calls",
"this",
"function",
"on",
"all",
"children",
"of",
"the",
"element",
"passed",
"in",
"then",
"removes",
"any",
"unused",
"attributes",
"on",
"this",
"elem",
"if",
"none",
"of",
"the",
"children",
"inherit",
"it"
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1195-L1247 | train | 51,588 |
scour-project/scour | scour/scour.py | _getStyle | def _getStyle(node):
u"""Returns the style attribute of a node as a dictionary."""
if node.nodeType == Node.ELEMENT_NODE and len(node.getAttribute('style')) > 0:
styleMap = {}
rawStyles = node.getAttribute('style').split(';')
for style in rawStyles:
propval = style.split(':')
if len(propval) == 2:
styleMap[propval[0].strip()] = propval[1].strip()
return styleMap
else:
return {} | python | def _getStyle(node):
u"""Returns the style attribute of a node as a dictionary."""
if node.nodeType == Node.ELEMENT_NODE and len(node.getAttribute('style')) > 0:
styleMap = {}
rawStyles = node.getAttribute('style').split(';')
for style in rawStyles:
propval = style.split(':')
if len(propval) == 2:
styleMap[propval[0].strip()] = propval[1].strip()
return styleMap
else:
return {} | [
"def",
"_getStyle",
"(",
"node",
")",
":",
"if",
"node",
".",
"nodeType",
"==",
"Node",
".",
"ELEMENT_NODE",
"and",
"len",
"(",
"node",
".",
"getAttribute",
"(",
"'style'",
")",
")",
">",
"0",
":",
"styleMap",
"=",
"{",
"}",
"rawStyles",
"=",
"node",... | u"""Returns the style attribute of a node as a dictionary. | [
"u",
"Returns",
"the",
"style",
"attribute",
"of",
"a",
"node",
"as",
"a",
"dictionary",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1443-L1454 | train | 51,589 |
scour-project/scour | scour/scour.py | _setStyle | def _setStyle(node, styleMap):
u"""Sets the style attribute of a node to the dictionary ``styleMap``."""
fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap])
if fixedStyle != '':
node.setAttribute('style', fixedStyle)
elif node.getAttribute('style'):
node.removeAttribute('style')
return node | python | def _setStyle(node, styleMap):
u"""Sets the style attribute of a node to the dictionary ``styleMap``."""
fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap])
if fixedStyle != '':
node.setAttribute('style', fixedStyle)
elif node.getAttribute('style'):
node.removeAttribute('style')
return node | [
"def",
"_setStyle",
"(",
"node",
",",
"styleMap",
")",
":",
"fixedStyle",
"=",
"';'",
".",
"join",
"(",
"[",
"prop",
"+",
"':'",
"+",
"styleMap",
"[",
"prop",
"]",
"for",
"prop",
"in",
"styleMap",
"]",
")",
"if",
"fixedStyle",
"!=",
"''",
":",
"nod... | u"""Sets the style attribute of a node to the dictionary ``styleMap``. | [
"u",
"Sets",
"the",
"style",
"attribute",
"of",
"a",
"node",
"to",
"the",
"dictionary",
"styleMap",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1457-L1464 | train | 51,590 |
scour-project/scour | scour/scour.py | styleInheritedFromParent | def styleInheritedFromParent(node, style):
"""
Returns the value of 'style' that is inherited from the parents of the passed-in node
Warning: This method only considers presentation attributes and inline styles,
any style sheets are ignored!
"""
parentNode = node.parentNode
# return None if we reached the Document element
if parentNode.nodeType == Node.DOCUMENT_NODE:
return None
# check styles first (they take precedence over presentation attributes)
styles = _getStyle(parentNode)
if style in styles:
value = styles[style]
if not value == 'inherit':
return value
# check attributes
value = parentNode.getAttribute(style)
if value not in ['', 'inherit']:
return parentNode.getAttribute(style)
# check the next parent recursively if we did not find a value yet
return styleInheritedFromParent(parentNode, style) | python | def styleInheritedFromParent(node, style):
"""
Returns the value of 'style' that is inherited from the parents of the passed-in node
Warning: This method only considers presentation attributes and inline styles,
any style sheets are ignored!
"""
parentNode = node.parentNode
# return None if we reached the Document element
if parentNode.nodeType == Node.DOCUMENT_NODE:
return None
# check styles first (they take precedence over presentation attributes)
styles = _getStyle(parentNode)
if style in styles:
value = styles[style]
if not value == 'inherit':
return value
# check attributes
value = parentNode.getAttribute(style)
if value not in ['', 'inherit']:
return parentNode.getAttribute(style)
# check the next parent recursively if we did not find a value yet
return styleInheritedFromParent(parentNode, style) | [
"def",
"styleInheritedFromParent",
"(",
"node",
",",
"style",
")",
":",
"parentNode",
"=",
"node",
".",
"parentNode",
"# return None if we reached the Document element",
"if",
"parentNode",
".",
"nodeType",
"==",
"Node",
".",
"DOCUMENT_NODE",
":",
"return",
"None",
... | Returns the value of 'style' that is inherited from the parents of the passed-in node
Warning: This method only considers presentation attributes and inline styles,
any style sheets are ignored! | [
"Returns",
"the",
"value",
"of",
"style",
"that",
"is",
"inherited",
"from",
"the",
"parents",
"of",
"the",
"passed",
"-",
"in",
"node"
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1601-L1627 | train | 51,591 |
scour-project/scour | scour/scour.py | styleInheritedByChild | def styleInheritedByChild(node, style, nodeIsChild=False):
"""
Returns whether 'style' is inherited by any children of the passed-in node
If False is returned, it is guaranteed that 'style' can safely be removed
from the passed-in node without influencing visual output of it's children
If True is returned, the passed-in node should not have its text-based
attributes removed.
Warning: This method only considers presentation attributes and inline styles,
any style sheets are ignored!
"""
# Comment, text and CDATA nodes don't have attributes and aren't containers so they can't inherit attributes
if node.nodeType != Node.ELEMENT_NODE:
return False
if nodeIsChild:
# if the current child node sets a new value for 'style'
# we can stop the search in the current branch of the DOM tree
# check attributes
if node.getAttribute(style) not in ['', 'inherit']:
return False
# check styles
styles = _getStyle(node)
if (style in styles) and not (styles[style] == 'inherit'):
return False
else:
# if the passed-in node does not have any children 'style' can obviously not be inherited
if not node.childNodes:
return False
# If we have child nodes recursively check those
if node.childNodes:
for child in node.childNodes:
if styleInheritedByChild(child, style, True):
return True
# If the current element is a container element the inherited style is meaningless
# (since we made sure it's not inherited by any of its children)
if node.nodeName in ['a', 'defs', 'glyph', 'g', 'marker', 'mask',
'missing-glyph', 'pattern', 'svg', 'switch', 'symbol']:
return False
# in all other cases we have to assume the inherited value of 'style' is meaningfull and has to be kept
# (e.g nodes without children at the end of the DOM tree, text nodes, ...)
return True | python | def styleInheritedByChild(node, style, nodeIsChild=False):
"""
Returns whether 'style' is inherited by any children of the passed-in node
If False is returned, it is guaranteed that 'style' can safely be removed
from the passed-in node without influencing visual output of it's children
If True is returned, the passed-in node should not have its text-based
attributes removed.
Warning: This method only considers presentation attributes and inline styles,
any style sheets are ignored!
"""
# Comment, text and CDATA nodes don't have attributes and aren't containers so they can't inherit attributes
if node.nodeType != Node.ELEMENT_NODE:
return False
if nodeIsChild:
# if the current child node sets a new value for 'style'
# we can stop the search in the current branch of the DOM tree
# check attributes
if node.getAttribute(style) not in ['', 'inherit']:
return False
# check styles
styles = _getStyle(node)
if (style in styles) and not (styles[style] == 'inherit'):
return False
else:
# if the passed-in node does not have any children 'style' can obviously not be inherited
if not node.childNodes:
return False
# If we have child nodes recursively check those
if node.childNodes:
for child in node.childNodes:
if styleInheritedByChild(child, style, True):
return True
# If the current element is a container element the inherited style is meaningless
# (since we made sure it's not inherited by any of its children)
if node.nodeName in ['a', 'defs', 'glyph', 'g', 'marker', 'mask',
'missing-glyph', 'pattern', 'svg', 'switch', 'symbol']:
return False
# in all other cases we have to assume the inherited value of 'style' is meaningfull and has to be kept
# (e.g nodes without children at the end of the DOM tree, text nodes, ...)
return True | [
"def",
"styleInheritedByChild",
"(",
"node",
",",
"style",
",",
"nodeIsChild",
"=",
"False",
")",
":",
"# Comment, text and CDATA nodes don't have attributes and aren't containers so they can't inherit attributes",
"if",
"node",
".",
"nodeType",
"!=",
"Node",
".",
"ELEMENT_NO... | Returns whether 'style' is inherited by any children of the passed-in node
If False is returned, it is guaranteed that 'style' can safely be removed
from the passed-in node without influencing visual output of it's children
If True is returned, the passed-in node should not have its text-based
attributes removed.
Warning: This method only considers presentation attributes and inline styles,
any style sheets are ignored! | [
"Returns",
"whether",
"style",
"is",
"inherited",
"by",
"any",
"children",
"of",
"the",
"passed",
"-",
"in",
"node"
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1630-L1677 | train | 51,592 |
scour-project/scour | scour/scour.py | mayContainTextNodes | def mayContainTextNodes(node):
"""
Returns True if the passed-in node is probably a text element, or at least
one of its descendants is probably a text element.
If False is returned, it is guaranteed that the passed-in node has no
business having text-based attributes.
If True is returned, the passed-in node should not have its text-based
attributes removed.
"""
# Cached result of a prior call?
try:
return node.mayContainTextNodes
except AttributeError:
pass
result = True # Default value
# Comment, text and CDATA nodes don't have attributes and aren't containers
if node.nodeType != Node.ELEMENT_NODE:
result = False
# Non-SVG elements? Unknown elements!
elif node.namespaceURI != NS['SVG']:
result = True
# Blacklisted elements. Those are guaranteed not to be text elements.
elif node.nodeName in ['rect', 'circle', 'ellipse', 'line', 'polygon',
'polyline', 'path', 'image', 'stop']:
result = False
# Group elements. If we're missing any here, the default of True is used.
elif node.nodeName in ['g', 'clipPath', 'marker', 'mask', 'pattern',
'linearGradient', 'radialGradient', 'symbol']:
result = False
for child in node.childNodes:
if mayContainTextNodes(child):
result = True
# Everything else should be considered a future SVG-version text element
# at best, or an unknown element at worst. result will stay True.
# Cache this result before returning it.
node.mayContainTextNodes = result
return result | python | def mayContainTextNodes(node):
"""
Returns True if the passed-in node is probably a text element, or at least
one of its descendants is probably a text element.
If False is returned, it is guaranteed that the passed-in node has no
business having text-based attributes.
If True is returned, the passed-in node should not have its text-based
attributes removed.
"""
# Cached result of a prior call?
try:
return node.mayContainTextNodes
except AttributeError:
pass
result = True # Default value
# Comment, text and CDATA nodes don't have attributes and aren't containers
if node.nodeType != Node.ELEMENT_NODE:
result = False
# Non-SVG elements? Unknown elements!
elif node.namespaceURI != NS['SVG']:
result = True
# Blacklisted elements. Those are guaranteed not to be text elements.
elif node.nodeName in ['rect', 'circle', 'ellipse', 'line', 'polygon',
'polyline', 'path', 'image', 'stop']:
result = False
# Group elements. If we're missing any here, the default of True is used.
elif node.nodeName in ['g', 'clipPath', 'marker', 'mask', 'pattern',
'linearGradient', 'radialGradient', 'symbol']:
result = False
for child in node.childNodes:
if mayContainTextNodes(child):
result = True
# Everything else should be considered a future SVG-version text element
# at best, or an unknown element at worst. result will stay True.
# Cache this result before returning it.
node.mayContainTextNodes = result
return result | [
"def",
"mayContainTextNodes",
"(",
"node",
")",
":",
"# Cached result of a prior call?",
"try",
":",
"return",
"node",
".",
"mayContainTextNodes",
"except",
"AttributeError",
":",
"pass",
"result",
"=",
"True",
"# Default value",
"# Comment, text and CDATA nodes don't have ... | Returns True if the passed-in node is probably a text element, or at least
one of its descendants is probably a text element.
If False is returned, it is guaranteed that the passed-in node has no
business having text-based attributes.
If True is returned, the passed-in node should not have its text-based
attributes removed. | [
"Returns",
"True",
"if",
"the",
"passed",
"-",
"in",
"node",
"is",
"probably",
"a",
"text",
"element",
"or",
"at",
"least",
"one",
"of",
"its",
"descendants",
"is",
"probably",
"a",
"text",
"element",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1680-L1720 | train | 51,593 |
scour-project/scour | scour/scour.py | taint | def taint(taintedSet, taintedAttribute):
u"""Adds an attribute to a set of attributes.
Related attributes are also included."""
taintedSet.add(taintedAttribute)
if taintedAttribute == 'marker':
taintedSet |= set(['marker-start', 'marker-mid', 'marker-end'])
if taintedAttribute in ['marker-start', 'marker-mid', 'marker-end']:
taintedSet.add('marker')
return taintedSet | python | def taint(taintedSet, taintedAttribute):
u"""Adds an attribute to a set of attributes.
Related attributes are also included."""
taintedSet.add(taintedAttribute)
if taintedAttribute == 'marker':
taintedSet |= set(['marker-start', 'marker-mid', 'marker-end'])
if taintedAttribute in ['marker-start', 'marker-mid', 'marker-end']:
taintedSet.add('marker')
return taintedSet | [
"def",
"taint",
"(",
"taintedSet",
",",
"taintedAttribute",
")",
":",
"taintedSet",
".",
"add",
"(",
"taintedAttribute",
")",
"if",
"taintedAttribute",
"==",
"'marker'",
":",
"taintedSet",
"|=",
"set",
"(",
"[",
"'marker-start'",
",",
"'marker-mid'",
",",
"'ma... | u"""Adds an attribute to a set of attributes.
Related attributes are also included. | [
"u",
"Adds",
"an",
"attribute",
"to",
"a",
"set",
"of",
"attributes",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1885-L1894 | train | 51,594 |
scour-project/scour | scour/scour.py | removeDefaultAttributeValue | def removeDefaultAttributeValue(node, attribute):
"""
Removes the DefaultAttribute 'attribute' from 'node' if specified conditions are fulfilled
Warning: Does NOT check if the attribute is actually valid for the passed element type for increased preformance!
"""
if not node.hasAttribute(attribute.name):
return 0
# differentiate between text and numeric values
if isinstance(attribute.value, str):
if node.getAttribute(attribute.name) == attribute.value:
if (attribute.conditions is None) or attribute.conditions(node):
node.removeAttribute(attribute.name)
return 1
else:
nodeValue = SVGLength(node.getAttribute(attribute.name))
if ((attribute.value is None)
or ((nodeValue.value == attribute.value) and not (nodeValue.units == Unit.INVALID))):
if ((attribute.units is None)
or (nodeValue.units == attribute.units)
or (isinstance(attribute.units, list) and nodeValue.units in attribute.units)):
if (attribute.conditions is None) or attribute.conditions(node):
node.removeAttribute(attribute.name)
return 1
return 0 | python | def removeDefaultAttributeValue(node, attribute):
"""
Removes the DefaultAttribute 'attribute' from 'node' if specified conditions are fulfilled
Warning: Does NOT check if the attribute is actually valid for the passed element type for increased preformance!
"""
if not node.hasAttribute(attribute.name):
return 0
# differentiate between text and numeric values
if isinstance(attribute.value, str):
if node.getAttribute(attribute.name) == attribute.value:
if (attribute.conditions is None) or attribute.conditions(node):
node.removeAttribute(attribute.name)
return 1
else:
nodeValue = SVGLength(node.getAttribute(attribute.name))
if ((attribute.value is None)
or ((nodeValue.value == attribute.value) and not (nodeValue.units == Unit.INVALID))):
if ((attribute.units is None)
or (nodeValue.units == attribute.units)
or (isinstance(attribute.units, list) and nodeValue.units in attribute.units)):
if (attribute.conditions is None) or attribute.conditions(node):
node.removeAttribute(attribute.name)
return 1
return 0 | [
"def",
"removeDefaultAttributeValue",
"(",
"node",
",",
"attribute",
")",
":",
"if",
"not",
"node",
".",
"hasAttribute",
"(",
"attribute",
".",
"name",
")",
":",
"return",
"0",
"# differentiate between text and numeric values",
"if",
"isinstance",
"(",
"attribute",
... | Removes the DefaultAttribute 'attribute' from 'node' if specified conditions are fulfilled
Warning: Does NOT check if the attribute is actually valid for the passed element type for increased preformance! | [
"Removes",
"the",
"DefaultAttribute",
"attribute",
"from",
"node",
"if",
"specified",
"conditions",
"are",
"fulfilled"
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1897-L1923 | train | 51,595 |
scour-project/scour | scour/scour.py | removeDefaultAttributeValues | def removeDefaultAttributeValues(node, options, tainted=set()):
u"""'tainted' keeps a set of attributes defined in parent nodes.
For such attributes, we don't delete attributes with default values."""
num = 0
if node.nodeType != Node.ELEMENT_NODE:
return 0
# Conditionally remove all default attributes defined in 'default_attributes' (a list of 'DefaultAttribute's)
#
# For increased performance do not iterate the whole list for each element but run only on valid subsets
# - 'default_attributes_universal' (attributes valid for all elements)
# - 'default_attributes_per_element' (attributes specific to one specific element type)
for attribute in default_attributes_universal:
num += removeDefaultAttributeValue(node, attribute)
if node.nodeName in default_attributes_per_element:
for attribute in default_attributes_per_element[node.nodeName]:
num += removeDefaultAttributeValue(node, attribute)
# Summarily get rid of default properties
attributes = [node.attributes.item(i).nodeName for i in range(node.attributes.length)]
for attribute in attributes:
if attribute not in tainted:
if attribute in default_properties:
if node.getAttribute(attribute) == default_properties[attribute]:
node.removeAttribute(attribute)
num += 1
else:
tainted = taint(tainted, attribute)
# Properties might also occur as styles, remove them too
styles = _getStyle(node)
for attribute in list(styles):
if attribute not in tainted:
if attribute in default_properties:
if styles[attribute] == default_properties[attribute]:
del styles[attribute]
num += 1
else:
tainted = taint(tainted, attribute)
_setStyle(node, styles)
# recurse for our child elements
for child in node.childNodes:
num += removeDefaultAttributeValues(child, options, tainted.copy())
return num | python | def removeDefaultAttributeValues(node, options, tainted=set()):
u"""'tainted' keeps a set of attributes defined in parent nodes.
For such attributes, we don't delete attributes with default values."""
num = 0
if node.nodeType != Node.ELEMENT_NODE:
return 0
# Conditionally remove all default attributes defined in 'default_attributes' (a list of 'DefaultAttribute's)
#
# For increased performance do not iterate the whole list for each element but run only on valid subsets
# - 'default_attributes_universal' (attributes valid for all elements)
# - 'default_attributes_per_element' (attributes specific to one specific element type)
for attribute in default_attributes_universal:
num += removeDefaultAttributeValue(node, attribute)
if node.nodeName in default_attributes_per_element:
for attribute in default_attributes_per_element[node.nodeName]:
num += removeDefaultAttributeValue(node, attribute)
# Summarily get rid of default properties
attributes = [node.attributes.item(i).nodeName for i in range(node.attributes.length)]
for attribute in attributes:
if attribute not in tainted:
if attribute in default_properties:
if node.getAttribute(attribute) == default_properties[attribute]:
node.removeAttribute(attribute)
num += 1
else:
tainted = taint(tainted, attribute)
# Properties might also occur as styles, remove them too
styles = _getStyle(node)
for attribute in list(styles):
if attribute not in tainted:
if attribute in default_properties:
if styles[attribute] == default_properties[attribute]:
del styles[attribute]
num += 1
else:
tainted = taint(tainted, attribute)
_setStyle(node, styles)
# recurse for our child elements
for child in node.childNodes:
num += removeDefaultAttributeValues(child, options, tainted.copy())
return num | [
"def",
"removeDefaultAttributeValues",
"(",
"node",
",",
"options",
",",
"tainted",
"=",
"set",
"(",
")",
")",
":",
"num",
"=",
"0",
"if",
"node",
".",
"nodeType",
"!=",
"Node",
".",
"ELEMENT_NODE",
":",
"return",
"0",
"# Conditionally remove all default attri... | u"""'tainted' keeps a set of attributes defined in parent nodes.
For such attributes, we don't delete attributes with default values. | [
"u",
"tainted",
"keeps",
"a",
"set",
"of",
"attributes",
"defined",
"in",
"parent",
"nodes",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L1926-L1971 | train | 51,596 |
scour-project/scour | scour/scour.py | parseListOfPoints | def parseListOfPoints(s):
"""
Parse string into a list of points.
Returns a list containing an even number of coordinate strings
"""
i = 0
# (wsp)? comma-or-wsp-separated coordinate pairs (wsp)?
# coordinate-pair = coordinate comma-or-wsp coordinate
# coordinate = sign? integer
# comma-wsp: (wsp+ comma? wsp*) | (comma wsp*)
ws_nums = re.split(r"\s*[\s,]\s*", s.strip())
nums = []
# also, if 100-100 is found, split it into two also
# <polygon points="100,-100,100-100,100-100-100,-100-100" />
for i in range(len(ws_nums)):
negcoords = ws_nums[i].split("-")
# this string didn't have any negative coordinates
if len(negcoords) == 1:
nums.append(negcoords[0])
# we got negative coords
else:
for j in range(len(negcoords)):
# first number could be positive
if j == 0:
if negcoords[0] != '':
nums.append(negcoords[0])
# otherwise all other strings will be negative
else:
# unless we accidentally split a number that was in scientific notation
# and had a negative exponent (500.00e-1)
prev = ""
if len(nums):
prev = nums[len(nums) - 1]
if prev and prev[len(prev) - 1] in ['e', 'E']:
nums[len(nums) - 1] = prev + '-' + negcoords[j]
else:
nums.append('-' + negcoords[j])
# if we have an odd number of points, return empty
if len(nums) % 2 != 0:
return []
# now resolve into Decimal values
i = 0
while i < len(nums):
try:
nums[i] = getcontext().create_decimal(nums[i])
nums[i + 1] = getcontext().create_decimal(nums[i + 1])
except InvalidOperation: # one of the lengths had a unit or is an invalid number
return []
i += 2
return nums | python | def parseListOfPoints(s):
"""
Parse string into a list of points.
Returns a list containing an even number of coordinate strings
"""
i = 0
# (wsp)? comma-or-wsp-separated coordinate pairs (wsp)?
# coordinate-pair = coordinate comma-or-wsp coordinate
# coordinate = sign? integer
# comma-wsp: (wsp+ comma? wsp*) | (comma wsp*)
ws_nums = re.split(r"\s*[\s,]\s*", s.strip())
nums = []
# also, if 100-100 is found, split it into two also
# <polygon points="100,-100,100-100,100-100-100,-100-100" />
for i in range(len(ws_nums)):
negcoords = ws_nums[i].split("-")
# this string didn't have any negative coordinates
if len(negcoords) == 1:
nums.append(negcoords[0])
# we got negative coords
else:
for j in range(len(negcoords)):
# first number could be positive
if j == 0:
if negcoords[0] != '':
nums.append(negcoords[0])
# otherwise all other strings will be negative
else:
# unless we accidentally split a number that was in scientific notation
# and had a negative exponent (500.00e-1)
prev = ""
if len(nums):
prev = nums[len(nums) - 1]
if prev and prev[len(prev) - 1] in ['e', 'E']:
nums[len(nums) - 1] = prev + '-' + negcoords[j]
else:
nums.append('-' + negcoords[j])
# if we have an odd number of points, return empty
if len(nums) % 2 != 0:
return []
# now resolve into Decimal values
i = 0
while i < len(nums):
try:
nums[i] = getcontext().create_decimal(nums[i])
nums[i + 1] = getcontext().create_decimal(nums[i + 1])
except InvalidOperation: # one of the lengths had a unit or is an invalid number
return []
i += 2
return nums | [
"def",
"parseListOfPoints",
"(",
"s",
")",
":",
"i",
"=",
"0",
"# (wsp)? comma-or-wsp-separated coordinate pairs (wsp)?",
"# coordinate-pair = coordinate comma-or-wsp coordinate",
"# coordinate = sign? integer",
"# comma-wsp: (wsp+ comma? wsp*) | (comma wsp*)",
"ws_nums",
"=",
"re",
... | Parse string into a list of points.
Returns a list containing an even number of coordinate strings | [
"Parse",
"string",
"into",
"a",
"list",
"of",
"points",
"."
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L2558-L2615 | train | 51,597 |
scour-project/scour | scour/scour.py | cleanPolygon | def cleanPolygon(elem, options):
"""
Remove unnecessary closing point of polygon points attribute
"""
global _num_points_removed_from_polygon
pts = parseListOfPoints(elem.getAttribute('points'))
N = len(pts) / 2
if N >= 2:
(startx, starty) = pts[:2]
(endx, endy) = pts[-2:]
if startx == endx and starty == endy:
del pts[-2:]
_num_points_removed_from_polygon += 1
elem.setAttribute('points', scourCoordinates(pts, options, True)) | python | def cleanPolygon(elem, options):
"""
Remove unnecessary closing point of polygon points attribute
"""
global _num_points_removed_from_polygon
pts = parseListOfPoints(elem.getAttribute('points'))
N = len(pts) / 2
if N >= 2:
(startx, starty) = pts[:2]
(endx, endy) = pts[-2:]
if startx == endx and starty == endy:
del pts[-2:]
_num_points_removed_from_polygon += 1
elem.setAttribute('points', scourCoordinates(pts, options, True)) | [
"def",
"cleanPolygon",
"(",
"elem",
",",
"options",
")",
":",
"global",
"_num_points_removed_from_polygon",
"pts",
"=",
"parseListOfPoints",
"(",
"elem",
".",
"getAttribute",
"(",
"'points'",
")",
")",
"N",
"=",
"len",
"(",
"pts",
")",
"/",
"2",
"if",
"N",... | Remove unnecessary closing point of polygon points attribute | [
"Remove",
"unnecessary",
"closing",
"point",
"of",
"polygon",
"points",
"attribute"
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L2618-L2632 | train | 51,598 |
scour-project/scour | scour/scour.py | cleanPolyline | def cleanPolyline(elem, options):
"""
Scour the polyline points attribute
"""
pts = parseListOfPoints(elem.getAttribute('points'))
elem.setAttribute('points', scourCoordinates(pts, options, True)) | python | def cleanPolyline(elem, options):
"""
Scour the polyline points attribute
"""
pts = parseListOfPoints(elem.getAttribute('points'))
elem.setAttribute('points', scourCoordinates(pts, options, True)) | [
"def",
"cleanPolyline",
"(",
"elem",
",",
"options",
")",
":",
"pts",
"=",
"parseListOfPoints",
"(",
"elem",
".",
"getAttribute",
"(",
"'points'",
")",
")",
"elem",
".",
"setAttribute",
"(",
"'points'",
",",
"scourCoordinates",
"(",
"pts",
",",
"options",
... | Scour the polyline points attribute | [
"Scour",
"the",
"polyline",
"points",
"attribute"
] | 049264eba6b1a54ae5ba1d6a5077d8e7b80e8835 | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L2635-L2640 | train | 51,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.