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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ttroy50/pyirishrail | pyirishrail/pyirishrail.py | _parse | def _parse(data, obj_name, attr_map):
"""parse xml data into a python map"""
parsed_xml = minidom.parseString(data)
parsed_objects = []
for obj in parsed_xml.getElementsByTagName(obj_name):
parsed_obj = {}
for (py_name, xml_name) in attr_map.items():
parsed_obj[py_name] = _ge... | python | def _parse(data, obj_name, attr_map):
"""parse xml data into a python map"""
parsed_xml = minidom.parseString(data)
parsed_objects = []
for obj in parsed_xml.getElementsByTagName(obj_name):
parsed_obj = {}
for (py_name, xml_name) in attr_map.items():
parsed_obj[py_name] = _ge... | [
"def",
"_parse",
"(",
"data",
",",
"obj_name",
",",
"attr_map",
")",
":",
"parsed_xml",
"=",
"minidom",
".",
"parseString",
"(",
"data",
")",
"parsed_objects",
"=",
"[",
"]",
"for",
"obj",
"in",
"parsed_xml",
".",
"getElementsByTagName",
"(",
"obj_name",
"... | parse xml data into a python map | [
"parse",
"xml",
"data",
"into",
"a",
"python",
"map"
] | 83232a65a53317fbcc2a41938165912c51b23515 | https://github.com/ttroy50/pyirishrail/blob/83232a65a53317fbcc2a41938165912c51b23515/pyirishrail/pyirishrail.py#L32-L41 | train | 56,000 |
ttroy50/pyirishrail | pyirishrail/pyirishrail.py | IrishRailRTPI.get_all_stations | def get_all_stations(self, station_type=None):
"""Returns information of all stations.
@param<optional> station_type: ['mainline', 'suburban', 'dart']
"""
params = None
if station_type and station_type in STATION_TYPE_TO_CODE_DICT:
url = self.api_base_url + 'getAllSta... | python | def get_all_stations(self, station_type=None):
"""Returns information of all stations.
@param<optional> station_type: ['mainline', 'suburban', 'dart']
"""
params = None
if station_type and station_type in STATION_TYPE_TO_CODE_DICT:
url = self.api_base_url + 'getAllSta... | [
"def",
"get_all_stations",
"(",
"self",
",",
"station_type",
"=",
"None",
")",
":",
"params",
"=",
"None",
"if",
"station_type",
"and",
"station_type",
"in",
"STATION_TYPE_TO_CODE_DICT",
":",
"url",
"=",
"self",
".",
"api_base_url",
"+",
"'getAllStationsXML_WithSt... | Returns information of all stations.
@param<optional> station_type: ['mainline', 'suburban', 'dart'] | [
"Returns",
"information",
"of",
"all",
"stations",
"."
] | 83232a65a53317fbcc2a41938165912c51b23515 | https://github.com/ttroy50/pyirishrail/blob/83232a65a53317fbcc2a41938165912c51b23515/pyirishrail/pyirishrail.py#L112-L131 | train | 56,001 |
ttroy50/pyirishrail | pyirishrail/pyirishrail.py | IrishRailRTPI.get_all_current_trains | def get_all_current_trains(self, train_type=None, direction=None):
"""Returns all trains that are due to start in the next 10 minutes
@param train_type: ['mainline', 'suburban', 'dart']
"""
params = None
if train_type:
url = self.api_base_url + 'getCurrentTrainsXML_Wi... | python | def get_all_current_trains(self, train_type=None, direction=None):
"""Returns all trains that are due to start in the next 10 minutes
@param train_type: ['mainline', 'suburban', 'dart']
"""
params = None
if train_type:
url = self.api_base_url + 'getCurrentTrainsXML_Wi... | [
"def",
"get_all_current_trains",
"(",
"self",
",",
"train_type",
"=",
"None",
",",
"direction",
"=",
"None",
")",
":",
"params",
"=",
"None",
"if",
"train_type",
":",
"url",
"=",
"self",
".",
"api_base_url",
"+",
"'getCurrentTrainsXML_WithTrainType'",
"params",
... | Returns all trains that are due to start in the next 10 minutes
@param train_type: ['mainline', 'suburban', 'dart'] | [
"Returns",
"all",
"trains",
"that",
"are",
"due",
"to",
"start",
"in",
"the",
"next",
"10",
"minutes"
] | 83232a65a53317fbcc2a41938165912c51b23515 | https://github.com/ttroy50/pyirishrail/blob/83232a65a53317fbcc2a41938165912c51b23515/pyirishrail/pyirishrail.py#L133-L157 | train | 56,002 |
ttroy50/pyirishrail | pyirishrail/pyirishrail.py | IrishRailRTPI.get_station_by_name | def get_station_by_name(self,
station_name,
num_minutes=None,
direction=None,
destination=None,
stops_at=None):
"""Returns all trains due to serve station `station_name`.
... | python | def get_station_by_name(self,
station_name,
num_minutes=None,
direction=None,
destination=None,
stops_at=None):
"""Returns all trains due to serve station `station_name`.
... | [
"def",
"get_station_by_name",
"(",
"self",
",",
"station_name",
",",
"num_minutes",
"=",
"None",
",",
"direction",
"=",
"None",
",",
"destination",
"=",
"None",
",",
"stops_at",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"api_base_url",
"+",
"'getStat... | Returns all trains due to serve station `station_name`.
@param station_code
@param num_minutes. Only trains within this time. Between 5 and 90
@param direction Filter by direction. Northbound or Southbound
@param destination Filter by name of the destination stations
@param stops... | [
"Returns",
"all",
"trains",
"due",
"to",
"serve",
"station",
"station_name",
"."
] | 83232a65a53317fbcc2a41938165912c51b23515 | https://github.com/ttroy50/pyirishrail/blob/83232a65a53317fbcc2a41938165912c51b23515/pyirishrail/pyirishrail.py#L159-L193 | train | 56,003 |
ttroy50/pyirishrail | pyirishrail/pyirishrail.py | IrishRailRTPI.get_train_stops | def get_train_stops(self, train_code, date=None):
"""Get details for a train.
@param train_code code for the trian
@param date Date in format "15 oct 2017". If none use today
"""
if date is None:
date = datetime.date.today().strftime("%d %B %Y")
url = self.ap... | python | def get_train_stops(self, train_code, date=None):
"""Get details for a train.
@param train_code code for the trian
@param date Date in format "15 oct 2017". If none use today
"""
if date is None:
date = datetime.date.today().strftime("%d %B %Y")
url = self.ap... | [
"def",
"get_train_stops",
"(",
"self",
",",
"train_code",
",",
"date",
"=",
"None",
")",
":",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
".",
"strftime",
"(",
"\"%d %B %Y\"",
")",
"url",
"=",
"self"... | Get details for a train.
@param train_code code for the trian
@param date Date in format "15 oct 2017". If none use today | [
"Get",
"details",
"for",
"a",
"train",
"."
] | 83232a65a53317fbcc2a41938165912c51b23515 | https://github.com/ttroy50/pyirishrail/blob/83232a65a53317fbcc2a41938165912c51b23515/pyirishrail/pyirishrail.py#L263-L283 | train | 56,004 |
marcrosis/selenium-sunbro | sunbro.py | BasePage.fill_fields | def fill_fields(self, **kwargs):
"""Fills the fields referenced by kwargs keys and fill them with
the value"""
for name, value in kwargs.items():
field = getattr(self, name)
field.send_keys(value) | python | def fill_fields(self, **kwargs):
"""Fills the fields referenced by kwargs keys and fill them with
the value"""
for name, value in kwargs.items():
field = getattr(self, name)
field.send_keys(value) | [
"def",
"fill_fields",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"name",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"field",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"field",
".",
"send_keys",
"(",
"value",
")"
] | Fills the fields referenced by kwargs keys and fill them with
the value | [
"Fills",
"the",
"fields",
"referenced",
"by",
"kwargs",
"keys",
"and",
"fill",
"them",
"with",
"the",
"value"
] | f3d964817dc48c6755062a66b0bd46354e81f356 | https://github.com/marcrosis/selenium-sunbro/blob/f3d964817dc48c6755062a66b0bd46354e81f356/sunbro.py#L139-L144 | train | 56,005 |
jingming/spotify | spotify/auth/user.py | authorize_url | def authorize_url(client_id=None, redirect_uri=None, state=None, scopes=None, show_dialog=False, http_client=None):
"""
Trigger authorization dialog
:param str client_id: Client ID
:param str redirect_uri: Application Redirect URI
:param str state: Application State
:param List[str] scopes: Sco... | python | def authorize_url(client_id=None, redirect_uri=None, state=None, scopes=None, show_dialog=False, http_client=None):
"""
Trigger authorization dialog
:param str client_id: Client ID
:param str redirect_uri: Application Redirect URI
:param str state: Application State
:param List[str] scopes: Sco... | [
"def",
"authorize_url",
"(",
"client_id",
"=",
"None",
",",
"redirect_uri",
"=",
"None",
",",
"state",
"=",
"None",
",",
"scopes",
"=",
"None",
",",
"show_dialog",
"=",
"False",
",",
"http_client",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'client_id'"... | Trigger authorization dialog
:param str client_id: Client ID
:param str redirect_uri: Application Redirect URI
:param str state: Application State
:param List[str] scopes: Scopes to request
:param bool show_dialog: Show the dialog
:param http_client: HTTP Client for requests
:return str Aut... | [
"Trigger",
"authorization",
"dialog"
] | d92c71073b2515f3c850604114133a7d2022d1a4 | https://github.com/jingming/spotify/blob/d92c71073b2515f3c850604114133a7d2022d1a4/spotify/auth/user.py#L7-L29 | train | 56,006 |
jingming/spotify | spotify/auth/user.py | User.refresh | def refresh(self):
"""
Refresh the access token
"""
data = {
'grant_type': 'refresh_token',
'refresh_token': self._token.refresh_token
}
response = self.http_client.post(self.URL, data=data, auth=(self.client_id, self.client_secret))
respo... | python | def refresh(self):
"""
Refresh the access token
"""
data = {
'grant_type': 'refresh_token',
'refresh_token': self._token.refresh_token
}
response = self.http_client.post(self.URL, data=data, auth=(self.client_id, self.client_secret))
respo... | [
"def",
"refresh",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'grant_type'",
":",
"'refresh_token'",
",",
"'refresh_token'",
":",
"self",
".",
"_token",
".",
"refresh_token",
"}",
"response",
"=",
"self",
".",
"http_client",
".",
"post",
"(",
"self",
".",
... | Refresh the access token | [
"Refresh",
"the",
"access",
"token"
] | d92c71073b2515f3c850604114133a7d2022d1a4 | https://github.com/jingming/spotify/blob/d92c71073b2515f3c850604114133a7d2022d1a4/spotify/auth/user.py#L77-L88 | train | 56,007 |
LeastAuthority/txkube | src/txkube/_invariants.py | instance_of | def instance_of(cls):
"""
Create an invariant requiring the value is an instance of ``cls``.
"""
def check(value):
return (
isinstance(value, cls),
u"{value!r} is instance of {actual!s}, required {required!s}".format(
value=value,
actual=fu... | python | def instance_of(cls):
"""
Create an invariant requiring the value is an instance of ``cls``.
"""
def check(value):
return (
isinstance(value, cls),
u"{value!r} is instance of {actual!s}, required {required!s}".format(
value=value,
actual=fu... | [
"def",
"instance_of",
"(",
"cls",
")",
":",
"def",
"check",
"(",
"value",
")",
":",
"return",
"(",
"isinstance",
"(",
"value",
",",
"cls",
")",
",",
"u\"{value!r} is instance of {actual!s}, required {required!s}\"",
".",
"format",
"(",
"value",
"=",
"value",
"... | Create an invariant requiring the value is an instance of ``cls``. | [
"Create",
"an",
"invariant",
"requiring",
"the",
"value",
"is",
"an",
"instance",
"of",
"cls",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_invariants.py#L10-L23 | train | 56,008 |
LeastAuthority/txkube | src/txkube/_invariants.py | provider_of | def provider_of(iface):
"""
Create an invariant requiring the value provides the zope.interface
``iface``.
"""
def check(value):
return (
iface.providedBy(value),
u"{value!r} does not provide {interface!s}".format(
value=value,
interfac... | python | def provider_of(iface):
"""
Create an invariant requiring the value provides the zope.interface
``iface``.
"""
def check(value):
return (
iface.providedBy(value),
u"{value!r} does not provide {interface!s}".format(
value=value,
interfac... | [
"def",
"provider_of",
"(",
"iface",
")",
":",
"def",
"check",
"(",
"value",
")",
":",
"return",
"(",
"iface",
".",
"providedBy",
"(",
"value",
")",
",",
"u\"{value!r} does not provide {interface!s}\"",
".",
"format",
"(",
"value",
"=",
"value",
",",
"interfa... | Create an invariant requiring the value provides the zope.interface
``iface``. | [
"Create",
"an",
"invariant",
"requiring",
"the",
"value",
"provides",
"the",
"zope",
".",
"interface",
"iface",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_invariants.py#L26-L39 | train | 56,009 |
themattrix/python-temporary | temporary/directories.py | temp_dir | def temp_dir(suffix='', prefix='tmp', parent_dir=None, make_cwd=False):
"""
Create a temporary directory and optionally change the current
working directory to it. The directory is deleted when the context
exits.
The temporary directory is created when entering the context
manager, and deleted ... | python | def temp_dir(suffix='', prefix='tmp', parent_dir=None, make_cwd=False):
"""
Create a temporary directory and optionally change the current
working directory to it. The directory is deleted when the context
exits.
The temporary directory is created when entering the context
manager, and deleted ... | [
"def",
"temp_dir",
"(",
"suffix",
"=",
"''",
",",
"prefix",
"=",
"'tmp'",
",",
"parent_dir",
"=",
"None",
",",
"make_cwd",
"=",
"False",
")",
":",
"prev_cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"parent_dir",
"=",
"parent_dir",
"if",
"parent_dir",
"is"... | Create a temporary directory and optionally change the current
working directory to it. The directory is deleted when the context
exits.
The temporary directory is created when entering the context
manager, and deleted when exiting it:
>>> import temporary
>>> with temporary.temp_dir() as temp_... | [
"Create",
"a",
"temporary",
"directory",
"and",
"optionally",
"change",
"the",
"current",
"working",
"directory",
"to",
"it",
".",
"The",
"directory",
"is",
"deleted",
"when",
"the",
"context",
"exits",
"."
] | 5af1a393e57e71c2d4728e2c8e228edfd020e847 | https://github.com/themattrix/python-temporary/blob/5af1a393e57e71c2d4728e2c8e228edfd020e847/temporary/directories.py#L13-L62 | train | 56,010 |
hollenstein/maspy | maspy/auxiliary.py | openSafeReplace | def openSafeReplace(filepath, mode='w+b'):
"""Context manager to open a temporary file and replace the original file on
closing.
"""
tempfileName = None
#Check if the filepath can be accessed and is writable before creating the
#tempfile
if not _isFileAccessible(filepath):
raise IOEr... | python | def openSafeReplace(filepath, mode='w+b'):
"""Context manager to open a temporary file and replace the original file on
closing.
"""
tempfileName = None
#Check if the filepath can be accessed and is writable before creating the
#tempfile
if not _isFileAccessible(filepath):
raise IOEr... | [
"def",
"openSafeReplace",
"(",
"filepath",
",",
"mode",
"=",
"'w+b'",
")",
":",
"tempfileName",
"=",
"None",
"#Check if the filepath can be accessed and is writable before creating the",
"#tempfile",
"if",
"not",
"_isFileAccessible",
"(",
"filepath",
")",
":",
"raise",
... | Context manager to open a temporary file and replace the original file on
closing. | [
"Context",
"manager",
"to",
"open",
"a",
"temporary",
"file",
"and",
"replace",
"the",
"original",
"file",
"on",
"closing",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L115-L133 | train | 56,011 |
hollenstein/maspy | maspy/auxiliary.py | _isFileAccessible | def _isFileAccessible(filepath):
"""Returns True if the specified filepath is writable."""
directory = os.path.dirname(filepath)
if not os.access(directory, os.W_OK):
#Return False if directory does not exist or is not writable
return False
if os.path.exists(filepath):
if not os.... | python | def _isFileAccessible(filepath):
"""Returns True if the specified filepath is writable."""
directory = os.path.dirname(filepath)
if not os.access(directory, os.W_OK):
#Return False if directory does not exist or is not writable
return False
if os.path.exists(filepath):
if not os.... | [
"def",
"_isFileAccessible",
"(",
"filepath",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filepath",
")",
"if",
"not",
"os",
".",
"access",
"(",
"directory",
",",
"os",
".",
"W_OK",
")",
":",
"#Return False if directory does not exist... | Returns True if the specified filepath is writable. | [
"Returns",
"True",
"if",
"the",
"specified",
"filepath",
"is",
"writable",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L136-L153 | train | 56,012 |
hollenstein/maspy | maspy/auxiliary.py | writeJsonZipfile | def writeJsonZipfile(filelike, data, compress=True, mode='w', name='data'):
"""Serializes the objects contained in data to a JSON formated string and
writes it to a zipfile.
:param filelike: path to a file (str) or a file-like object
:param data: object that should be converted to a JSON formated strin... | python | def writeJsonZipfile(filelike, data, compress=True, mode='w', name='data'):
"""Serializes the objects contained in data to a JSON formated string and
writes it to a zipfile.
:param filelike: path to a file (str) or a file-like object
:param data: object that should be converted to a JSON formated strin... | [
"def",
"writeJsonZipfile",
"(",
"filelike",
",",
"data",
",",
"compress",
"=",
"True",
",",
"mode",
"=",
"'w'",
",",
"name",
"=",
"'data'",
")",
":",
"zipcomp",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
"if",
"compress",
"else",
"zipfile",
".",
"ZIP_STORED",
... | Serializes the objects contained in data to a JSON formated string and
writes it to a zipfile.
:param filelike: path to a file (str) or a file-like object
:param data: object that should be converted to a JSON formated string.
Objects and types in data must be supported by the json.JSONEncoder or
... | [
"Serializes",
"the",
"objects",
"contained",
"in",
"data",
"to",
"a",
"JSON",
"formated",
"string",
"and",
"writes",
"it",
"to",
"a",
"zipfile",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L175-L193 | train | 56,013 |
hollenstein/maspy | maspy/auxiliary.py | writeBinaryItemContainer | def writeBinaryItemContainer(filelike, binaryItemContainer, compress=True):
"""Serializes the binaryItems contained in binaryItemContainer and writes
them into a zipfile archive.
Examples of binaryItem classes are :class:`maspy.core.Ci` and
:class:`maspy.core.Sai`. A binaryItem class has to define the ... | python | def writeBinaryItemContainer(filelike, binaryItemContainer, compress=True):
"""Serializes the binaryItems contained in binaryItemContainer and writes
them into a zipfile archive.
Examples of binaryItem classes are :class:`maspy.core.Ci` and
:class:`maspy.core.Sai`. A binaryItem class has to define the ... | [
"def",
"writeBinaryItemContainer",
"(",
"filelike",
",",
"binaryItemContainer",
",",
"compress",
"=",
"True",
")",
":",
"allMetadata",
"=",
"dict",
"(",
")",
"binarydatafile",
"=",
"io",
".",
"BytesIO",
"(",
")",
"#Note: It would be possible to sort the items here",
... | Serializes the binaryItems contained in binaryItemContainer and writes
them into a zipfile archive.
Examples of binaryItem classes are :class:`maspy.core.Ci` and
:class:`maspy.core.Sai`. A binaryItem class has to define the function
``_reprJSON()`` which returns a JSON formated string representation of... | [
"Serializes",
"the",
"binaryItems",
"contained",
"in",
"binaryItemContainer",
"and",
"writes",
"them",
"into",
"a",
"zipfile",
"archive",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L196-L236 | train | 56,014 |
hollenstein/maspy | maspy/auxiliary.py | _dumpArrayToFile | def _dumpArrayToFile(filelike, array):
"""Serializes a 1-dimensional ``numpy.array`` to bytes, writes the bytes to
the filelike object and returns a dictionary with metadata, necessary to
restore the ``numpy.array`` from the file.
:param filelike: can be a file or a file-like object that provides the
... | python | def _dumpArrayToFile(filelike, array):
"""Serializes a 1-dimensional ``numpy.array`` to bytes, writes the bytes to
the filelike object and returns a dictionary with metadata, necessary to
restore the ``numpy.array`` from the file.
:param filelike: can be a file or a file-like object that provides the
... | [
"def",
"_dumpArrayToFile",
"(",
"filelike",
",",
"array",
")",
":",
"bytedata",
"=",
"array",
".",
"tobytes",
"(",
"'C'",
")",
"start",
"=",
"filelike",
".",
"tell",
"(",
")",
"end",
"=",
"start",
"+",
"len",
"(",
"bytedata",
")",
"metadata",
"=",
"{... | Serializes a 1-dimensional ``numpy.array`` to bytes, writes the bytes to
the filelike object and returns a dictionary with metadata, necessary to
restore the ``numpy.array`` from the file.
:param filelike: can be a file or a file-like object that provides the
methods ``.write()`` and ``.tell()``.
... | [
"Serializes",
"a",
"1",
"-",
"dimensional",
"numpy",
".",
"array",
"to",
"bytes",
"writes",
"the",
"bytes",
"to",
"the",
"filelike",
"object",
"and",
"returns",
"a",
"dictionary",
"with",
"metadata",
"necessary",
"to",
"restore",
"the",
"numpy",
".",
"array"... | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L266-L287 | train | 56,015 |
hollenstein/maspy | maspy/auxiliary.py | _dumpNdarrayToFile | def _dumpNdarrayToFile(filelike, ndarray):
"""Serializes an N-dimensional ``numpy.array`` to bytes, writes the bytes to
the filelike object and returns a dictionary with metadata, necessary to
restore the ``numpy.array`` from the file.
:param filelike: can be a file or a file-like object that provides ... | python | def _dumpNdarrayToFile(filelike, ndarray):
"""Serializes an N-dimensional ``numpy.array`` to bytes, writes the bytes to
the filelike object and returns a dictionary with metadata, necessary to
restore the ``numpy.array`` from the file.
:param filelike: can be a file or a file-like object that provides ... | [
"def",
"_dumpNdarrayToFile",
"(",
"filelike",
",",
"ndarray",
")",
":",
"bytedata",
"=",
"ndarray",
".",
"tobytes",
"(",
"'C'",
")",
"start",
"=",
"filelike",
".",
"tell",
"(",
")",
"end",
"=",
"start",
"+",
"len",
"(",
"bytedata",
")",
"metadata",
"="... | Serializes an N-dimensional ``numpy.array`` to bytes, writes the bytes to
the filelike object and returns a dictionary with metadata, necessary to
restore the ``numpy.array`` from the file.
:param filelike: can be a file or a file-like object that provides the
methods ``.write()`` and ``.tell()``.
... | [
"Serializes",
"an",
"N",
"-",
"dimensional",
"numpy",
".",
"array",
"to",
"bytes",
"writes",
"the",
"bytes",
"to",
"the",
"filelike",
"object",
"and",
"returns",
"a",
"dictionary",
"with",
"metadata",
"necessary",
"to",
"restore",
"the",
"numpy",
".",
"array... | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L290-L312 | train | 56,016 |
hollenstein/maspy | maspy/auxiliary.py | _arrayFromBytes | def _arrayFromBytes(dataBytes, metadata):
"""Generates and returns a numpy array from raw data bytes.
:param bytes: raw data bytes as generated by ``numpy.ndarray.tobytes()``
:param metadata: a dictionary containing the data type and optionally the
shape parameter to reconstruct a ``numpy.array`` f... | python | def _arrayFromBytes(dataBytes, metadata):
"""Generates and returns a numpy array from raw data bytes.
:param bytes: raw data bytes as generated by ``numpy.ndarray.tobytes()``
:param metadata: a dictionary containing the data type and optionally the
shape parameter to reconstruct a ``numpy.array`` f... | [
"def",
"_arrayFromBytes",
"(",
"dataBytes",
",",
"metadata",
")",
":",
"array",
"=",
"numpy",
".",
"fromstring",
"(",
"dataBytes",
",",
"dtype",
"=",
"numpy",
".",
"typeDict",
"[",
"metadata",
"[",
"'dtype'",
"]",
"]",
")",
"if",
"'shape'",
"in",
"metada... | Generates and returns a numpy array from raw data bytes.
:param bytes: raw data bytes as generated by ``numpy.ndarray.tobytes()``
:param metadata: a dictionary containing the data type and optionally the
shape parameter to reconstruct a ``numpy.array`` from the raw data
bytes. ``{"dtype": "floa... | [
"Generates",
"and",
"returns",
"a",
"numpy",
"array",
"from",
"raw",
"data",
"bytes",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L353-L366 | train | 56,017 |
hollenstein/maspy | maspy/auxiliary.py | searchFileLocation | def searchFileLocation(targetFileName, targetFileExtension, rootDirectory,
recursive=True):
"""Search for a filename with a specified file extension in all subfolders
of specified rootDirectory, returns first matching instance.
:param targetFileName: #TODO: docstring
:type target... | python | def searchFileLocation(targetFileName, targetFileExtension, rootDirectory,
recursive=True):
"""Search for a filename with a specified file extension in all subfolders
of specified rootDirectory, returns first matching instance.
:param targetFileName: #TODO: docstring
:type target... | [
"def",
"searchFileLocation",
"(",
"targetFileName",
",",
"targetFileExtension",
",",
"rootDirectory",
",",
"recursive",
"=",
"True",
")",
":",
"expectedFileName",
"=",
"targetFileName",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'.'",
"+",
"targetFile... | Search for a filename with a specified file extension in all subfolders
of specified rootDirectory, returns first matching instance.
:param targetFileName: #TODO: docstring
:type targetFileName: str
:param rootDirectory: #TODO: docstring
:type rootDirectory: str
:param targetFileExtension: #TOD... | [
"Search",
"for",
"a",
"filename",
"with",
"a",
"specified",
"file",
"extension",
"in",
"all",
"subfolders",
"of",
"specified",
"rootDirectory",
"returns",
"first",
"matching",
"instance",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L370-L405 | train | 56,018 |
hollenstein/maspy | maspy/auxiliary.py | matchingFilePaths | def matchingFilePaths(targetfilename, directory, targetFileExtension=None,
selector=None):
"""Search for files in all subfolders of specified directory, return
filepaths of all matching instances.
:param targetfilename: filename to search for, only the string before the
last "... | python | def matchingFilePaths(targetfilename, directory, targetFileExtension=None,
selector=None):
"""Search for files in all subfolders of specified directory, return
filepaths of all matching instances.
:param targetfilename: filename to search for, only the string before the
last "... | [
"def",
"matchingFilePaths",
"(",
"targetfilename",
",",
"directory",
",",
"targetFileExtension",
"=",
"None",
",",
"selector",
"=",
"None",
")",
":",
"targetFilePaths",
"=",
"list",
"(",
")",
"targetfilename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"t... | Search for files in all subfolders of specified directory, return
filepaths of all matching instances.
:param targetfilename: filename to search for, only the string before the
last "." is used for filename matching. Ignored if a selector function
is specified.
:param directory: search dire... | [
"Search",
"for",
"files",
"in",
"all",
"subfolders",
"of",
"specified",
"directory",
"return",
"filepaths",
"of",
"all",
"matching",
"instances",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L408-L443 | train | 56,019 |
hollenstein/maspy | maspy/auxiliary.py | listFiletypes | def listFiletypes(targetfilename, directory):
"""Looks for all occurences of a specified filename in a directory and
returns a list of all present file extensions of this filename.
In this cas everything after the first dot is considered to be the file
extension: ``"filename.txt" -> "txt"``, ``"filenam... | python | def listFiletypes(targetfilename, directory):
"""Looks for all occurences of a specified filename in a directory and
returns a list of all present file extensions of this filename.
In this cas everything after the first dot is considered to be the file
extension: ``"filename.txt" -> "txt"``, ``"filenam... | [
"def",
"listFiletypes",
"(",
"targetfilename",
",",
"directory",
")",
":",
"targetextensions",
"=",
"list",
"(",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"joinpath... | Looks for all occurences of a specified filename in a directory and
returns a list of all present file extensions of this filename.
In this cas everything after the first dot is considered to be the file
extension: ``"filename.txt" -> "txt"``, ``"filename.txt.zip" -> "txt.zip"``
:param targetfilename:... | [
"Looks",
"for",
"all",
"occurences",
"of",
"a",
"specified",
"filename",
"in",
"a",
"directory",
"and",
"returns",
"a",
"list",
"of",
"all",
"present",
"file",
"extensions",
"of",
"this",
"filename",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L446-L468 | train | 56,020 |
hollenstein/maspy | maspy/auxiliary.py | findAllSubstrings | def findAllSubstrings(string, substring):
""" Returns a list of all substring starting positions in string or an empty
list if substring is not present in string.
:param string: a template string
:param substring: a string, which is looked for in the ``string`` parameter.
:returns: a list of subst... | python | def findAllSubstrings(string, substring):
""" Returns a list of all substring starting positions in string or an empty
list if substring is not present in string.
:param string: a template string
:param substring: a string, which is looked for in the ``string`` parameter.
:returns: a list of subst... | [
"def",
"findAllSubstrings",
"(",
"string",
",",
"substring",
")",
":",
"#TODO: solve with regex? what about '.':",
"#return [m.start() for m in re.finditer('(?='+substring+')', string)]",
"start",
"=",
"0",
"positions",
"=",
"[",
"]",
"while",
"True",
":",
"start",
"=",
"... | Returns a list of all substring starting positions in string or an empty
list if substring is not present in string.
:param string: a template string
:param substring: a string, which is looked for in the ``string`` parameter.
:returns: a list of substring starting positions in the template string | [
"Returns",
"a",
"list",
"of",
"all",
"substring",
"starting",
"positions",
"in",
"string",
"or",
"an",
"empty",
"list",
"if",
"substring",
"is",
"not",
"present",
"in",
"string",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L471-L491 | train | 56,021 |
hollenstein/maspy | maspy/auxiliary.py | toList | def toList(variable, types=(basestring, int, float, )):
"""Converts a variable of type string, int, float to a list, containing the
variable as the only element.
:param variable: any python object
:type variable: (str, int, float, others)
:returns: [variable] or variable
"""
if isinstance(... | python | def toList(variable, types=(basestring, int, float, )):
"""Converts a variable of type string, int, float to a list, containing the
variable as the only element.
:param variable: any python object
:type variable: (str, int, float, others)
:returns: [variable] or variable
"""
if isinstance(... | [
"def",
"toList",
"(",
"variable",
",",
"types",
"=",
"(",
"basestring",
",",
"int",
",",
"float",
",",
")",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"types",
")",
":",
"return",
"[",
"variable",
"]",
"else",
":",
"return",
"variable"
] | Converts a variable of type string, int, float to a list, containing the
variable as the only element.
:param variable: any python object
:type variable: (str, int, float, others)
:returns: [variable] or variable | [
"Converts",
"a",
"variable",
"of",
"type",
"string",
"int",
"float",
"to",
"a",
"list",
"containing",
"the",
"variable",
"as",
"the",
"only",
"element",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L494-L506 | train | 56,022 |
hollenstein/maspy | maspy/auxiliary.py | calcDeviationLimits | def calcDeviationLimits(value, tolerance, mode):
"""Returns the upper and lower deviation limits for a value and a given
tolerance, either as relative or a absolute difference.
:param value: can be a single value or a list of values if a list of values
is given, the minimal value will be used to ca... | python | def calcDeviationLimits(value, tolerance, mode):
"""Returns the upper and lower deviation limits for a value and a given
tolerance, either as relative or a absolute difference.
:param value: can be a single value or a list of values if a list of values
is given, the minimal value will be used to ca... | [
"def",
"calcDeviationLimits",
"(",
"value",
",",
"tolerance",
",",
"mode",
")",
":",
"values",
"=",
"toList",
"(",
"value",
")",
"if",
"mode",
"==",
"'relative'",
":",
"lowerLimit",
"=",
"min",
"(",
"values",
")",
"*",
"(",
"1",
"-",
"tolerance",
")",
... | Returns the upper and lower deviation limits for a value and a given
tolerance, either as relative or a absolute difference.
:param value: can be a single value or a list of values if a list of values
is given, the minimal value will be used to calculate the lower limit
and the maximum value to... | [
"Returns",
"the",
"upper",
"and",
"lower",
"deviation",
"limits",
"for",
"a",
"value",
"and",
"a",
"given",
"tolerance",
"either",
"as",
"relative",
"or",
"a",
"absolute",
"difference",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L556-L576 | train | 56,023 |
hollenstein/maspy | maspy/auxiliary.py | PartiallySafeReplace.open | def open(self, filepath, mode='w+b'):
"""Opens a file - will actually return a temporary file but replace the
original file when the context is closed.
"""
#Check if the filepath can be accessed and is writable before creating
#the tempfile
if not _isFileAccessible(filepa... | python | def open(self, filepath, mode='w+b'):
"""Opens a file - will actually return a temporary file but replace the
original file when the context is closed.
"""
#Check if the filepath can be accessed and is writable before creating
#the tempfile
if not _isFileAccessible(filepa... | [
"def",
"open",
"(",
"self",
",",
"filepath",
",",
"mode",
"=",
"'w+b'",
")",
":",
"#Check if the filepath can be accessed and is writable before creating",
"#the tempfile",
"if",
"not",
"_isFileAccessible",
"(",
"filepath",
")",
":",
"raise",
"IOError",
"(",
"'File %s... | Opens a file - will actually return a temporary file but replace the
original file when the context is closed. | [
"Opens",
"a",
"file",
"-",
"will",
"actually",
"return",
"a",
"temporary",
"file",
"but",
"replace",
"the",
"original",
"file",
"when",
"the",
"context",
"is",
"closed",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L83-L100 | train | 56,024 |
GeorgeArgyros/symautomata | symautomata/sfa.py | SFA.add_state | def add_state(self):
"""This function adds a new state"""
sid = len(self.states)
self.states.append(SFAState(sid)) | python | def add_state(self):
"""This function adds a new state"""
sid = len(self.states)
self.states.append(SFAState(sid)) | [
"def",
"add_state",
"(",
"self",
")",
":",
"sid",
"=",
"len",
"(",
"self",
".",
"states",
")",
"self",
".",
"states",
".",
"append",
"(",
"SFAState",
"(",
"sid",
")",
")"
] | This function adds a new state | [
"This",
"function",
"adds",
"a",
"new",
"state"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/sfa.py#L168-L171 | train | 56,025 |
bitesofcode/projex | projex/addon.py | AddonMixin._initAddons | def _initAddons(cls, recurse=True):
"""
Initializes the addons for this manager.
"""
for addon_module in cls.addonModules(recurse):
projex.importmodules(addon_module) | python | def _initAddons(cls, recurse=True):
"""
Initializes the addons for this manager.
"""
for addon_module in cls.addonModules(recurse):
projex.importmodules(addon_module) | [
"def",
"_initAddons",
"(",
"cls",
",",
"recurse",
"=",
"True",
")",
":",
"for",
"addon_module",
"in",
"cls",
".",
"addonModules",
"(",
"recurse",
")",
":",
"projex",
".",
"importmodules",
"(",
"addon_module",
")"
] | Initializes the addons for this manager. | [
"Initializes",
"the",
"addons",
"for",
"this",
"manager",
"."
] | d31743ec456a41428709968ab11a2cf6c6c76247 | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/addon.py#L9-L14 | train | 56,026 |
stephrdev/django-tapeforms | tapeforms/contrib/bootstrap.py | BootstrapTapeformMixin.get_field_label_css_class | def get_field_label_css_class(self, bound_field):
"""
Returns 'form-check-label' if widget is CheckboxInput. For all other fields,
no css class is added.
"""
# If we render CheckboxInputs, Bootstrap requires a different
# field label css class for checkboxes.
if i... | python | def get_field_label_css_class(self, bound_field):
"""
Returns 'form-check-label' if widget is CheckboxInput. For all other fields,
no css class is added.
"""
# If we render CheckboxInputs, Bootstrap requires a different
# field label css class for checkboxes.
if i... | [
"def",
"get_field_label_css_class",
"(",
"self",
",",
"bound_field",
")",
":",
"# If we render CheckboxInputs, Bootstrap requires a different",
"# field label css class for checkboxes.",
"if",
"isinstance",
"(",
"bound_field",
".",
"field",
".",
"widget",
",",
"forms",
".",
... | Returns 'form-check-label' if widget is CheckboxInput. For all other fields,
no css class is added. | [
"Returns",
"form",
"-",
"check",
"-",
"label",
"if",
"widget",
"is",
"CheckboxInput",
".",
"For",
"all",
"other",
"fields",
"no",
"css",
"class",
"is",
"added",
"."
] | 255602de43777141f18afaf30669d7bdd4f7c323 | https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/contrib/bootstrap.py#L43-L53 | train | 56,027 |
e7dal/bubble3 | behave4cmd0/pathutil.py | create_textfile_with_contents | def create_textfile_with_contents(filename, contents, encoding='utf-8'):
"""
Creates a textual file with the provided contents in the workdir.
Overwrites an existing file.
"""
ensure_directory_exists(os.path.dirname(filename))
if os.path.exists(filename):
os.remove(filename)
outstrea... | python | def create_textfile_with_contents(filename, contents, encoding='utf-8'):
"""
Creates a textual file with the provided contents in the workdir.
Overwrites an existing file.
"""
ensure_directory_exists(os.path.dirname(filename))
if os.path.exists(filename):
os.remove(filename)
outstrea... | [
"def",
"create_textfile_with_contents",
"(",
"filename",
",",
"contents",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"ensure_directory_exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
... | Creates a textual file with the provided contents in the workdir.
Overwrites an existing file. | [
"Creates",
"a",
"textual",
"file",
"with",
"the",
"provided",
"contents",
"in",
"the",
"workdir",
".",
"Overwrites",
"an",
"existing",
"file",
"."
] | 59c735281a95b44f6263a25f4d6ce24fca520082 | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/pathutil.py#L69-L83 | train | 56,028 |
e7dal/bubble3 | behave4cmd0/pathutil.py | ensure_directory_exists | def ensure_directory_exists(dirname, context=None):
"""
Ensures that a directory exits.
If it does not exist, it is automatically created.
"""
real_dirname = dirname
if context:
real_dirname = realpath_with_context(dirname, context)
if not os.path.exists(real_dirname):
os.mak... | python | def ensure_directory_exists(dirname, context=None):
"""
Ensures that a directory exits.
If it does not exist, it is automatically created.
"""
real_dirname = dirname
if context:
real_dirname = realpath_with_context(dirname, context)
if not os.path.exists(real_dirname):
os.mak... | [
"def",
"ensure_directory_exists",
"(",
"dirname",
",",
"context",
"=",
"None",
")",
":",
"real_dirname",
"=",
"dirname",
"if",
"context",
":",
"real_dirname",
"=",
"realpath_with_context",
"(",
"dirname",
",",
"context",
")",
"if",
"not",
"os",
".",
"path",
... | Ensures that a directory exits.
If it does not exist, it is automatically created. | [
"Ensures",
"that",
"a",
"directory",
"exits",
".",
"If",
"it",
"does",
"not",
"exist",
"it",
"is",
"automatically",
"created",
"."
] | 59c735281a95b44f6263a25f4d6ce24fca520082 | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/pathutil.py#L94-L105 | train | 56,029 |
BrianHicks/emit | emit/multilang.py | ShellNode.deserialize | def deserialize(self, msg):
'deserialize output to a Python object'
self.logger.debug('deserializing %s', msg)
return json.loads(msg) | python | def deserialize(self, msg):
'deserialize output to a Python object'
self.logger.debug('deserializing %s', msg)
return json.loads(msg) | [
"def",
"deserialize",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'deserializing %s'",
",",
"msg",
")",
"return",
"json",
".",
"loads",
"(",
"msg",
")"
] | deserialize output to a Python object | [
"deserialize",
"output",
"to",
"a",
"Python",
"object"
] | 19a86c2392b136c9e857000798ccaa525aa0ed84 | https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/multilang.py#L65-L68 | train | 56,030 |
HPCC-Cloud-Computing/CAL | calplus/utils.py | append_request_id | def append_request_id(req, resp, resource, params):
"""Append request id which got from response
header to resource.req_ids list.
"""
def get_headers(resp):
if hasattr(resp, 'headers'):
return resp.headers
if hasattr(resp, '_headers'):
return resp._headers
... | python | def append_request_id(req, resp, resource, params):
"""Append request id which got from response
header to resource.req_ids list.
"""
def get_headers(resp):
if hasattr(resp, 'headers'):
return resp.headers
if hasattr(resp, '_headers'):
return resp._headers
... | [
"def",
"append_request_id",
"(",
"req",
",",
"resp",
",",
"resource",
",",
"params",
")",
":",
"def",
"get_headers",
"(",
"resp",
")",
":",
"if",
"hasattr",
"(",
"resp",
",",
"'headers'",
")",
":",
"return",
"resp",
".",
"headers",
"if",
"hasattr",
"("... | Append request id which got from response
header to resource.req_ids list. | [
"Append",
"request",
"id",
"which",
"got",
"from",
"response",
"header",
"to",
"resource",
".",
"req_ids",
"list",
"."
] | 7134b3dfe9ee3a383506a592765c7a12fa4ca1e9 | https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/calplus/utils.py#L66-L90 | train | 56,031 |
HPCC-Cloud-Computing/CAL | calplus/utils.py | JSONResponseSerializer._sanitizer | def _sanitizer(self, obj):
"""Sanitizer method that will be passed to json.dumps."""
if isinstance(obj, datetime.datetime):
return obj.isoformat()
if hasattr(obj, "to_dict"):
return obj.to_dict()
return obj | python | def _sanitizer(self, obj):
"""Sanitizer method that will be passed to json.dumps."""
if isinstance(obj, datetime.datetime):
return obj.isoformat()
if hasattr(obj, "to_dict"):
return obj.to_dict()
return obj | [
"def",
"_sanitizer",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"obj",
".",
"isoformat",
"(",
")",
"if",
"hasattr",
"(",
"obj",
",",
"\"to_dict\"",
")",
":",
"return",
"obj... | Sanitizer method that will be passed to json.dumps. | [
"Sanitizer",
"method",
"that",
"will",
"be",
"passed",
"to",
"json",
".",
"dumps",
"."
] | 7134b3dfe9ee3a383506a592765c7a12fa4ca1e9 | https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/calplus/utils.py#L50-L56 | train | 56,032 |
e7dal/bubble3 | bubble3/util/cli_misc.py | make_uniq_for_step | def make_uniq_for_step(ctx, ukeys, step, stage, full_data, clean_missing_after_seconds, to_uniq):
"""initially just a copy from UNIQ_PULL"""
# TODO:
# this still seems to work ok for Storage types json/bubble,
# for DS we need to reload de dumped step to uniqify
if not ukeys:
return to_uni... | python | def make_uniq_for_step(ctx, ukeys, step, stage, full_data, clean_missing_after_seconds, to_uniq):
"""initially just a copy from UNIQ_PULL"""
# TODO:
# this still seems to work ok for Storage types json/bubble,
# for DS we need to reload de dumped step to uniqify
if not ukeys:
return to_uni... | [
"def",
"make_uniq_for_step",
"(",
"ctx",
",",
"ukeys",
",",
"step",
",",
"stage",
",",
"full_data",
",",
"clean_missing_after_seconds",
",",
"to_uniq",
")",
":",
"# TODO:",
"# this still seems to work ok for Storage types json/bubble,",
"# for DS we need to reload de dumped s... | initially just a copy from UNIQ_PULL | [
"initially",
"just",
"a",
"copy",
"from",
"UNIQ_PULL"
] | 59c735281a95b44f6263a25f4d6ce24fca520082 | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/bubble3/util/cli_misc.py#L217-L264 | train | 56,033 |
HPCC-Cloud-Computing/CAL | calplus/v1/compute/drivers/amazon.py | AmazonDriver.list_ip | def list_ip(self, instance_id):
"""Add all IPs"""
output = self.client.describe_instances(InstanceIds=[instance_id])
output = output.get("Reservations")[0].get("Instances")[0]
ips = {}
ips['PrivateIp'] = output.get("PrivateIpAddress")
ips['PublicIp'] = output.get("PublicI... | python | def list_ip(self, instance_id):
"""Add all IPs"""
output = self.client.describe_instances(InstanceIds=[instance_id])
output = output.get("Reservations")[0].get("Instances")[0]
ips = {}
ips['PrivateIp'] = output.get("PrivateIpAddress")
ips['PublicIp'] = output.get("PublicI... | [
"def",
"list_ip",
"(",
"self",
",",
"instance_id",
")",
":",
"output",
"=",
"self",
".",
"client",
".",
"describe_instances",
"(",
"InstanceIds",
"=",
"[",
"instance_id",
"]",
")",
"output",
"=",
"output",
".",
"get",
"(",
"\"Reservations\"",
")",
"[",
"... | Add all IPs | [
"Add",
"all",
"IPs"
] | 7134b3dfe9ee3a383506a592765c7a12fa4ca1e9 | https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/calplus/v1/compute/drivers/amazon.py#L131-L138 | train | 56,034 |
GeorgeArgyros/symautomata | symautomata/flex2fst.py | main | def main():
"""
Testing function for Flex Regular Expressions to FST DFA
"""
if len(argv) < 2:
print 'Usage: %s fst_file [optional: save_file]' % argv[0]
return
flex_a = Flexparser()
mma = flex_a.yyparse(argv[1])
mma.minimize()
print mma
if len(argv) == 3:
mma... | python | def main():
"""
Testing function for Flex Regular Expressions to FST DFA
"""
if len(argv) < 2:
print 'Usage: %s fst_file [optional: save_file]' % argv[0]
return
flex_a = Flexparser()
mma = flex_a.yyparse(argv[1])
mma.minimize()
print mma
if len(argv) == 3:
mma... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"argv",
")",
"<",
"2",
":",
"print",
"'Usage: %s fst_file [optional: save_file]'",
"%",
"argv",
"[",
"0",
"]",
"return",
"flex_a",
"=",
"Flexparser",
"(",
")",
"mma",
"=",
"flex_a",
".",
"yyparse",
"(",
"... | Testing function for Flex Regular Expressions to FST DFA | [
"Testing",
"function",
"for",
"Flex",
"Regular",
"Expressions",
"to",
"FST",
"DFA"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/flex2fst.py#L297-L309 | train | 56,035 |
Cadasta/django-tutelary | tutelary/mixins.py | PermissionRequiredMixin.has_permission | def has_permission(self):
"""Permission checking for "normal" Django."""
objs = [None]
if hasattr(self, 'get_perms_objects'):
objs = self.get_perms_objects()
else:
if hasattr(self, 'get_object'):
try:
objs = [self.get_object()]
... | python | def has_permission(self):
"""Permission checking for "normal" Django."""
objs = [None]
if hasattr(self, 'get_perms_objects'):
objs = self.get_perms_objects()
else:
if hasattr(self, 'get_object'):
try:
objs = [self.get_object()]
... | [
"def",
"has_permission",
"(",
"self",
")",
":",
"objs",
"=",
"[",
"None",
"]",
"if",
"hasattr",
"(",
"self",
",",
"'get_perms_objects'",
")",
":",
"objs",
"=",
"self",
".",
"get_perms_objects",
"(",
")",
"else",
":",
"if",
"hasattr",
"(",
"self",
",",
... | Permission checking for "normal" Django. | [
"Permission",
"checking",
"for",
"normal",
"Django",
"."
] | 66bb05de7098777c0a383410c287bf48433cde87 | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/mixins.py#L72-L97 | train | 56,036 |
Cadasta/django-tutelary | tutelary/mixins.py | APIPermissionRequiredMixin.check_permissions | def check_permissions(self, request):
"""Permission checking for DRF."""
objs = [None]
if hasattr(self, 'get_perms_objects'):
objs = self.get_perms_objects()
else:
if hasattr(self, 'get_object'):
try:
objs = [self.get_object()]
... | python | def check_permissions(self, request):
"""Permission checking for DRF."""
objs = [None]
if hasattr(self, 'get_perms_objects'):
objs = self.get_perms_objects()
else:
if hasattr(self, 'get_object'):
try:
objs = [self.get_object()]
... | [
"def",
"check_permissions",
"(",
"self",
",",
"request",
")",
":",
"objs",
"=",
"[",
"None",
"]",
"if",
"hasattr",
"(",
"self",
",",
"'get_perms_objects'",
")",
":",
"objs",
"=",
"self",
".",
"get_perms_objects",
"(",
")",
"else",
":",
"if",
"hasattr",
... | Permission checking for DRF. | [
"Permission",
"checking",
"for",
"DRF",
"."
] | 66bb05de7098777c0a383410c287bf48433cde87 | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/mixins.py#L146-L180 | train | 56,037 |
jaredLunde/redis_structures | redis_structures/__init__.py | BaseRedisStructure._hashed_key | def _hashed_key(self):
""" Returns 16-digit numeric hash of the redis key """
return abs(int(hashlib.md5(
self.key_prefix.encode('utf8')
).hexdigest(), 16)) % (10 ** (
self._size_mod if hasattr(self, '_size_mod') else 5)) | python | def _hashed_key(self):
""" Returns 16-digit numeric hash of the redis key """
return abs(int(hashlib.md5(
self.key_prefix.encode('utf8')
).hexdigest(), 16)) % (10 ** (
self._size_mod if hasattr(self, '_size_mod') else 5)) | [
"def",
"_hashed_key",
"(",
"self",
")",
":",
"return",
"abs",
"(",
"int",
"(",
"hashlib",
".",
"md5",
"(",
"self",
".",
"key_prefix",
".",
"encode",
"(",
"'utf8'",
")",
")",
".",
"hexdigest",
"(",
")",
",",
"16",
")",
")",
"%",
"(",
"10",
"**",
... | Returns 16-digit numeric hash of the redis key | [
"Returns",
"16",
"-",
"digit",
"numeric",
"hash",
"of",
"the",
"redis",
"key"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L165-L170 | train | 56,038 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisMap.update | def update(self, data):
""" Set given keys to their respective values
@data: #dict or :class:RedisMap of |{key: value}| entries to set
"""
if not data:
return
_rk, _dumps = self.get_key, self._dumps
data = self._client.mset({
_rk(key): _dumps(v... | python | def update(self, data):
""" Set given keys to their respective values
@data: #dict or :class:RedisMap of |{key: value}| entries to set
"""
if not data:
return
_rk, _dumps = self.get_key, self._dumps
data = self._client.mset({
_rk(key): _dumps(v... | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"_rk",
",",
"_dumps",
"=",
"self",
".",
"get_key",
",",
"self",
".",
"_dumps",
"data",
"=",
"self",
".",
"_client",
".",
"mset",
"(",
"{",
"_rk",
"(",
"key",... | Set given keys to their respective values
@data: #dict or :class:RedisMap of |{key: value}| entries to set | [
"Set",
"given",
"keys",
"to",
"their",
"respective",
"values"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L417-L426 | train | 56,039 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisMap.expire_at | def expire_at(self, key, _time):
""" Sets the expiration time of @key to @_time
@_time: absolute Unix timestamp (seconds since January 1, 1970)
"""
return self._client.expireat(self.get_key(key), round(_time)) | python | def expire_at(self, key, _time):
""" Sets the expiration time of @key to @_time
@_time: absolute Unix timestamp (seconds since January 1, 1970)
"""
return self._client.expireat(self.get_key(key), round(_time)) | [
"def",
"expire_at",
"(",
"self",
",",
"key",
",",
"_time",
")",
":",
"return",
"self",
".",
"_client",
".",
"expireat",
"(",
"self",
".",
"get_key",
"(",
"key",
")",
",",
"round",
"(",
"_time",
")",
")"
] | Sets the expiration time of @key to @_time
@_time: absolute Unix timestamp (seconds since January 1, 1970) | [
"Sets",
"the",
"expiration",
"time",
"of"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L453-L457 | train | 56,040 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisDict._bucket_key | def _bucket_key(self):
""" Returns hash bucket key for the redis key """
return "{}.size.{}".format(
self.prefix, (self._hashed_key//1000)
if self._hashed_key > 1000 else self._hashed_key) | python | def _bucket_key(self):
""" Returns hash bucket key for the redis key """
return "{}.size.{}".format(
self.prefix, (self._hashed_key//1000)
if self._hashed_key > 1000 else self._hashed_key) | [
"def",
"_bucket_key",
"(",
"self",
")",
":",
"return",
"\"{}.size.{}\"",
".",
"format",
"(",
"self",
".",
"prefix",
",",
"(",
"self",
".",
"_hashed_key",
"//",
"1000",
")",
"if",
"self",
".",
"_hashed_key",
">",
"1000",
"else",
"self",
".",
"_hashed_key"... | Returns hash bucket key for the redis key | [
"Returns",
"hash",
"bucket",
"key",
"for",
"the",
"redis",
"key"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L708-L712 | train | 56,041 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisList.reverse_iter | def reverse_iter(self, start=None, stop=None, count=2000):
""" -> yields items of the list in reverse """
cursor = '0'
count = 1000
start = start if start is not None else (-1 * count)
stop = stop if stop is not None else -1
_loads = self._loads
while cursor:
... | python | def reverse_iter(self, start=None, stop=None, count=2000):
""" -> yields items of the list in reverse """
cursor = '0'
count = 1000
start = start if start is not None else (-1 * count)
stop = stop if stop is not None else -1
_loads = self._loads
while cursor:
... | [
"def",
"reverse_iter",
"(",
"self",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"count",
"=",
"2000",
")",
":",
"cursor",
"=",
"'0'",
"count",
"=",
"1000",
"start",
"=",
"start",
"if",
"start",
"is",
"not",
"None",
"else",
"(",
"-",
... | -> yields items of the list in reverse | [
"-",
">",
"yields",
"items",
"of",
"the",
"list",
"in",
"reverse"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L1350-L1362 | train | 56,042 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisList.pop | def pop(self, index=None):
""" Removes and returns the item at @index or from the end of the list
-> item at @index
"""
if index is None:
return self._loads(self._client.rpop(self.key_prefix))
elif index == 0:
return self._loads(self._client.lpop(self.... | python | def pop(self, index=None):
""" Removes and returns the item at @index or from the end of the list
-> item at @index
"""
if index is None:
return self._loads(self._client.rpop(self.key_prefix))
elif index == 0:
return self._loads(self._client.lpop(self.... | [
"def",
"pop",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"return",
"self",
".",
"_loads",
"(",
"self",
".",
"_client",
".",
"rpop",
"(",
"self",
".",
"key_prefix",
")",
")",
"elif",
"index",
"==",
"0",
":"... | Removes and returns the item at @index or from the end of the list
-> item at @index | [
"Removes",
"and",
"returns",
"the",
"item",
"at"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L1387-L1400 | train | 56,043 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisList.count | def count(self, value):
""" Not recommended for use on large lists due to time
complexity, but it works. Use with caution.
-> #int number of occurences of @value
"""
cnt = 0
for x in self:
if x == value:
cnt += 1
return cnt | python | def count(self, value):
""" Not recommended for use on large lists due to time
complexity, but it works. Use with caution.
-> #int number of occurences of @value
"""
cnt = 0
for x in self:
if x == value:
cnt += 1
return cnt | [
"def",
"count",
"(",
"self",
",",
"value",
")",
":",
"cnt",
"=",
"0",
"for",
"x",
"in",
"self",
":",
"if",
"x",
"==",
"value",
":",
"cnt",
"+=",
"1",
"return",
"cnt"
] | Not recommended for use on large lists due to time
complexity, but it works. Use with caution.
-> #int number of occurences of @value | [
"Not",
"recommended",
"for",
"use",
"on",
"large",
"lists",
"due",
"to",
"time",
"complexity",
"but",
"it",
"works",
".",
"Use",
"with",
"caution",
"."
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L1417-L1427 | train | 56,044 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisList.push | def push(self, *items):
""" Prepends the list with @items
-> #int length of list after operation
"""
if self.serialized:
items = list(map(self._dumps, items))
return self._client.lpush(self.key_prefix, *items) | python | def push(self, *items):
""" Prepends the list with @items
-> #int length of list after operation
"""
if self.serialized:
items = list(map(self._dumps, items))
return self._client.lpush(self.key_prefix, *items) | [
"def",
"push",
"(",
"self",
",",
"*",
"items",
")",
":",
"if",
"self",
".",
"serialized",
":",
"items",
"=",
"list",
"(",
"map",
"(",
"self",
".",
"_dumps",
",",
"items",
")",
")",
"return",
"self",
".",
"_client",
".",
"lpush",
"(",
"self",
".",... | Prepends the list with @items
-> #int length of list after operation | [
"Prepends",
"the",
"list",
"with"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L1429-L1435 | train | 56,045 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisList.index | def index(self, item):
""" Not recommended for use on large lists due to time
complexity, but it works
-> #int list index of @item
"""
for i, x in enumerate(self.iter()):
if x == item:
return i
return None | python | def index(self, item):
""" Not recommended for use on large lists due to time
complexity, but it works
-> #int list index of @item
"""
for i, x in enumerate(self.iter()):
if x == item:
return i
return None | [
"def",
"index",
"(",
"self",
",",
"item",
")",
":",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"self",
".",
"iter",
"(",
")",
")",
":",
"if",
"x",
"==",
"item",
":",
"return",
"i",
"return",
"None"
] | Not recommended for use on large lists due to time
complexity, but it works
-> #int list index of @item | [
"Not",
"recommended",
"for",
"use",
"on",
"large",
"lists",
"due",
"to",
"time",
"complexity",
"but",
"it",
"works"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L1437-L1446 | train | 56,046 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisSet.intersection | def intersection(self, *others):
""" Calculates the intersection of all the given sets, that is, members
which are present in all given sets.
@others: one or several #str keynames or :class:RedisSet objects
-> #set of resulting intersection between @others and this set
... | python | def intersection(self, *others):
""" Calculates the intersection of all the given sets, that is, members
which are present in all given sets.
@others: one or several #str keynames or :class:RedisSet objects
-> #set of resulting intersection between @others and this set
... | [
"def",
"intersection",
"(",
"self",
",",
"*",
"others",
")",
":",
"others",
"=",
"self",
".",
"_typesafe_others",
"(",
"others",
")",
"return",
"set",
"(",
"map",
"(",
"self",
".",
"_loads",
",",
"self",
".",
"_client",
".",
"sinter",
"(",
"self",
".... | Calculates the intersection of all the given sets, that is, members
which are present in all given sets.
@others: one or several #str keynames or :class:RedisSet objects
-> #set of resulting intersection between @others and this set | [
"Calculates",
"the",
"intersection",
"of",
"all",
"the",
"given",
"sets",
"that",
"is",
"members",
"which",
"are",
"present",
"in",
"all",
"given",
"sets",
"."
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L1741-L1751 | train | 56,047 |
jaredLunde/redis_structures | redis_structures/__init__.py | RedisSortedSet.rank | def rank(self, member):
""" Gets the ASC rank of @member from the sorted set, that is,
lower scores have lower ranks
"""
if self.reversed:
return self._client.zrevrank(self.key_prefix, self._dumps(member))
return self._client.zrank(self.key_prefix, self._dumps(mem... | python | def rank(self, member):
""" Gets the ASC rank of @member from the sorted set, that is,
lower scores have lower ranks
"""
if self.reversed:
return self._client.zrevrank(self.key_prefix, self._dumps(member))
return self._client.zrank(self.key_prefix, self._dumps(mem... | [
"def",
"rank",
"(",
"self",
",",
"member",
")",
":",
"if",
"self",
".",
"reversed",
":",
"return",
"self",
".",
"_client",
".",
"zrevrank",
"(",
"self",
".",
"key_prefix",
",",
"self",
".",
"_dumps",
"(",
"member",
")",
")",
"return",
"self",
".",
... | Gets the ASC rank of @member from the sorted set, that is,
lower scores have lower ranks | [
"Gets",
"the",
"ASC",
"rank",
"of"
] | b9cce5f5c85db5e12c292633ff8d04e3ae053294 | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L2102-L2108 | train | 56,048 |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | recv_blocking | def recv_blocking(conn, msglen):
"""Recieve data until msglen bytes have been received."""
msg = b''
while len(msg) < msglen:
maxlen = msglen-len(msg)
if maxlen > 4096:
maxlen = 4096
tmpmsg = conn.recv(maxlen)
if not tmpmsg:
raise RuntimeError("socket ... | python | def recv_blocking(conn, msglen):
"""Recieve data until msglen bytes have been received."""
msg = b''
while len(msg) < msglen:
maxlen = msglen-len(msg)
if maxlen > 4096:
maxlen = 4096
tmpmsg = conn.recv(maxlen)
if not tmpmsg:
raise RuntimeError("socket ... | [
"def",
"recv_blocking",
"(",
"conn",
",",
"msglen",
")",
":",
"msg",
"=",
"b''",
"while",
"len",
"(",
"msg",
")",
"<",
"msglen",
":",
"maxlen",
"=",
"msglen",
"-",
"len",
"(",
"msg",
")",
"if",
"maxlen",
">",
"4096",
":",
"maxlen",
"=",
"4096",
"... | Recieve data until msglen bytes have been received. | [
"Recieve",
"data",
"until",
"msglen",
"bytes",
"have",
"been",
"received",
"."
] | 275de1e71ed05c6acff1a5fa87f754f4d385a372 | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L52-L65 | train | 56,049 |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | compare_password | def compare_password(expected, actual):
"""Compare two 64byte encoded passwords."""
if expected == actual:
return True, "OK"
msg = []
ver_exp = expected[-8:].rstrip()
ver_act = actual[-8:].rstrip()
if expected[:-8] != actual[:-8]:
msg.append("Password mismatch")
if ver_exp !... | python | def compare_password(expected, actual):
"""Compare two 64byte encoded passwords."""
if expected == actual:
return True, "OK"
msg = []
ver_exp = expected[-8:].rstrip()
ver_act = actual[-8:].rstrip()
if expected[:-8] != actual[:-8]:
msg.append("Password mismatch")
if ver_exp !... | [
"def",
"compare_password",
"(",
"expected",
",",
"actual",
")",
":",
"if",
"expected",
"==",
"actual",
":",
"return",
"True",
",",
"\"OK\"",
"msg",
"=",
"[",
"]",
"ver_exp",
"=",
"expected",
"[",
"-",
"8",
":",
"]",
".",
"rstrip",
"(",
")",
"ver_act"... | Compare two 64byte encoded passwords. | [
"Compare",
"two",
"64byte",
"encoded",
"passwords",
"."
] | 275de1e71ed05c6acff1a5fa87f754f4d385a372 | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L74-L87 | train | 56,050 |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | encode_to_sha | def encode_to_sha(msg):
"""coerce numeric list inst sha-looking bytearray"""
if isinstance(msg, str):
msg = msg.encode('utf-8')
return (codecs.encode(msg, "hex_codec") + (b'00' * 32))[:64] | python | def encode_to_sha(msg):
"""coerce numeric list inst sha-looking bytearray"""
if isinstance(msg, str):
msg = msg.encode('utf-8')
return (codecs.encode(msg, "hex_codec") + (b'00' * 32))[:64] | [
"def",
"encode_to_sha",
"(",
"msg",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"str",
")",
":",
"msg",
"=",
"msg",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"(",
"codecs",
".",
"encode",
"(",
"msg",
",",
"\"hex_codec\"",
")",
"+",
"(",
"b'0... | coerce numeric list inst sha-looking bytearray | [
"coerce",
"numeric",
"list",
"inst",
"sha",
"-",
"looking",
"bytearray"
] | 275de1e71ed05c6acff1a5fa87f754f4d385a372 | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L90-L94 | train | 56,051 |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | decode_from_sha | def decode_from_sha(sha):
"""convert coerced sha back into numeric list"""
if isinstance(sha, str):
sha = sha.encode('utf-8')
return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec") | python | def decode_from_sha(sha):
"""convert coerced sha back into numeric list"""
if isinstance(sha, str):
sha = sha.encode('utf-8')
return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec") | [
"def",
"decode_from_sha",
"(",
"sha",
")",
":",
"if",
"isinstance",
"(",
"sha",
",",
"str",
")",
":",
"sha",
"=",
"sha",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"codecs",
".",
"decode",
"(",
"re",
".",
"sub",
"(",
"rb'(00)*$'",
",",
"b''",
",... | convert coerced sha back into numeric list | [
"convert",
"coerced",
"sha",
"back",
"into",
"numeric",
"list"
] | 275de1e71ed05c6acff1a5fa87f754f4d385a372 | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L97-L101 | train | 56,052 |
jplusplus/statscraper | statscraper/scrapers/PXWebScraper.py | PXWeb._api_path | def _api_path(self, item):
"""Get the API path for the current cursor position."""
if self.base_url is None:
raise NotImplementedError("base_url not set")
path = "/".join([x.blob["id"] for x in item.path])
return "/".join([self.base_url, path]) | python | def _api_path(self, item):
"""Get the API path for the current cursor position."""
if self.base_url is None:
raise NotImplementedError("base_url not set")
path = "/".join([x.blob["id"] for x in item.path])
return "/".join([self.base_url, path]) | [
"def",
"_api_path",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
".",
"base_url",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"base_url not set\"",
")",
"path",
"=",
"\"/\"",
".",
"join",
"(",
"[",
"x",
".",
"blob",
"[",
"\"id\"",
"]... | Get the API path for the current cursor position. | [
"Get",
"the",
"API",
"path",
"for",
"the",
"current",
"cursor",
"position",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/PXWebScraper.py#L31-L36 | train | 56,053 |
pauleveritt/kaybee | kaybee/plugins/references/handlers.py | register_references | def register_references(kb_app: kb,
sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docnames: List[str]):
""" Walk the registry and add sphinx directives """
references: ReferencesContainer = sphinx_app.env.references
for name, klas... | python | def register_references(kb_app: kb,
sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docnames: List[str]):
""" Walk the registry and add sphinx directives """
references: ReferencesContainer = sphinx_app.env.references
for name, klas... | [
"def",
"register_references",
"(",
"kb_app",
":",
"kb",
",",
"sphinx_app",
":",
"Sphinx",
",",
"sphinx_env",
":",
"BuildEnvironment",
",",
"docnames",
":",
"List",
"[",
"str",
"]",
")",
":",
"references",
":",
"ReferencesContainer",
"=",
"sphinx_app",
".",
"... | Walk the registry and add sphinx directives | [
"Walk",
"the",
"registry",
"and",
"add",
"sphinx",
"directives"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/references/handlers.py#L25-L37 | train | 56,054 |
invinst/ResponseBot | responsebot/listeners/responsebot_listener.py | ResponseBotListener.register_handlers | def register_handlers(self, handler_classes):
"""
Create handlers from discovered handler classes
:param handler_classes: List of :class:`~responsebot.handlers.base.BaseTweetHandler`'s derived classes
"""
for handler_class in handler_classes:
self.handlers.append(han... | python | def register_handlers(self, handler_classes):
"""
Create handlers from discovered handler classes
:param handler_classes: List of :class:`~responsebot.handlers.base.BaseTweetHandler`'s derived classes
"""
for handler_class in handler_classes:
self.handlers.append(han... | [
"def",
"register_handlers",
"(",
"self",
",",
"handler_classes",
")",
":",
"for",
"handler_class",
"in",
"handler_classes",
":",
"self",
".",
"handlers",
".",
"append",
"(",
"handler_class",
"(",
"client",
"=",
"self",
".",
"client",
")",
")",
"logging",
"."... | Create handlers from discovered handler classes
:param handler_classes: List of :class:`~responsebot.handlers.base.BaseTweetHandler`'s derived classes | [
"Create",
"handlers",
"from",
"discovered",
"handler",
"classes"
] | a6b1a431a343007f7ae55a193e432a61af22253f | https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/listeners/responsebot_listener.py#L23-L33 | train | 56,055 |
invinst/ResponseBot | responsebot/listeners/responsebot_listener.py | ResponseBotListener.get_merged_filter | def get_merged_filter(self):
"""
Return merged filter from list of handlers
:return: merged filter
:rtype: :class:`~responsebot.models.TweetFilter`
"""
track = set()
follow = set()
for handler in self.handlers:
track.update(handler.filter.tra... | python | def get_merged_filter(self):
"""
Return merged filter from list of handlers
:return: merged filter
:rtype: :class:`~responsebot.models.TweetFilter`
"""
track = set()
follow = set()
for handler in self.handlers:
track.update(handler.filter.tra... | [
"def",
"get_merged_filter",
"(",
"self",
")",
":",
"track",
"=",
"set",
"(",
")",
"follow",
"=",
"set",
"(",
")",
"for",
"handler",
"in",
"self",
".",
"handlers",
":",
"track",
".",
"update",
"(",
"handler",
".",
"filter",
".",
"track",
")",
"follow"... | Return merged filter from list of handlers
:return: merged filter
:rtype: :class:`~responsebot.models.TweetFilter` | [
"Return",
"merged",
"filter",
"from",
"list",
"of",
"handlers"
] | a6b1a431a343007f7ae55a193e432a61af22253f | https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/listeners/responsebot_listener.py#L75-L89 | train | 56,056 |
MacHu-GWU/crawlib-project | crawlib/util.py | get_domain | def get_domain(url):
"""
Get domain part of an url.
For example: https://www.python.org/doc/ -> https://www.python.org
"""
parse_result = urlparse(url)
domain = "{schema}://{netloc}".format(
schema=parse_result.scheme, netloc=parse_result.netloc)
return domain | python | def get_domain(url):
"""
Get domain part of an url.
For example: https://www.python.org/doc/ -> https://www.python.org
"""
parse_result = urlparse(url)
domain = "{schema}://{netloc}".format(
schema=parse_result.scheme, netloc=parse_result.netloc)
return domain | [
"def",
"get_domain",
"(",
"url",
")",
":",
"parse_result",
"=",
"urlparse",
"(",
"url",
")",
"domain",
"=",
"\"{schema}://{netloc}\"",
".",
"format",
"(",
"schema",
"=",
"parse_result",
".",
"scheme",
",",
"netloc",
"=",
"parse_result",
".",
"netloc",
")",
... | Get domain part of an url.
For example: https://www.python.org/doc/ -> https://www.python.org | [
"Get",
"domain",
"part",
"of",
"an",
"url",
"."
] | 241516f2a7a0a32c692f7af35a1f44064e8ce1ab | https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/util.py#L24-L33 | train | 56,057 |
MacHu-GWU/crawlib-project | crawlib/util.py | join_all | def join_all(domain, *parts):
"""
Join all url components.
Example::
>>> join_all("https://www.apple.com", "iphone")
https://www.apple.com/iphone
:param domain: Domain parts, example: https://www.python.org
:param parts: Other parts, example: "/doc", "/py27"
:return: url
"... | python | def join_all(domain, *parts):
"""
Join all url components.
Example::
>>> join_all("https://www.apple.com", "iphone")
https://www.apple.com/iphone
:param domain: Domain parts, example: https://www.python.org
:param parts: Other parts, example: "/doc", "/py27"
:return: url
"... | [
"def",
"join_all",
"(",
"domain",
",",
"*",
"parts",
")",
":",
"l",
"=",
"list",
"(",
")",
"if",
"domain",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"domain",
"=",
"domain",
"[",
":",
"-",
"1",
"]",
"l",
".",
"append",
"(",
"domain",
")",
"for",... | Join all url components.
Example::
>>> join_all("https://www.apple.com", "iphone")
https://www.apple.com/iphone
:param domain: Domain parts, example: https://www.python.org
:param parts: Other parts, example: "/doc", "/py27"
:return: url | [
"Join",
"all",
"url",
"components",
"."
] | 241516f2a7a0a32c692f7af35a1f44064e8ce1ab | https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/util.py#L36-L60 | train | 56,058 |
nicferrier/md | src/mdlib/pull.py | _list_remote | def _list_remote(store, maildir, verbose=False):
"""List the a maildir.
store is an abstract representation of the source maildir.
maildir is the local maildir to which mail will be pulled.
This is a generator for a reason. Because of the way ssh
multi-mastering works a single open TCP connectio... | python | def _list_remote(store, maildir, verbose=False):
"""List the a maildir.
store is an abstract representation of the source maildir.
maildir is the local maildir to which mail will be pulled.
This is a generator for a reason. Because of the way ssh
multi-mastering works a single open TCP connectio... | [
"def",
"_list_remote",
"(",
"store",
",",
"maildir",
",",
"verbose",
"=",
"False",
")",
":",
"# This command produces a list of all files in the maildir like:",
"# base-filename timestamp container-directory",
"command",
"=",
"\"\"\"echo {maildir}/{{cur,new}} | tr ' ' '\\\\n' | whi... | List the a maildir.
store is an abstract representation of the source maildir.
maildir is the local maildir to which mail will be pulled.
This is a generator for a reason. Because of the way ssh
multi-mastering works a single open TCP connection allows multiple
virtual ssh connections. So the en... | [
"List",
"the",
"a",
"maildir",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/pull.py#L96-L120 | train | 56,059 |
nicferrier/md | src/mdlib/pull.py | sshpull | def sshpull(host, maildir, localmaildir, noop=False, verbose=False, filterfile=None):
"""Pull a remote maildir to the local one.
"""
store = _SSHStore(host, maildir)
_pull(store, localmaildir, noop, verbose, filterfile) | python | def sshpull(host, maildir, localmaildir, noop=False, verbose=False, filterfile=None):
"""Pull a remote maildir to the local one.
"""
store = _SSHStore(host, maildir)
_pull(store, localmaildir, noop, verbose, filterfile) | [
"def",
"sshpull",
"(",
"host",
",",
"maildir",
",",
"localmaildir",
",",
"noop",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"filterfile",
"=",
"None",
")",
":",
"store",
"=",
"_SSHStore",
"(",
"host",
",",
"maildir",
")",
"_pull",
"(",
"store",
... | Pull a remote maildir to the local one. | [
"Pull",
"a",
"remote",
"maildir",
"to",
"the",
"local",
"one",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/pull.py#L122-L126 | train | 56,060 |
nicferrier/md | src/mdlib/pull.py | filepull | def filepull(maildir, localmaildir, noop=False, verbose=False, filterfile=None):
"""Pull one local maildir into another.
The source need not be an md folder (it need not have a store). In
this case filepull is kind of an import.
"""
store = _Store(maildir)
_pull(store, localmaildir, noop, verbo... | python | def filepull(maildir, localmaildir, noop=False, verbose=False, filterfile=None):
"""Pull one local maildir into another.
The source need not be an md folder (it need not have a store). In
this case filepull is kind of an import.
"""
store = _Store(maildir)
_pull(store, localmaildir, noop, verbo... | [
"def",
"filepull",
"(",
"maildir",
",",
"localmaildir",
",",
"noop",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"filterfile",
"=",
"None",
")",
":",
"store",
"=",
"_Store",
"(",
"maildir",
")",
"_pull",
"(",
"store",
",",
"localmaildir",
",",
"no... | Pull one local maildir into another.
The source need not be an md folder (it need not have a store). In
this case filepull is kind of an import. | [
"Pull",
"one",
"local",
"maildir",
"into",
"another",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/pull.py#L128-L135 | train | 56,061 |
nicferrier/md | src/mdlib/pull.py | _filter | def _filter(msgdata, mailparser, mdfolder, mailfilters):
"""Filter msgdata by mailfilters"""
if mailfilters:
for f in mailfilters:
msg = mailparser.parse(StringIO(msgdata))
rule = f(msg, folder=mdfolder)
if rule:
yield rule
return | python | def _filter(msgdata, mailparser, mdfolder, mailfilters):
"""Filter msgdata by mailfilters"""
if mailfilters:
for f in mailfilters:
msg = mailparser.parse(StringIO(msgdata))
rule = f(msg, folder=mdfolder)
if rule:
yield rule
return | [
"def",
"_filter",
"(",
"msgdata",
",",
"mailparser",
",",
"mdfolder",
",",
"mailfilters",
")",
":",
"if",
"mailfilters",
":",
"for",
"f",
"in",
"mailfilters",
":",
"msg",
"=",
"mailparser",
".",
"parse",
"(",
"StringIO",
"(",
"msgdata",
")",
")",
"rule",... | Filter msgdata by mailfilters | [
"Filter",
"msgdata",
"by",
"mailfilters"
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/pull.py#L144-L152 | train | 56,062 |
nicferrier/md | src/mdlib/pull.py | _SSHStore.cmd | def cmd(self, cmd, verbose=False):
"""Executes the specified command on the remote host.
The cmd must be format safe, this means { and } must be doubled, thusly:
echo /var/local/maildir/{{cur,new}}
the cmd can include the format word 'maildir' to be replaced
by self.director... | python | def cmd(self, cmd, verbose=False):
"""Executes the specified command on the remote host.
The cmd must be format safe, this means { and } must be doubled, thusly:
echo /var/local/maildir/{{cur,new}}
the cmd can include the format word 'maildir' to be replaced
by self.director... | [
"def",
"cmd",
"(",
"self",
",",
"cmd",
",",
"verbose",
"=",
"False",
")",
":",
"command",
"=",
"cmd",
".",
"format",
"(",
"maildir",
"=",
"self",
".",
"directory",
")",
"if",
"verbose",
":",
"print",
"(",
"command",
")",
"p",
"=",
"Popen",
"(",
"... | Executes the specified command on the remote host.
The cmd must be format safe, this means { and } must be doubled, thusly:
echo /var/local/maildir/{{cur,new}}
the cmd can include the format word 'maildir' to be replaced
by self.directory. eg:
echo {maildir}/{{cur,new}} | [
"Executes",
"the",
"specified",
"command",
"on",
"the",
"remote",
"host",
"."
] | 302ca8882dae060fb15bd5ae470d8e661fb67ec4 | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/pull.py#L37-L59 | train | 56,063 |
sharibarboza/py_zap | py_zap/search.py | SearchDaily.fetch_result | def fetch_result(self):
"""Return a list of urls for each search result."""
results = self.soup.find_all('div', {'class': 'container container-small'})
href = None
is_match = False
i = 0
while i < len(results) and not is_match:
result = results[i]
... | python | def fetch_result(self):
"""Return a list of urls for each search result."""
results = self.soup.find_all('div', {'class': 'container container-small'})
href = None
is_match = False
i = 0
while i < len(results) and not is_match:
result = results[i]
... | [
"def",
"fetch_result",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"soup",
".",
"find_all",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'container container-small'",
"}",
")",
"href",
"=",
"None",
"is_match",
"=",
"False",
"i",
"=",
"0",
"while",
... | Return a list of urls for each search result. | [
"Return",
"a",
"list",
"of",
"urls",
"for",
"each",
"search",
"result",
"."
] | ce90853efcad66d3e28b8f1ac910f275349d016c | https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/search.py#L40-L64 | train | 56,064 |
sharibarboza/py_zap | py_zap/search.py | SearchDaily._filter_results | def _filter_results(self, result, anchor):
"""Filter search results by checking category titles and dates"""
valid = True
try:
cat_tag = result.find('a', {'rel': 'category tag'}).string
title = anchor.string.lower()
date_tag = result.find('time').string
... | python | def _filter_results(self, result, anchor):
"""Filter search results by checking category titles and dates"""
valid = True
try:
cat_tag = result.find('a', {'rel': 'category tag'}).string
title = anchor.string.lower()
date_tag = result.find('time').string
... | [
"def",
"_filter_results",
"(",
"self",
",",
"result",
",",
"anchor",
")",
":",
"valid",
"=",
"True",
"try",
":",
"cat_tag",
"=",
"result",
".",
"find",
"(",
"'a'",
",",
"{",
"'rel'",
":",
"'category tag'",
"}",
")",
".",
"string",
"title",
"=",
"anch... | Filter search results by checking category titles and dates | [
"Filter",
"search",
"results",
"by",
"checking",
"category",
"titles",
"and",
"dates"
] | ce90853efcad66d3e28b8f1ac910f275349d016c | https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/search.py#L66-L86 | train | 56,065 |
sharibarboza/py_zap | py_zap/search.py | SearchDaily._build_url | def _build_url(self):
"""Build url based on searching by date or by show."""
url_params = [
BASE_URL, self.category + ' ratings', self.day, self.year, self.month
]
return SEARCH_URL.format(*url_params) | python | def _build_url(self):
"""Build url based on searching by date or by show."""
url_params = [
BASE_URL, self.category + ' ratings', self.day, self.year, self.month
]
return SEARCH_URL.format(*url_params) | [
"def",
"_build_url",
"(",
"self",
")",
":",
"url_params",
"=",
"[",
"BASE_URL",
",",
"self",
".",
"category",
"+",
"' ratings'",
",",
"self",
".",
"day",
",",
"self",
".",
"year",
",",
"self",
".",
"month",
"]",
"return",
"SEARCH_URL",
".",
"format",
... | Build url based on searching by date or by show. | [
"Build",
"url",
"based",
"on",
"searching",
"by",
"date",
"or",
"by",
"show",
"."
] | ce90853efcad66d3e28b8f1ac910f275349d016c | https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/search.py#L88-L94 | train | 56,066 |
sharibarboza/py_zap | py_zap/search.py | SearchDaily._assert_category | def _assert_category(self, category):
"""Validate category argument"""
category = category.lower()
valid_categories = ['cable', 'broadcast', 'final', 'tv']
assert_msg = "%s is not a valid category." % (category)
assert (category in valid_categories), assert_msg | python | def _assert_category(self, category):
"""Validate category argument"""
category = category.lower()
valid_categories = ['cable', 'broadcast', 'final', 'tv']
assert_msg = "%s is not a valid category." % (category)
assert (category in valid_categories), assert_msg | [
"def",
"_assert_category",
"(",
"self",
",",
"category",
")",
":",
"category",
"=",
"category",
".",
"lower",
"(",
")",
"valid_categories",
"=",
"[",
"'cable'",
",",
"'broadcast'",
",",
"'final'",
",",
"'tv'",
"]",
"assert_msg",
"=",
"\"%s is not a valid categ... | Validate category argument | [
"Validate",
"category",
"argument"
] | ce90853efcad66d3e28b8f1ac910f275349d016c | https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/search.py#L96-L101 | train | 56,067 |
rogerhil/thegamesdb | thegamesdb/api.py | TheGamesDb.get_data | def get_data(self, path, **params):
""" Giving a service path and optional specific arguments, returns
the XML data from the API parsed as a dict structure.
"""
xml = self.get_response(path, **params)
try:
return parse(xml)
except Exception as err:
... | python | def get_data(self, path, **params):
""" Giving a service path and optional specific arguments, returns
the XML data from the API parsed as a dict structure.
"""
xml = self.get_response(path, **params)
try:
return parse(xml)
except Exception as err:
... | [
"def",
"get_data",
"(",
"self",
",",
"path",
",",
"*",
"*",
"params",
")",
":",
"xml",
"=",
"self",
".",
"get_response",
"(",
"path",
",",
"*",
"*",
"params",
")",
"try",
":",
"return",
"parse",
"(",
"xml",
")",
"except",
"Exception",
"as",
"err",
... | Giving a service path and optional specific arguments, returns
the XML data from the API parsed as a dict structure. | [
"Giving",
"a",
"service",
"path",
"and",
"optional",
"specific",
"arguments",
"returns",
"the",
"XML",
"data",
"from",
"the",
"API",
"parsed",
"as",
"a",
"dict",
"structure",
"."
] | 795314215f9ee73697c7520dea4ddecfb23ca8e6 | https://github.com/rogerhil/thegamesdb/blob/795314215f9ee73697c7520dea4ddecfb23ca8e6/thegamesdb/api.py#L120-L131 | train | 56,068 |
langloisjp/tornado-logging-app | tornadoutil.py | LoggingApplication.run | def run(self, port): # pragma: no coverage
"""
Run on given port. Parse standard options and start the http server.
"""
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(self)
http_server.listen(port)
tornado.ioloop.IOLoop.instance()... | python | def run(self, port): # pragma: no coverage
"""
Run on given port. Parse standard options and start the http server.
"""
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(self)
http_server.listen(port)
tornado.ioloop.IOLoop.instance()... | [
"def",
"run",
"(",
"self",
",",
"port",
")",
":",
"# pragma: no coverage",
"tornado",
".",
"options",
".",
"parse_command_line",
"(",
")",
"http_server",
"=",
"tornado",
".",
"httpserver",
".",
"HTTPServer",
"(",
"self",
")",
"http_server",
".",
"listen",
"(... | Run on given port. Parse standard options and start the http server. | [
"Run",
"on",
"given",
"port",
".",
"Parse",
"standard",
"options",
"and",
"start",
"the",
"http",
"server",
"."
] | 02505b8a5bef782f9b67120874355b64f1b3e81a | https://github.com/langloisjp/tornado-logging-app/blob/02505b8a5bef782f9b67120874355b64f1b3e81a/tornadoutil.py#L46-L53 | train | 56,069 |
langloisjp/tornado-logging-app | tornadoutil.py | LoggingApplication.log_request | def log_request(self, handler):
"""
Override base method to log requests to JSON UDP collector and emit
a metric.
"""
packet = {'method': handler.request.method,
'uri': handler.request.uri,
'remote_ip': handler.request.remote_ip,
... | python | def log_request(self, handler):
"""
Override base method to log requests to JSON UDP collector and emit
a metric.
"""
packet = {'method': handler.request.method,
'uri': handler.request.uri,
'remote_ip': handler.request.remote_ip,
... | [
"def",
"log_request",
"(",
"self",
",",
"handler",
")",
":",
"packet",
"=",
"{",
"'method'",
":",
"handler",
".",
"request",
".",
"method",
",",
"'uri'",
":",
"handler",
".",
"request",
".",
"uri",
",",
"'remote_ip'",
":",
"handler",
".",
"request",
".... | Override base method to log requests to JSON UDP collector and emit
a metric. | [
"Override",
"base",
"method",
"to",
"log",
"requests",
"to",
"JSON",
"UDP",
"collector",
"and",
"emit",
"a",
"metric",
"."
] | 02505b8a5bef782f9b67120874355b64f1b3e81a | https://github.com/langloisjp/tornado-logging-app/blob/02505b8a5bef782f9b67120874355b64f1b3e81a/tornadoutil.py#L55-L80 | train | 56,070 |
langloisjp/tornado-logging-app | tornadoutil.py | RequestHandler.logvalue | def logvalue(self, key, value):
"""Add log entry to request log info"""
if not hasattr(self, 'logvalues'):
self.logvalues = {}
self.logvalues[key] = value | python | def logvalue(self, key, value):
"""Add log entry to request log info"""
if not hasattr(self, 'logvalues'):
self.logvalues = {}
self.logvalues[key] = value | [
"def",
"logvalue",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'logvalues'",
")",
":",
"self",
".",
"logvalues",
"=",
"{",
"}",
"self",
".",
"logvalues",
"[",
"key",
"]",
"=",
"value"
] | Add log entry to request log info | [
"Add",
"log",
"entry",
"to",
"request",
"log",
"info"
] | 02505b8a5bef782f9b67120874355b64f1b3e81a | https://github.com/langloisjp/tornado-logging-app/blob/02505b8a5bef782f9b67120874355b64f1b3e81a/tornadoutil.py#L94-L98 | train | 56,071 |
langloisjp/tornado-logging-app | tornadoutil.py | RequestHandler.write_error | def write_error(self, status_code, **kwargs):
"""Log halt_reason in service log and output error page"""
message = default_message = httplib.responses.get(status_code, '')
# HTTPError exceptions may have a log_message attribute
if 'exc_info' in kwargs:
(_, exc, _) = kwargs['e... | python | def write_error(self, status_code, **kwargs):
"""Log halt_reason in service log and output error page"""
message = default_message = httplib.responses.get(status_code, '')
# HTTPError exceptions may have a log_message attribute
if 'exc_info' in kwargs:
(_, exc, _) = kwargs['e... | [
"def",
"write_error",
"(",
"self",
",",
"status_code",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"default_message",
"=",
"httplib",
".",
"responses",
".",
"get",
"(",
"status_code",
",",
"''",
")",
"# HTTPError exceptions may have a log_message attribute"... | Log halt_reason in service log and output error page | [
"Log",
"halt_reason",
"in",
"service",
"log",
"and",
"output",
"error",
"page"
] | 02505b8a5bef782f9b67120874355b64f1b3e81a | https://github.com/langloisjp/tornado-logging-app/blob/02505b8a5bef782f9b67120874355b64f1b3e81a/tornadoutil.py#L108-L120 | train | 56,072 |
langloisjp/tornado-logging-app | tornadoutil.py | RequestHandler.timeit | def timeit(self, metric, func, *args, **kwargs):
"""Time execution of callable and emit metric then return result."""
return metrics.timeit(metric, func, *args, **kwargs) | python | def timeit(self, metric, func, *args, **kwargs):
"""Time execution of callable and emit metric then return result."""
return metrics.timeit(metric, func, *args, **kwargs) | [
"def",
"timeit",
"(",
"self",
",",
"metric",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"metrics",
".",
"timeit",
"(",
"metric",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Time execution of callable and emit metric then return result. | [
"Time",
"execution",
"of",
"callable",
"and",
"emit",
"metric",
"then",
"return",
"result",
"."
] | 02505b8a5bef782f9b67120874355b64f1b3e81a | https://github.com/langloisjp/tornado-logging-app/blob/02505b8a5bef782f9b67120874355b64f1b3e81a/tornadoutil.py#L122-L124 | train | 56,073 |
langloisjp/tornado-logging-app | tornadoutil.py | RequestHandler.require_content_type | def require_content_type(self, content_type):
"""Raises a 400 if request content type is not as specified."""
if self.request.headers.get('content-type', '') != content_type:
self.halt(400, 'Content type must be ' + content_type) | python | def require_content_type(self, content_type):
"""Raises a 400 if request content type is not as specified."""
if self.request.headers.get('content-type', '') != content_type:
self.halt(400, 'Content type must be ' + content_type) | [
"def",
"require_content_type",
"(",
"self",
",",
"content_type",
")",
":",
"if",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'content-type'",
",",
"''",
")",
"!=",
"content_type",
":",
"self",
".",
"halt",
"(",
"400",
",",
"'Content type must... | Raises a 400 if request content type is not as specified. | [
"Raises",
"a",
"400",
"if",
"request",
"content",
"type",
"is",
"not",
"as",
"specified",
"."
] | 02505b8a5bef782f9b67120874355b64f1b3e81a | https://github.com/langloisjp/tornado-logging-app/blob/02505b8a5bef782f9b67120874355b64f1b3e81a/tornadoutil.py#L130-L133 | train | 56,074 |
langloisjp/tornado-logging-app | tornadoutil.py | RequestHandler._ensure_request_id_header | def _ensure_request_id_header(self):
"Ensure request headers have a request ID. Set one if needed."
if REQUEST_ID_HEADER not in self.request.headers:
self.request.headers.add(REQUEST_ID_HEADER, uuid.uuid1().hex) | python | def _ensure_request_id_header(self):
"Ensure request headers have a request ID. Set one if needed."
if REQUEST_ID_HEADER not in self.request.headers:
self.request.headers.add(REQUEST_ID_HEADER, uuid.uuid1().hex) | [
"def",
"_ensure_request_id_header",
"(",
"self",
")",
":",
"if",
"REQUEST_ID_HEADER",
"not",
"in",
"self",
".",
"request",
".",
"headers",
":",
"self",
".",
"request",
".",
"headers",
".",
"add",
"(",
"REQUEST_ID_HEADER",
",",
"uuid",
".",
"uuid1",
"(",
")... | Ensure request headers have a request ID. Set one if needed. | [
"Ensure",
"request",
"headers",
"have",
"a",
"request",
"ID",
".",
"Set",
"one",
"if",
"needed",
"."
] | 02505b8a5bef782f9b67120874355b64f1b3e81a | https://github.com/langloisjp/tornado-logging-app/blob/02505b8a5bef782f9b67120874355b64f1b3e81a/tornadoutil.py#L149-L152 | train | 56,075 |
GeorgeArgyros/symautomata | symautomata/stateremoval.py | main | def main():
"""Testing function for DFA _Brzozowski Operation"""
if len(argv) < 2:
targetfile = 'target.y'
else:
targetfile = argv[1]
print 'Parsing ruleset: ' + targetfile,
flex_a = Flexparser()
mma = flex_a.yyparse(targetfile)
print 'OK'
print 'Perform minimization on i... | python | def main():
"""Testing function for DFA _Brzozowski Operation"""
if len(argv) < 2:
targetfile = 'target.y'
else:
targetfile = argv[1]
print 'Parsing ruleset: ' + targetfile,
flex_a = Flexparser()
mma = flex_a.yyparse(targetfile)
print 'OK'
print 'Perform minimization on i... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"argv",
")",
"<",
"2",
":",
"targetfile",
"=",
"'target.y'",
"else",
":",
"targetfile",
"=",
"argv",
"[",
"1",
"]",
"print",
"'Parsing ruleset: '",
"+",
"targetfile",
",",
"flex_a",
"=",
"Flexparser",
"("... | Testing function for DFA _Brzozowski Operation | [
"Testing",
"function",
"for",
"DFA",
"_Brzozowski",
"Operation"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/stateremoval.py#L148-L164 | train | 56,076 |
GeorgeArgyros/symautomata | symautomata/stateremoval.py | StateRemoval._state_removal_init | def _state_removal_init(self):
"""State Removal Operation Initialization"""
# First, we remove all multi-edges:
for state_i in self.mma.states:
for state_j in self.mma.states:
if state_i.stateid == state_j.stateid:
self.l_transitions[
... | python | def _state_removal_init(self):
"""State Removal Operation Initialization"""
# First, we remove all multi-edges:
for state_i in self.mma.states:
for state_j in self.mma.states:
if state_i.stateid == state_j.stateid:
self.l_transitions[
... | [
"def",
"_state_removal_init",
"(",
"self",
")",
":",
"# First, we remove all multi-edges:",
"for",
"state_i",
"in",
"self",
".",
"mma",
".",
"states",
":",
"for",
"state_j",
"in",
"self",
".",
"mma",
".",
"states",
":",
"if",
"state_i",
".",
"stateid",
"==",... | State Removal Operation Initialization | [
"State",
"Removal",
"Operation",
"Initialization"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/stateremoval.py#L45-L64 | train | 56,077 |
GeorgeArgyros/symautomata | symautomata/stateremoval.py | StateRemoval._state_removal_solve | def _state_removal_solve(self):
"""The State Removal Operation"""
initial = sorted(
self.mma.states,
key=attrgetter('initial'),
reverse=True)[0].stateid
for state_k in self.mma.states:
if state_k.final:
continue
if state... | python | def _state_removal_solve(self):
"""The State Removal Operation"""
initial = sorted(
self.mma.states,
key=attrgetter('initial'),
reverse=True)[0].stateid
for state_k in self.mma.states:
if state_k.final:
continue
if state... | [
"def",
"_state_removal_solve",
"(",
"self",
")",
":",
"initial",
"=",
"sorted",
"(",
"self",
".",
"mma",
".",
"states",
",",
"key",
"=",
"attrgetter",
"(",
"'initial'",
")",
",",
"reverse",
"=",
"True",
")",
"[",
"0",
"]",
".",
"stateid",
"for",
"sta... | The State Removal Operation | [
"The",
"State",
"Removal",
"Operation"
] | f5d66533573b27e155bec3f36b8c00b8e3937cb3 | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/stateremoval.py#L125-L139 | train | 56,078 |
iron-io/iron_core_python | iron_core.py | IronClient.request | def request(self, url, method, body="", headers={}, retry=True):
"""Execute an HTTP request and return a dict containing the response
and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project I... | python | def request(self, url, method, body="", headers={}, retry=True):
"""Execute an HTTP request and return a dict containing the response
and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project I... | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"method",
",",
"body",
"=",
"\"\"",
",",
"headers",
"=",
"{",
"}",
",",
"retry",
"=",
"True",
")",
":",
"if",
"headers",
":",
"headers",
"=",
"dict",
"(",
"list",
"(",
"headers",
".",
"items",
"(",
... | Execute an HTTP request and return a dict containing the response
and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, with no leading /. Required.
method -- The HTTP method to use. Re... | [
"Execute",
"an",
"HTTP",
"request",
"and",
"return",
"a",
"dict",
"containing",
"the",
"response",
"and",
"the",
"response",
"status",
"code",
"."
] | f09a160a854912efcb75a810702686bc25b74fa8 | https://github.com/iron-io/iron_core_python/blob/f09a160a854912efcb75a810702686bc25b74fa8/iron_core.py#L209-L270 | train | 56,079 |
iron-io/iron_core_python | iron_core.py | IronClient.get | def get(self, url, headers={}, retry=True):
"""Execute an HTTP GET request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, with no leadin... | python | def get(self, url, headers={}, retry=True):
"""Execute an HTTP GET request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, with no leadin... | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"{",
"}",
",",
"retry",
"=",
"True",
")",
":",
"return",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"\"GET\"",
",",
"headers",
"=",
"headers",
",",
"retry",
"=",... | Execute an HTTP GET request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, with no leading /. Required.
headers -- HTTP Headers to send ... | [
"Execute",
"an",
"HTTP",
"GET",
"request",
"and",
"return",
"a",
"dict",
"containing",
"the",
"response",
"and",
"the",
"response",
"status",
"code",
"."
] | f09a160a854912efcb75a810702686bc25b74fa8 | https://github.com/iron-io/iron_core_python/blob/f09a160a854912efcb75a810702686bc25b74fa8/iron_core.py#L272-L285 | train | 56,080 |
iron-io/iron_core_python | iron_core.py | IronClient.post | def post(self, url, body="", headers={}, retry=True):
"""Execute an HTTP POST request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, wit... | python | def post(self, url, body="", headers={}, retry=True):
"""Execute an HTTP POST request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, wit... | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"body",
"=",
"\"\"",
",",
"headers",
"=",
"{",
"}",
",",
"retry",
"=",
"True",
")",
":",
"headers",
"[",
"\"Content-Length\"",
"]",
"=",
"str",
"(",
"len",
"(",
"body",
")",
")",
"return",
"self",
".",... | Execute an HTTP POST request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, with no leading /. Required.
body -- A string or file object... | [
"Execute",
"an",
"HTTP",
"POST",
"request",
"and",
"return",
"a",
"dict",
"containing",
"the",
"response",
"and",
"the",
"response",
"status",
"code",
"."
] | f09a160a854912efcb75a810702686bc25b74fa8 | https://github.com/iron-io/iron_core_python/blob/f09a160a854912efcb75a810702686bc25b74fa8/iron_core.py#L287-L303 | train | 56,081 |
iron-io/iron_core_python | iron_core.py | IronClient.patch | def patch(self, url, body="", headers={}, retry=True):
"""Execute an HTTP PATCH request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, w... | python | def patch(self, url, body="", headers={}, retry=True):
"""Execute an HTTP PATCH request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, w... | [
"def",
"patch",
"(",
"self",
",",
"url",
",",
"body",
"=",
"\"\"",
",",
"headers",
"=",
"{",
"}",
",",
"retry",
"=",
"True",
")",
":",
"return",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"\"PATCH\"",
",",
"body",
"=",
... | Execute an HTTP PATCH request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, with no leading /. Required.
body -- A string or file objec... | [
"Execute",
"an",
"HTTP",
"PATCH",
"request",
"and",
"return",
"a",
"dict",
"containing",
"the",
"response",
"and",
"the",
"response",
"status",
"code",
"."
] | f09a160a854912efcb75a810702686bc25b74fa8 | https://github.com/iron-io/iron_core_python/blob/f09a160a854912efcb75a810702686bc25b74fa8/iron_core.py#L339-L354 | train | 56,082 |
ScottDuckworth/python-anyvcs | anyvcs/svn.py | SvnRepo.clone | def clone(cls, srcpath, destpath):
"""Copy a main repository to a new location."""
try:
os.makedirs(destpath)
except OSError as e:
if not e.errno == errno.EEXIST:
raise
cmd = [SVNADMIN, 'dump', '--quiet', '.']
dump = subprocess.Popen(
... | python | def clone(cls, srcpath, destpath):
"""Copy a main repository to a new location."""
try:
os.makedirs(destpath)
except OSError as e:
if not e.errno == errno.EEXIST:
raise
cmd = [SVNADMIN, 'dump', '--quiet', '.']
dump = subprocess.Popen(
... | [
"def",
"clone",
"(",
"cls",
",",
"srcpath",
",",
"destpath",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"destpath",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"not",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
":",
"raise",
"cmd",
... | Copy a main repository to a new location. | [
"Copy",
"a",
"main",
"repository",
"to",
"a",
"new",
"location",
"."
] | 9eb09defbc6b7c99d373fad53cbf8fc81b637923 | https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L118-L138 | train | 56,083 |
ScottDuckworth/python-anyvcs | anyvcs/svn.py | SvnRepo.proplist | def proplist(self, rev, path=None):
"""List Subversion properties of the path"""
rev, prefix = self._maprev(rev)
if path is None:
return self._proplist(str(rev), None)
else:
path = type(self).cleanPath(_join(prefix, path))
return self._proplist(str(rev... | python | def proplist(self, rev, path=None):
"""List Subversion properties of the path"""
rev, prefix = self._maprev(rev)
if path is None:
return self._proplist(str(rev), None)
else:
path = type(self).cleanPath(_join(prefix, path))
return self._proplist(str(rev... | [
"def",
"proplist",
"(",
"self",
",",
"rev",
",",
"path",
"=",
"None",
")",
":",
"rev",
",",
"prefix",
"=",
"self",
".",
"_maprev",
"(",
"rev",
")",
"if",
"path",
"is",
"None",
":",
"return",
"self",
".",
"_proplist",
"(",
"str",
"(",
"rev",
")",
... | List Subversion properties of the path | [
"List",
"Subversion",
"properties",
"of",
"the",
"path"
] | 9eb09defbc6b7c99d373fad53cbf8fc81b637923 | https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L193-L200 | train | 56,084 |
ScottDuckworth/python-anyvcs | anyvcs/svn.py | SvnRepo.propget | def propget(self, prop, rev, path=None):
"""Get Subversion property value of the path"""
rev, prefix = self._maprev(rev)
if path is None:
return self._propget(prop, str(rev), None)
else:
path = type(self).cleanPath(_join(prefix, path))
return self._pro... | python | def propget(self, prop, rev, path=None):
"""Get Subversion property value of the path"""
rev, prefix = self._maprev(rev)
if path is None:
return self._propget(prop, str(rev), None)
else:
path = type(self).cleanPath(_join(prefix, path))
return self._pro... | [
"def",
"propget",
"(",
"self",
",",
"prop",
",",
"rev",
",",
"path",
"=",
"None",
")",
":",
"rev",
",",
"prefix",
"=",
"self",
".",
"_maprev",
"(",
"rev",
")",
"if",
"path",
"is",
"None",
":",
"return",
"self",
".",
"_propget",
"(",
"prop",
",",
... | Get Subversion property value of the path | [
"Get",
"Subversion",
"property",
"value",
"of",
"the",
"path"
] | 9eb09defbc6b7c99d373fad53cbf8fc81b637923 | https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L206-L213 | train | 56,085 |
ScottDuckworth/python-anyvcs | anyvcs/svn.py | SvnRepo.dump | def dump(
self, stream, progress=None, lower=None, upper=None,
incremental=False, deltas=False
):
"""Dump the repository to a dumpfile stream.
:param stream: A file stream to which the dumpfile is written
:param progress: A file stream to which progress is written
:p... | python | def dump(
self, stream, progress=None, lower=None, upper=None,
incremental=False, deltas=False
):
"""Dump the repository to a dumpfile stream.
:param stream: A file stream to which the dumpfile is written
:param progress: A file stream to which progress is written
:p... | [
"def",
"dump",
"(",
"self",
",",
"stream",
",",
"progress",
"=",
"None",
",",
"lower",
"=",
"None",
",",
"upper",
"=",
"None",
",",
"incremental",
"=",
"False",
",",
"deltas",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"SVNADMIN",
",",
"'dump'",
",",... | Dump the repository to a dumpfile stream.
:param stream: A file stream to which the dumpfile is written
:param progress: A file stream to which progress is written
:param lower: Must be a numeric version number
:param upper: Must be a numeric version number
See ``svnadmin help ... | [
"Dump",
"the",
"repository",
"to",
"a",
"dumpfile",
"stream",
"."
] | 9eb09defbc6b7c99d373fad53cbf8fc81b637923 | https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L746-L776 | train | 56,086 |
ScottDuckworth/python-anyvcs | anyvcs/svn.py | SvnRepo.load | def load(
self, stream, progress=None, ignore_uuid=False, force_uuid=False,
use_pre_commit_hook=False, use_post_commit_hook=False, parent_dir=None
):
"""Load a dumpfile stream into the repository.
:param stream: A file stream from which the dumpfile is read
:param progress: ... | python | def load(
self, stream, progress=None, ignore_uuid=False, force_uuid=False,
use_pre_commit_hook=False, use_post_commit_hook=False, parent_dir=None
):
"""Load a dumpfile stream into the repository.
:param stream: A file stream from which the dumpfile is read
:param progress: ... | [
"def",
"load",
"(",
"self",
",",
"stream",
",",
"progress",
"=",
"None",
",",
"ignore_uuid",
"=",
"False",
",",
"force_uuid",
"=",
"False",
",",
"use_pre_commit_hook",
"=",
"False",
",",
"use_post_commit_hook",
"=",
"False",
",",
"parent_dir",
"=",
"None",
... | Load a dumpfile stream into the repository.
:param stream: A file stream from which the dumpfile is read
:param progress: A file stream to which progress is written
See ``svnadmin help load`` for details on the other arguments. | [
"Load",
"a",
"dumpfile",
"stream",
"into",
"the",
"repository",
"."
] | 9eb09defbc6b7c99d373fad53cbf8fc81b637923 | https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/svn.py#L778-L811 | train | 56,087 |
themattrix/python-temporary | temporary/files.py | temp_file | def temp_file(
content=None,
suffix='',
prefix='tmp',
parent_dir=None):
"""
Create a temporary file and optionally populate it with content. The file
is deleted when the context exits.
The temporary file is created when entering the context manager and
deleted when e... | python | def temp_file(
content=None,
suffix='',
prefix='tmp',
parent_dir=None):
"""
Create a temporary file and optionally populate it with content. The file
is deleted when the context exits.
The temporary file is created when entering the context manager and
deleted when e... | [
"def",
"temp_file",
"(",
"content",
"=",
"None",
",",
"suffix",
"=",
"''",
",",
"prefix",
"=",
"'tmp'",
",",
"parent_dir",
"=",
"None",
")",
":",
"binary",
"=",
"isinstance",
"(",
"content",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
"parent_dir",
... | Create a temporary file and optionally populate it with content. The file
is deleted when the context exits.
The temporary file is created when entering the context manager and
deleted when exiting it.
>>> import temporary
>>> with temporary.temp_file() as temp_file:
... assert temp_file.ex... | [
"Create",
"a",
"temporary",
"file",
"and",
"optionally",
"populate",
"it",
"with",
"content",
".",
"The",
"file",
"is",
"deleted",
"when",
"the",
"context",
"exits",
"."
] | 5af1a393e57e71c2d4728e2c8e228edfd020e847 | https://github.com/themattrix/python-temporary/blob/5af1a393e57e71c2d4728e2c8e228edfd020e847/temporary/files.py#L11-L55 | train | 56,088 |
Sikilabs/pyebook | pyebook/pyebook.py | Book.load_content | def load_content(self):
"""
Load the book content
"""
# get the toc file from the root file
rel_path = self.root_file_url.replace(os.path.basename(self.root_file_url), '')
self.toc_file_url = rel_path + self.root_file.find(id="ncx")['href']
self.toc_file_soup = b... | python | def load_content(self):
"""
Load the book content
"""
# get the toc file from the root file
rel_path = self.root_file_url.replace(os.path.basename(self.root_file_url), '')
self.toc_file_url = rel_path + self.root_file.find(id="ncx")['href']
self.toc_file_soup = b... | [
"def",
"load_content",
"(",
"self",
")",
":",
"# get the toc file from the root file",
"rel_path",
"=",
"self",
".",
"root_file_url",
".",
"replace",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"root_file_url",
")",
",",
"''",
")",
"self",
"."... | Load the book content | [
"Load",
"the",
"book",
"content"
] | 96a14833df3ad8585efde91ac2b6c30982dca0d3 | https://github.com/Sikilabs/pyebook/blob/96a14833df3ad8585efde91ac2b6c30982dca0d3/pyebook/pyebook.py#L48-L66 | train | 56,089 |
Equitable/trump | uninstall/uninstall.py | UninstallTrump | def UninstallTrump(RemoveDataTables=True, RemoveOverrides=True, RemoveFailsafes=True):
"""
This script removes all tables associated with Trump.
It's written for PostgreSQL, but should be very easy to adapt to other
databases.
"""
ts = ['_symbols', '_symbol_validity', '_symbol_... | python | def UninstallTrump(RemoveDataTables=True, RemoveOverrides=True, RemoveFailsafes=True):
"""
This script removes all tables associated with Trump.
It's written for PostgreSQL, but should be very easy to adapt to other
databases.
"""
ts = ['_symbols', '_symbol_validity', '_symbol_... | [
"def",
"UninstallTrump",
"(",
"RemoveDataTables",
"=",
"True",
",",
"RemoveOverrides",
"=",
"True",
",",
"RemoveFailsafes",
"=",
"True",
")",
":",
"ts",
"=",
"[",
"'_symbols'",
",",
"'_symbol_validity'",
",",
"'_symbol_tags'",
",",
"'_symbol_aliases'",
",",
"'_f... | This script removes all tables associated with Trump.
It's written for PostgreSQL, but should be very easy to adapt to other
databases. | [
"This",
"script",
"removes",
"all",
"tables",
"associated",
"with",
"Trump",
".",
"It",
"s",
"written",
"for",
"PostgreSQL",
"but",
"should",
"be",
"very",
"easy",
"to",
"adapt",
"to",
"other",
"databases",
"."
] | a2802692bc642fa32096374159eea7ceca2947b4 | https://github.com/Equitable/trump/blob/a2802692bc642fa32096374159eea7ceca2947b4/uninstall/uninstall.py#L3-L31 | train | 56,090 |
hollenstein/maspy | maspy/peptidemethods.py | digestInSilico | def digestInSilico(proteinSequence, cleavageRule='[KR]', missedCleavage=0,
removeNtermM=True, minLength=5, maxLength=55):
"""Returns a list of peptide sequences and cleavage information derived
from an in silico digestion of a polypeptide.
:param proteinSequence: amino acid sequence of t... | python | def digestInSilico(proteinSequence, cleavageRule='[KR]', missedCleavage=0,
removeNtermM=True, minLength=5, maxLength=55):
"""Returns a list of peptide sequences and cleavage information derived
from an in silico digestion of a polypeptide.
:param proteinSequence: amino acid sequence of t... | [
"def",
"digestInSilico",
"(",
"proteinSequence",
",",
"cleavageRule",
"=",
"'[KR]'",
",",
"missedCleavage",
"=",
"0",
",",
"removeNtermM",
"=",
"True",
",",
"minLength",
"=",
"5",
",",
"maxLength",
"=",
"55",
")",
":",
"passFilter",
"=",
"lambda",
"startPos"... | Returns a list of peptide sequences and cleavage information derived
from an in silico digestion of a polypeptide.
:param proteinSequence: amino acid sequence of the poly peptide to be
digested
:param cleavageRule: cleavage rule expressed in a regular expression, see
:attr:`maspy.constants.... | [
"Returns",
"a",
"list",
"of",
"peptide",
"sequences",
"and",
"cleavage",
"information",
"derived",
"from",
"an",
"in",
"silico",
"digestion",
"of",
"a",
"polypeptide",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/peptidemethods.py#L42-L128 | train | 56,091 |
hollenstein/maspy | maspy/peptidemethods.py | calcPeptideMass | def calcPeptideMass(peptide, **kwargs):
"""Calculate the mass of a peptide.
:param aaMass: A dictionary with the monoisotopic masses of amino acid
residues, by default :attr:`maspy.constants.aaMass`
:param aaModMass: A dictionary with the monoisotopic mass changes of
modications, by default... | python | def calcPeptideMass(peptide, **kwargs):
"""Calculate the mass of a peptide.
:param aaMass: A dictionary with the monoisotopic masses of amino acid
residues, by default :attr:`maspy.constants.aaMass`
:param aaModMass: A dictionary with the monoisotopic mass changes of
modications, by default... | [
"def",
"calcPeptideMass",
"(",
"peptide",
",",
"*",
"*",
"kwargs",
")",
":",
"aaMass",
"=",
"kwargs",
".",
"get",
"(",
"'aaMass'",
",",
"maspy",
".",
"constants",
".",
"aaMass",
")",
"aaModMass",
"=",
"kwargs",
".",
"get",
"(",
"'aaModMass'",
",",
"mas... | Calculate the mass of a peptide.
:param aaMass: A dictionary with the monoisotopic masses of amino acid
residues, by default :attr:`maspy.constants.aaMass`
:param aaModMass: A dictionary with the monoisotopic mass changes of
modications, by default :attr:`maspy.constants.aaModMass`
:param e... | [
"Calculate",
"the",
"mass",
"of",
"a",
"peptide",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/peptidemethods.py#L132-L170 | train | 56,092 |
hollenstein/maspy | maspy/peptidemethods.py | removeModifications | def removeModifications(peptide):
"""Removes all modifications from a peptide string and return the plain
amino acid sequence.
:param peptide: peptide sequence, modifications have to be written in the
format "[modificationName]"
:param peptide: str
:returns: amino acid sequence of ``peptid... | python | def removeModifications(peptide):
"""Removes all modifications from a peptide string and return the plain
amino acid sequence.
:param peptide: peptide sequence, modifications have to be written in the
format "[modificationName]"
:param peptide: str
:returns: amino acid sequence of ``peptid... | [
"def",
"removeModifications",
"(",
"peptide",
")",
":",
"while",
"peptide",
".",
"find",
"(",
"'['",
")",
"!=",
"-",
"1",
":",
"peptide",
"=",
"peptide",
".",
"split",
"(",
"'['",
",",
"1",
")",
"[",
"0",
"]",
"+",
"peptide",
".",
"split",
"(",
"... | Removes all modifications from a peptide string and return the plain
amino acid sequence.
:param peptide: peptide sequence, modifications have to be written in the
format "[modificationName]"
:param peptide: str
:returns: amino acid sequence of ``peptide`` without any modifications | [
"Removes",
"all",
"modifications",
"from",
"a",
"peptide",
"string",
"and",
"return",
"the",
"plain",
"amino",
"acid",
"sequence",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/peptidemethods.py#L173-L185 | train | 56,093 |
hollenstein/maspy | maspy/peptidemethods.py | returnModPositions | def returnModPositions(peptide, indexStart=1, removeModString='UNIMOD:'):
"""Determines the amino acid positions of all present modifications.
:param peptide: peptide sequence, modifications have to be written in the
format "[modificationName]"
:param indexStart: returned amino acids positions of t... | python | def returnModPositions(peptide, indexStart=1, removeModString='UNIMOD:'):
"""Determines the amino acid positions of all present modifications.
:param peptide: peptide sequence, modifications have to be written in the
format "[modificationName]"
:param indexStart: returned amino acids positions of t... | [
"def",
"returnModPositions",
"(",
"peptide",
",",
"indexStart",
"=",
"1",
",",
"removeModString",
"=",
"'UNIMOD:'",
")",
":",
"unidmodPositionDict",
"=",
"dict",
"(",
")",
"while",
"peptide",
".",
"find",
"(",
"'['",
")",
"!=",
"-",
"1",
":",
"currModifica... | Determines the amino acid positions of all present modifications.
:param peptide: peptide sequence, modifications have to be written in the
format "[modificationName]"
:param indexStart: returned amino acids positions of the peptide start with
this number (first amino acid position = indexStart... | [
"Determines",
"the",
"amino",
"acid",
"positions",
"of",
"all",
"present",
"modifications",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/peptidemethods.py#L188-L216 | train | 56,094 |
hollenstein/maspy | maspy/peptidemethods.py | calcMhFromMz | def calcMhFromMz(mz, charge):
"""Calculate the MH+ value from mz and charge.
:param mz: float, mass to charge ratio (Dalton / charge)
:param charge: int, charge state
:returns: mass to charge ratio of the mono protonated ion (charge = 1)
"""
mh = (mz * charge) - (maspy.constants.atomicMassProt... | python | def calcMhFromMz(mz, charge):
"""Calculate the MH+ value from mz and charge.
:param mz: float, mass to charge ratio (Dalton / charge)
:param charge: int, charge state
:returns: mass to charge ratio of the mono protonated ion (charge = 1)
"""
mh = (mz * charge) - (maspy.constants.atomicMassProt... | [
"def",
"calcMhFromMz",
"(",
"mz",
",",
"charge",
")",
":",
"mh",
"=",
"(",
"mz",
"*",
"charge",
")",
"-",
"(",
"maspy",
".",
"constants",
".",
"atomicMassProton",
"*",
"(",
"charge",
"-",
"1",
")",
")",
"return",
"mh"
] | Calculate the MH+ value from mz and charge.
:param mz: float, mass to charge ratio (Dalton / charge)
:param charge: int, charge state
:returns: mass to charge ratio of the mono protonated ion (charge = 1) | [
"Calculate",
"the",
"MH",
"+",
"value",
"from",
"mz",
"and",
"charge",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/peptidemethods.py#L220-L229 | train | 56,095 |
hollenstein/maspy | maspy/peptidemethods.py | calcMzFromMh | def calcMzFromMh(mh, charge):
"""Calculate the mz value from MH+ and charge.
:param mh: float, mass to charge ratio (Dalton / charge) of the mono
protonated ion
:param charge: int, charge state
:returns: mass to charge ratio of the specified charge state
"""
mz = (mh + (maspy.constants... | python | def calcMzFromMh(mh, charge):
"""Calculate the mz value from MH+ and charge.
:param mh: float, mass to charge ratio (Dalton / charge) of the mono
protonated ion
:param charge: int, charge state
:returns: mass to charge ratio of the specified charge state
"""
mz = (mh + (maspy.constants... | [
"def",
"calcMzFromMh",
"(",
"mh",
",",
"charge",
")",
":",
"mz",
"=",
"(",
"mh",
"+",
"(",
"maspy",
".",
"constants",
".",
"atomicMassProton",
"*",
"(",
"charge",
"-",
"1",
")",
")",
")",
"/",
"charge",
"return",
"mz"
] | Calculate the mz value from MH+ and charge.
:param mh: float, mass to charge ratio (Dalton / charge) of the mono
protonated ion
:param charge: int, charge state
:returns: mass to charge ratio of the specified charge state | [
"Calculate",
"the",
"mz",
"value",
"from",
"MH",
"+",
"and",
"charge",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/peptidemethods.py#L232-L242 | train | 56,096 |
hollenstein/maspy | maspy/peptidemethods.py | calcMzFromMass | def calcMzFromMass(mass, charge):
"""Calculate the mz value of a peptide from its mass and charge.
:param mass: float, exact non protonated mass
:param charge: int, charge state
:returns: mass to charge ratio of the specified charge state
"""
mz = (mass + (maspy.constants.atomicMassProton * ch... | python | def calcMzFromMass(mass, charge):
"""Calculate the mz value of a peptide from its mass and charge.
:param mass: float, exact non protonated mass
:param charge: int, charge state
:returns: mass to charge ratio of the specified charge state
"""
mz = (mass + (maspy.constants.atomicMassProton * ch... | [
"def",
"calcMzFromMass",
"(",
"mass",
",",
"charge",
")",
":",
"mz",
"=",
"(",
"mass",
"+",
"(",
"maspy",
".",
"constants",
".",
"atomicMassProton",
"*",
"charge",
")",
")",
"/",
"charge",
"return",
"mz"
] | Calculate the mz value of a peptide from its mass and charge.
:param mass: float, exact non protonated mass
:param charge: int, charge state
:returns: mass to charge ratio of the specified charge state | [
"Calculate",
"the",
"mz",
"value",
"of",
"a",
"peptide",
"from",
"its",
"mass",
"and",
"charge",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/peptidemethods.py#L245-L254 | train | 56,097 |
hollenstein/maspy | maspy/peptidemethods.py | calcMassFromMz | def calcMassFromMz(mz, charge):
"""Calculate the mass of a peptide from its mz and charge.
:param mz: float, mass to charge ratio (Dalton / charge)
:param charge: int, charge state
:returns: non protonated mass (charge = 0)
"""
mass = (mz - maspy.constants.atomicMassProton) * charge
return... | python | def calcMassFromMz(mz, charge):
"""Calculate the mass of a peptide from its mz and charge.
:param mz: float, mass to charge ratio (Dalton / charge)
:param charge: int, charge state
:returns: non protonated mass (charge = 0)
"""
mass = (mz - maspy.constants.atomicMassProton) * charge
return... | [
"def",
"calcMassFromMz",
"(",
"mz",
",",
"charge",
")",
":",
"mass",
"=",
"(",
"mz",
"-",
"maspy",
".",
"constants",
".",
"atomicMassProton",
")",
"*",
"charge",
"return",
"mass"
] | Calculate the mass of a peptide from its mz and charge.
:param mz: float, mass to charge ratio (Dalton / charge)
:param charge: int, charge state
:returns: non protonated mass (charge = 0) | [
"Calculate",
"the",
"mass",
"of",
"a",
"peptide",
"from",
"its",
"mz",
"and",
"charge",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/peptidemethods.py#L257-L266 | train | 56,098 |
sporsh/carnifex | carnifex/sshprocess.py | SSHProcessInductor.execute | def execute(self, processProtocol, command, env={},
path=None, uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a process on the remote machine using SSH
@param processProtocol: the ProcessProtocol instance to connect
@param executable: the executable program to run
... | python | def execute(self, processProtocol, command, env={},
path=None, uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a process on the remote machine using SSH
@param processProtocol: the ProcessProtocol instance to connect
@param executable: the executable program to run
... | [
"def",
"execute",
"(",
"self",
",",
"processProtocol",
",",
"command",
",",
"env",
"=",
"{",
"}",
",",
"path",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"usePTY",
"=",
"0",
",",
"childFDs",
"=",
"None",
")",
":",
"sshCom... | Execute a process on the remote machine using SSH
@param processProtocol: the ProcessProtocol instance to connect
@param executable: the executable program to run
@param args: the arguments to pass to the process
@param env: environment variables to request the remote ssh server to set
... | [
"Execute",
"a",
"process",
"on",
"the",
"remote",
"machine",
"using",
"SSH"
] | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/sshprocess.py#L64-L88 | train | 56,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.