repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
expfactory/expfactory | expfactory/database/relational.py | https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L177-L213 | def save_data(self,session, exp_id, content):
'''save data will obtain the current subid from the session, and save it
depending on the database type. Currently we just support flat files'''
from expfactory.database.models import (
Participant,
Result
)
subid = session.get('subid'... | [
"def",
"save_data",
"(",
"self",
",",
"session",
",",
"exp_id",
",",
"content",
")",
":",
"from",
"expfactory",
".",
"database",
".",
"models",
"import",
"(",
"Participant",
",",
"Result",
")",
"subid",
"=",
"session",
".",
"get",
"(",
"'subid'",
")",
... | save data will obtain the current subid from the session, and save it
depending on the database type. Currently we just support flat files | [
"save",
"data",
"will",
"obtain",
"the",
"current",
"subid",
"from",
"the",
"session",
"and",
"save",
"it",
"depending",
"on",
"the",
"database",
"type",
".",
"Currently",
"we",
"just",
"support",
"flat",
"files"
] | python | train | 39.945946 |
bcbio/bcbio-nextgen | bcbio/heterogeneity/theta.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/theta.py#L43-L76 | def subset_by_supported(input_file, get_coords, calls_by_name, work_dir, data,
headers=("#",)):
"""Limit CNVkit input to calls with support from another caller.
get_coords is a function that return chrom, start, end from a line of the
input_file, allowing handling of multiple input ... | [
"def",
"subset_by_supported",
"(",
"input_file",
",",
"get_coords",
",",
"calls_by_name",
",",
"work_dir",
",",
"data",
",",
"headers",
"=",
"(",
"\"#\"",
",",
")",
")",
":",
"support_files",
"=",
"[",
"(",
"c",
",",
"tz",
".",
"get_in",
"(",
"[",
"c",... | Limit CNVkit input to calls with support from another caller.
get_coords is a function that return chrom, start, end from a line of the
input_file, allowing handling of multiple input file types. | [
"Limit",
"CNVkit",
"input",
"to",
"calls",
"with",
"support",
"from",
"another",
"caller",
"."
] | python | train | 57.735294 |
kivy/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/compiler.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/compiler.py#L125-L128 | def add_special(self, name):
"""Register a special name like `loop`."""
self.undeclared.discard(name)
self.declared.add(name) | [
"def",
"add_special",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"undeclared",
".",
"discard",
"(",
"name",
")",
"self",
".",
"declared",
".",
"add",
"(",
"name",
")"
] | Register a special name like `loop`. | [
"Register",
"a",
"special",
"name",
"like",
"loop",
"."
] | python | train | 36.5 |
kontron/python-aardvark | pyaardvark/aardvark.py | https://github.com/kontron/python-aardvark/blob/9827f669fbdc5bceb98e7d08a294b4e4e455d0d5/pyaardvark/aardvark.py#L280-L286 | def enable_i2c(self):
"""Set this to `True` to enable the hardware I2C interface. If set to
`False` the hardware interface will be disabled and its pins (SDA and
SCL) can be used as GPIOs.
"""
config = self._interface_configuration(CONFIG_QUERY)
return config == CONFIG_GP... | [
"def",
"enable_i2c",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"_interface_configuration",
"(",
"CONFIG_QUERY",
")",
"return",
"config",
"==",
"CONFIG_GPIO_I2C",
"or",
"config",
"==",
"CONFIG_SPI_I2C"
] | Set this to `True` to enable the hardware I2C interface. If set to
`False` the hardware interface will be disabled and its pins (SDA and
SCL) can be used as GPIOs. | [
"Set",
"this",
"to",
"True",
"to",
"enable",
"the",
"hardware",
"I2C",
"interface",
".",
"If",
"set",
"to",
"False",
"the",
"hardware",
"interface",
"will",
"be",
"disabled",
"and",
"its",
"pins",
"(",
"SDA",
"and",
"SCL",
")",
"can",
"be",
"used",
"as... | python | train | 49.714286 |
siemens/django-dingos | dingos/models.py | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/models.py#L1822-L1836 | def get_user_data_iobject(user=None,group=None,data_kind=DINGOS_USER_DATA_TYPE_NAME):
"""
Returns either stored settings of a given user or default settings.
This behavior reflects the need for views to have some settings at
hand when running. The settings are returned as dict object.
... | [
"def",
"get_user_data_iobject",
"(",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"data_kind",
"=",
"DINGOS_USER_DATA_TYPE_NAME",
")",
":",
"logger",
".",
"debug",
"(",
"\"Get user settings called\"",
")",
"if",
"not",
"user",
".",
"is_authenticated",
"(... | Returns either stored settings of a given user or default settings.
This behavior reflects the need for views to have some settings at
hand when running. The settings are returned as dict object. | [
"Returns",
"either",
"stored",
"settings",
"of",
"a",
"given",
"user",
"or",
"default",
"settings",
".",
"This",
"behavior",
"reflects",
"the",
"need",
"for",
"views",
"to",
"have",
"some",
"settings",
"at",
"hand",
"when",
"running",
".",
"The",
"settings",... | python | train | 41.466667 |
limix/limix-core | limix_core/util/cobj.py | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/cobj.py#L42-L54 | def cached_idxs(method):
""" this function is used as a decorator for caching """
def method_wrapper(self,*args,**kwargs):
tail = '_'.join(str(idx) for idx in args)
_cache_attr_name = '_cache_'+method.__name__+'_'+tail
_bool_attr_name = '_cached_'+method.__name__+'_'+tail
is_cac... | [
"def",
"cached_idxs",
"(",
"method",
")",
":",
"def",
"method_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tail",
"=",
"'_'",
".",
"join",
"(",
"str",
"(",
"idx",
")",
"for",
"idx",
"in",
"args",
")",
"_cache_attr_na... | this function is used as a decorator for caching | [
"this",
"function",
"is",
"used",
"as",
"a",
"decorator",
"for",
"caching"
] | python | train | 45.615385 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/text.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/text.py#L363-L399 | def indent(instr,nspaces=4, ntabs=0, flatten=False):
"""Indent a string a given number of spaces or tabstops.
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
Parameters
----------
instr : basestring
The string to be indented.
nspaces : int (default: 4)
The number... | [
"def",
"indent",
"(",
"instr",
",",
"nspaces",
"=",
"4",
",",
"ntabs",
"=",
"0",
",",
"flatten",
"=",
"False",
")",
":",
"if",
"instr",
"is",
"None",
":",
"return",
"ind",
"=",
"'\\t'",
"*",
"ntabs",
"+",
"' '",
"*",
"nspaces",
"if",
"flatten",
"... | Indent a string a given number of spaces or tabstops.
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
Parameters
----------
instr : basestring
The string to be indented.
nspaces : int (default: 4)
The number of spaces to be indented.
ntabs : int (default: 0)
... | [
"Indent",
"a",
"string",
"a",
"given",
"number",
"of",
"spaces",
"or",
"tabstops",
"."
] | python | test | 27.702703 |
bkg/greenwich | greenwich/tile.py | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/tile.py#L20-L40 | def to_lonlat(xtile, ytile, zoom):
"""Returns a tuple of (longitude, latitude) from a map tile xyz coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2
Arguments:
xtile - x tile location as int or float
ytile - y tile location as int or float
zo... | [
"def",
"to_lonlat",
"(",
"xtile",
",",
"ytile",
",",
"zoom",
")",
":",
"n",
"=",
"2.0",
"**",
"zoom",
"lon",
"=",
"xtile",
"/",
"n",
"*",
"360.0",
"-",
"180.0",
"# Caculate latitude in radians and convert to degrees constrained from -90",
"# to 90. Values too big fo... | Returns a tuple of (longitude, latitude) from a map tile xyz coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2
Arguments:
xtile - x tile location as int or float
ytile - y tile location as int or float
zoom - zoom level as int or float | [
"Returns",
"a",
"tuple",
"of",
"(",
"longitude",
"latitude",
")",
"from",
"a",
"map",
"tile",
"xyz",
"coordinate",
"."
] | python | test | 38.095238 |
gmr/queries | queries/session.py | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/session.py#L273-L307 | def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the conne... | [
"def",
"_connect",
"(",
"self",
")",
":",
"# Attempt to get a cached connection from the connection pool",
"try",
":",
"connection",
"=",
"self",
".",
"_pool_manager",
".",
"get",
"(",
"self",
".",
"pid",
",",
"self",
")",
"LOGGER",
".",
"debug",
"(",
"\"Re-usin... | Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError | [
"Connect",
"to",
"PostgreSQL",
"either",
"by",
"reusing",
"a",
"connection",
"from",
"the",
"pool",
"if",
"possible",
"or",
"by",
"creating",
"the",
"new",
"connection",
"."
] | python | train | 38.885714 |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L86-L90 | def _factory(slice_, axis, weighted):
"""return subclass for PairwiseSignificance, based on slice dimension types."""
if slice_.dim_types[0] == DT.MR_SUBVAR:
return _MrXCatPairwiseSignificance(slice_, axis, weighted)
return _CatXCatPairwiseSignificance(slice_, axis, weighted) | [
"def",
"_factory",
"(",
"slice_",
",",
"axis",
",",
"weighted",
")",
":",
"if",
"slice_",
".",
"dim_types",
"[",
"0",
"]",
"==",
"DT",
".",
"MR_SUBVAR",
":",
"return",
"_MrXCatPairwiseSignificance",
"(",
"slice_",
",",
"axis",
",",
"weighted",
")",
"retu... | return subclass for PairwiseSignificance, based on slice dimension types. | [
"return",
"subclass",
"for",
"PairwiseSignificance",
"based",
"on",
"slice",
"dimension",
"types",
"."
] | python | train | 61.6 |
PaulHancock/Aegean | AegeanTools/BANE.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/BANE.py#L467-L491 | def write_fits(data, header, file_name):
"""
Combine data and a fits header to write a fits file.
Parameters
----------
data : numpy.ndarray
The data to be written.
header : astropy.io.fits.hduheader
The header for the fits file.
file_name : string
The file to writ... | [
"def",
"write_fits",
"(",
"data",
",",
"header",
",",
"file_name",
")",
":",
"hdu",
"=",
"fits",
".",
"PrimaryHDU",
"(",
"data",
")",
"hdu",
".",
"header",
"=",
"header",
"hdulist",
"=",
"fits",
".",
"HDUList",
"(",
"[",
"hdu",
"]",
")",
"hdulist",
... | Combine data and a fits header to write a fits file.
Parameters
----------
data : numpy.ndarray
The data to be written.
header : astropy.io.fits.hduheader
The header for the fits file.
file_name : string
The file to write
Returns
-------
None | [
"Combine",
"data",
"and",
"a",
"fits",
"header",
"to",
"write",
"a",
"fits",
"file",
"."
] | python | train | 21.4 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_heliplane.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_heliplane.py#L102-L130 | def update_channels(self):
'''update which channels provide input'''
self.interlock_channel = -1
self.override_channel = -1
self.zero_I_channel = -1
self.no_vtol_channel = -1
# output channels
self.rsc_out_channel = 9
self.fwd_thr_channel = 10
fo... | [
"def",
"update_channels",
"(",
"self",
")",
":",
"self",
".",
"interlock_channel",
"=",
"-",
"1",
"self",
".",
"override_channel",
"=",
"-",
"1",
"self",
".",
"zero_I_channel",
"=",
"-",
"1",
"self",
".",
"no_vtol_channel",
"=",
"-",
"1",
"# output channel... | update which channels provide input | [
"update",
"which",
"channels",
"provide",
"input"
] | python | train | 33.206897 |
pvlib/pvlib-python | pvlib/solarposition.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/solarposition.py#L1105-L1144 | def declination_spencer71(dayofyear):
"""
Solar declination from Duffie & Beckman [1] and attributed to
Spencer (1971) and Iqbal (1983).
.. warning::
Return units are radians, not degrees.
Parameters
----------
dayofyear : numeric
Returns
-------
declination (radians) ... | [
"def",
"declination_spencer71",
"(",
"dayofyear",
")",
":",
"day_angle",
"=",
"_calculate_simple_day_angle",
"(",
"dayofyear",
")",
"return",
"(",
"0.006918",
"-",
"0.399912",
"*",
"np",
".",
"cos",
"(",
"day_angle",
")",
"+",
"0.070257",
"*",
"np",
".",
"si... | Solar declination from Duffie & Beckman [1] and attributed to
Spencer (1971) and Iqbal (1983).
.. warning::
Return units are radians, not degrees.
Parameters
----------
dayofyear : numeric
Returns
-------
declination (radians) : numeric
Angular position of the sun at s... | [
"Solar",
"declination",
"from",
"Duffie",
"&",
"Beckman",
"[",
"1",
"]",
"and",
"attributed",
"to",
"Spencer",
"(",
"1971",
")",
"and",
"Iqbal",
"(",
"1983",
")",
"."
] | python | train | 30.65 |
pennlabs/penn-sdk-python | penn/calendar3year.py | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/calendar3year.py#L12-L48 | def pull_3year(self):
"""Returns a list (in JSON format) containing all the events from the Penn iCal Calendar.
List contains events in chronological order.
Each element of the list is a dictionary, containing:
- Name of the event 'name'
- Start date 'start'
... | [
"def",
"pull_3year",
"(",
"self",
")",
":",
"events",
"=",
"[",
"]",
"for",
"term",
"in",
"[",
"\"fall\"",
",",
"\"summer\"",
",",
"\"spring\"",
"]",
":",
"url",
"=",
"\"{}{}{}term.ics\"",
".",
"format",
"(",
"BASE_URL",
",",
"datetime",
".",
"datetime",... | Returns a list (in JSON format) containing all the events from the Penn iCal Calendar.
List contains events in chronological order.
Each element of the list is a dictionary, containing:
- Name of the event 'name'
- Start date 'start'
- End date 'end' | [
"Returns",
"a",
"list",
"(",
"in",
"JSON",
"format",
")",
"containing",
"all",
"the",
"events",
"from",
"the",
"Penn",
"iCal",
"Calendar",
"."
] | python | train | 40.864865 |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7187-L7199 | def validateOneElement(self, doc, elem):
"""Try to validate a single element and it's attributes,
basically it does the following checks as described by the
XML-1.0 recommendation: - [ VC: Element Valid ] - [ VC:
Required Attribute ] Then call xmlValidateOneAttribute()
fo... | [
"def",
"validateOneElement",
"(",
"self",
",",
"doc",
",",
"elem",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"if",
"elem",
"is",
"None",
":",
"elem__o",
"=",
"None",
"else",
":",
... | Try to validate a single element and it's attributes,
basically it does the following checks as described by the
XML-1.0 recommendation: - [ VC: Element Valid ] - [ VC:
Required Attribute ] Then call xmlValidateOneAttribute()
for each attribute present. The ID/IDREF checkings ar... | [
"Try",
"to",
"validate",
"a",
"single",
"element",
"and",
"it",
"s",
"attributes",
"basically",
"it",
"does",
"the",
"following",
"checks",
"as",
"described",
"by",
"the",
"XML",
"-",
"1",
".",
"0",
"recommendation",
":",
"-",
"[",
"VC",
":",
"Element",
... | python | train | 48 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_DGPS.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_DGPS.py#L21-L41 | def idle_task(self):
'''called in idle time'''
try:
data = self.port.recv(200)
except socket.error as e:
if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
return
raise
if len(data) > 110:
print("DGPS data too large: %u byte... | [
"def",
"idle_task",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"port",
".",
"recv",
"(",
"200",
")",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"in",
"[",
"errno",
".",
"EAGAIN",
",",
"errno",
"... | called in idle time | [
"called",
"in",
"idle",
"time"
] | python | train | 29.428571 |
JohnVinyard/zounds | zounds/spectral/tfrepresentation.py | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/tfrepresentation.py#L57-L69 | def validate(self, size):
"""
Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match
"""
msg = 'scale and array size must match, ' \
'but were s... | [
"def",
"validate",
"(",
"self",
",",
"size",
")",
":",
"msg",
"=",
"'scale and array size must match, '",
"'but were scale: {self.scale.n_bands}, array size: {size}'",
"if",
"size",
"!=",
"len",
"(",
"self",
".",
"scale",
")",
":",
"raise",
"ValueError",
"(",
"msg"... | Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match | [
"Ensure",
"that",
"the",
"size",
"of",
"the",
"dimension",
"matches",
"the",
"number",
"of",
"bands",
"in",
"the",
"scale"
] | python | train | 34.307692 |
Jajcus/pyxmpp2 | pyxmpp2/transport.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L656-L665 | def _initiate_starttls(self, **kwargs):
"""Initiate starttls handshake over the socket.
"""
if self._tls_state == "connected":
raise RuntimeError("Already TLS-connected")
kwargs["do_handshake_on_connect"] = False
logger.debug("Wrapping the socket into ssl")
se... | [
"def",
"_initiate_starttls",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_tls_state",
"==",
"\"connected\"",
":",
"raise",
"RuntimeError",
"(",
"\"Already TLS-connected\"",
")",
"kwargs",
"[",
"\"do_handshake_on_connect\"",
"]",
"=",
"Fal... | Initiate starttls handshake over the socket. | [
"Initiate",
"starttls",
"handshake",
"over",
"the",
"socket",
"."
] | python | valid | 44.3 |
apache/incubator-mxnet | plugin/opencv/opencv.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/plugin/opencv/opencv.py#L173-L188 | def next(self):
"""Move iterator position forward"""
batch = mx.nd.zeros((self.batch_size, self.size[1], self.size[0], 3))
i = self.cur
for i in range(self.cur, min(len(self.list), self.cur+self.batch_size)):
str_img = open(self.root+self.list[i]+'.jpg').read()
im... | [
"def",
"next",
"(",
"self",
")",
":",
"batch",
"=",
"mx",
".",
"nd",
".",
"zeros",
"(",
"(",
"self",
".",
"batch_size",
",",
"self",
".",
"size",
"[",
"1",
"]",
",",
"self",
".",
"size",
"[",
"0",
"]",
",",
"3",
")",
")",
"i",
"=",
"self",
... | Move iterator position forward | [
"Move",
"iterator",
"position",
"forward"
] | python | train | 44 |
ubc/github2gitlab | github2gitlab/main.py | https://github.com/ubc/github2gitlab/blob/795898f6d438621fa0c996a7156d70c382ff0493/github2gitlab/main.py#L254-L281 | def add_key(self):
"Add ssh key to gitlab if necessary"
try:
with open(self.args.ssh_public_key) as f:
public_key = f.read().strip()
except:
log.debug("No key found in {}".format(self.args.ssh_public_key))
return None
g = self.gitlab
... | [
"def",
"add_key",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"args",
".",
"ssh_public_key",
")",
"as",
"f",
":",
"public_key",
"=",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"except",
":",
"log",
".",
"debug",
... | Add ssh key to gitlab if necessary | [
"Add",
"ssh",
"key",
"to",
"gitlab",
"if",
"necessary"
] | python | train | 43.428571 |
pytorch/vision | torchvision/transforms/functional.py | https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L410-L432 | def _get_perspective_coeffs(startpoints, endpoints):
"""Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms.
In Perspective Transform each pixel (x, y) in the orignal image gets transformed as,
(x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy ... | [
"def",
"_get_perspective_coeffs",
"(",
"startpoints",
",",
"endpoints",
")",
":",
"matrix",
"=",
"[",
"]",
"for",
"p1",
",",
"p2",
"in",
"zip",
"(",
"endpoints",
",",
"startpoints",
")",
":",
"matrix",
".",
"append",
"(",
"[",
"p1",
"[",
"0",
"]",
",... | Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms.
In Perspective Transform each pixel (x, y) in the orignal image gets transformed as,
(x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) )
Args:
List containing [top-left, top-rig... | [
"Helper",
"function",
"to",
"get",
"the",
"coefficients",
"(",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
")",
"for",
"the",
"perspective",
"transforms",
"."
] | python | test | 44.434783 |
apache/incubator-mxnet | example/gluon/lipnet/utils/preprocess_data.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/preprocess_data.py#L118-L124 | def process_frames_mouth(self, frames):
"""
Preprocess from frames using mouth detector
"""
self.face = np.array(frames)
self.mouth = np.array(frames)
self.set_data(frames) | [
"def",
"process_frames_mouth",
"(",
"self",
",",
"frames",
")",
":",
"self",
".",
"face",
"=",
"np",
".",
"array",
"(",
"frames",
")",
"self",
".",
"mouth",
"=",
"np",
".",
"array",
"(",
"frames",
")",
"self",
".",
"set_data",
"(",
"frames",
")"
] | Preprocess from frames using mouth detector | [
"Preprocess",
"from",
"frames",
"using",
"mouth",
"detector"
] | python | train | 30.571429 |
heroku/heroku.py | heroku/helpers.py | https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/helpers.py#L99-L131 | def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None):
"""Extends a given object for API Production."""
# Cast all int_keys to int()
if int_keys:
for in_key in int_keys:
if (in_key in in_dict) and (in_dict.get(in_key, None) is not None):
in_dict[in_key] = in... | [
"def",
"to_api",
"(",
"in_dict",
",",
"int_keys",
"=",
"None",
",",
"date_keys",
"=",
"None",
",",
"bool_keys",
"=",
"None",
")",
":",
"# Cast all int_keys to int()",
"if",
"int_keys",
":",
"for",
"in_key",
"in",
"int_keys",
":",
"if",
"(",
"in_key",
"in",... | Extends a given object for API Production. | [
"Extends",
"a",
"given",
"object",
"for",
"API",
"Production",
"."
] | python | train | 30.424242 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/sampling/sampler.py | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/sampling/sampler.py#L83-L96 | def load_settings(self, daemon_config, context, origin=None):
"""
The pollers have dependency on the context manager
of the X-Ray recorder. They will respect the customer
specified xray client to poll sampling rules/targets.
Otherwise they falls back to use the same X-Ray daemon
... | [
"def",
"load_settings",
"(",
"self",
",",
"daemon_config",
",",
"context",
",",
"origin",
"=",
"None",
")",
":",
"self",
".",
"_connector",
".",
"setup_xray_client",
"(",
"ip",
"=",
"daemon_config",
".",
"tcp_ip",
",",
"port",
"=",
"daemon_config",
".",
"t... | The pollers have dependency on the context manager
of the X-Ray recorder. They will respect the customer
specified xray client to poll sampling rules/targets.
Otherwise they falls back to use the same X-Ray daemon
as the emitter. | [
"The",
"pollers",
"have",
"dependency",
"on",
"the",
"context",
"manager",
"of",
"the",
"X",
"-",
"Ray",
"recorder",
".",
"They",
"will",
"respect",
"the",
"customer",
"specified",
"xray",
"client",
"to",
"poll",
"sampling",
"rules",
"/",
"targets",
".",
"... | python | train | 44.285714 |
odlgroup/odl | odl/phantom/transmission.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/phantom/transmission.py#L79-L111 | def shepp_logan_ellipsoids(ndim, modified=False):
"""Ellipsoids for the standard Shepp-Logan phantom in 2 or 3 dimensions.
Parameters
----------
ndim : {2, 3}
Dimension of the space the ellipsoids should be in.
modified : bool, optional
True if the modified Shepp-Logan phantom shoul... | [
"def",
"shepp_logan_ellipsoids",
"(",
"ndim",
",",
"modified",
"=",
"False",
")",
":",
"if",
"ndim",
"==",
"2",
":",
"ellipsoids",
"=",
"_shepp_logan_ellipse_2d",
"(",
")",
"elif",
"ndim",
"==",
"3",
":",
"ellipsoids",
"=",
"_shepp_logan_ellipsoids_3d",
"(",
... | Ellipsoids for the standard Shepp-Logan phantom in 2 or 3 dimensions.
Parameters
----------
ndim : {2, 3}
Dimension of the space the ellipsoids should be in.
modified : bool, optional
True if the modified Shepp-Logan phantom should be given.
The modified phantom has greatly ampl... | [
"Ellipsoids",
"for",
"the",
"standard",
"Shepp",
"-",
"Logan",
"phantom",
"in",
"2",
"or",
"3",
"dimensions",
"."
] | python | train | 30.515152 |
google/transitfeed | transitfeed/serviceperiod.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L106-L110 | def GetCalendarFieldValuesTuple(self):
"""Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt ."""
if self.start_date and self.end_date:
return [getattr(self, fn) for fn in self._FIELD_NAMES] | [
"def",
"GetCalendarFieldValuesTuple",
"(",
"self",
")",
":",
"if",
"self",
".",
"start_date",
"and",
"self",
".",
"end_date",
":",
"return",
"[",
"getattr",
"(",
"self",
",",
"fn",
")",
"for",
"fn",
"in",
"self",
".",
"_FIELD_NAMES",
"]"
] | Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt . | [
"Return",
"the",
"tuple",
"of",
"calendar",
".",
"txt",
"values",
"or",
"None",
"if",
"this",
"ServicePeriod",
"should",
"not",
"be",
"in",
"calendar",
".",
"txt",
"."
] | python | train | 50.6 |
APSL/puput | setup.py | https://github.com/APSL/puput/blob/c3294f6bb0dd784f881ce9e3089cbf40d0528e47/setup.py#L11-L16 | def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = codecs.open(os.path.join(package, '__init__.py'), encoding='utf-8').read()
return re.search("^__version__ = ['\"]([^'\"]+)['\"]", init_py, re.MULTILINE).group(1) | [
"def",
"get_version",
"(",
"package",
")",
":",
"init_py",
"=",
"codecs",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"package",
",",
"'__init__.py'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
".",
"read",
"(",
")",
"return",
"re",
".",
... | Return package version as listed in `__version__` in `init.py`. | [
"Return",
"package",
"version",
"as",
"listed",
"in",
"__version__",
"in",
"init",
".",
"py",
"."
] | python | train | 47.333333 |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L5064-L5074 | def setOverlayTexture(self, ulOverlayHandle):
"""
Texture to draw for the overlay. This function can only be called by the overlay's creator or renderer process (see SetOverlayRenderingPid) .
* OpenGL dirty state:
glBindTexture
"""
fn = self.function_table.setOverlayText... | [
"def",
"setOverlayTexture",
"(",
"self",
",",
"ulOverlayHandle",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTexture",
"pTexture",
"=",
"Texture_t",
"(",
")",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"byref",
"(",
"pTexture",
... | Texture to draw for the overlay. This function can only be called by the overlay's creator or renderer process (see SetOverlayRenderingPid) .
* OpenGL dirty state:
glBindTexture | [
"Texture",
"to",
"draw",
"for",
"the",
"overlay",
".",
"This",
"function",
"can",
"only",
"be",
"called",
"by",
"the",
"overlay",
"s",
"creator",
"or",
"renderer",
"process",
"(",
"see",
"SetOverlayRenderingPid",
")",
".",
"*",
"OpenGL",
"dirty",
"state",
... | python | train | 39.090909 |
BlockHub/blockhubdpostools | dpostools/api.py | https://github.com/BlockHub/blockhubdpostools/blob/27712cd97cd3658ee54a4330ff3135b51a01d7d1/dpostools/api.py#L76-L101 | def status(self):
"""
check the status of the network and the peers
:return: network_height, peer_status
"""
peer = random.choice(self.PEERS)
formatted_peer = 'http://{}:4001'.format(peer)
peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers'... | [
"def",
"status",
"(",
"self",
")",
":",
"peer",
"=",
"random",
".",
"choice",
"(",
"self",
".",
"PEERS",
")",
"formatted_peer",
"=",
"'http://{}:4001'",
".",
"format",
"(",
"peer",
")",
"peerdata",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"formatt... | check the status of the network and the peers
:return: network_height, peer_status | [
"check",
"the",
"status",
"of",
"the",
"network",
"and",
"the",
"peers"
] | python | valid | 31.846154 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/monitoring.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/monitoring.py#L711-L716 | def event_listeners(self):
"""List of registered event listeners."""
return (self.__command_listeners[:],
self.__server_heartbeat_listeners[:],
self.__server_listeners[:],
self.__topology_listeners[:]) | [
"def",
"event_listeners",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"__command_listeners",
"[",
":",
"]",
",",
"self",
".",
"__server_heartbeat_listeners",
"[",
":",
"]",
",",
"self",
".",
"__server_listeners",
"[",
":",
"]",
",",
"self",
".",
"... | List of registered event listeners. | [
"List",
"of",
"registered",
"event",
"listeners",
"."
] | python | train | 43.333333 |
deepmind/sonnet | sonnet/python/modules/nets/convnet.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/convnet.py#L588-L712 | def transpose(self,
name=None,
output_channels=None,
kernel_shapes=None,
strides=None,
paddings=None,
activation=None,
activate_final=None,
normalization_ctor=None,
normalizati... | [
"def",
"transpose",
"(",
"self",
",",
"name",
"=",
"None",
",",
"output_channels",
"=",
"None",
",",
"kernel_shapes",
"=",
"None",
",",
"strides",
"=",
"None",
",",
"paddings",
"=",
"None",
",",
"activation",
"=",
"None",
",",
"activate_final",
"=",
"Non... | Returns transposed version of this network.
Args:
name: Optional string specifying the name of the transposed module. The
default name is constructed by appending "_transpose"
to `self.module_name`.
output_channels: Optional iterable of numbers of output channels.
kernel_shapes: O... | [
"Returns",
"transposed",
"version",
"of",
"this",
"network",
"."
] | python | train | 46.488 |
drdoctr/doctr | doctr/local.py | https://github.com/drdoctr/doctr/blob/0f19ff78c8239efcc98d417f36b0a31d9be01ba5/doctr/local.py#L314-L335 | def generate_ssh_key():
"""
Generates an SSH deploy public and private key.
Returns (private key, public key), a tuple of byte strings.
"""
key = rsa.generate_private_key(
backend=default_backend(),
public_exponent=65537,
key_size=4096
)
private_key = key.privat... | [
"def",
"generate_ssh_key",
"(",
")",
":",
"key",
"=",
"rsa",
".",
"generate_private_key",
"(",
"backend",
"=",
"default_backend",
"(",
")",
",",
"public_exponent",
"=",
"65537",
",",
"key_size",
"=",
"4096",
")",
"private_key",
"=",
"key",
".",
"private_byte... | Generates an SSH deploy public and private key.
Returns (private key, public key), a tuple of byte strings. | [
"Generates",
"an",
"SSH",
"deploy",
"public",
"and",
"private",
"key",
"."
] | python | train | 27.136364 |
saltstack/salt | salt/modules/boto_apigateway.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L856-L879 | def create_api_stage(restApiId, stageName, deploymentId, description='',
cacheClusterEnabled=False, cacheClusterSize='0.5', variables=None,
region=None, key=None, keyid=None, profile=None):
'''
Creates a new API stage for a given restApiId and deploymentId.
CLI Exa... | [
"def",
"create_api_stage",
"(",
"restApiId",
",",
"stageName",
",",
"deploymentId",
",",
"description",
"=",
"''",
",",
"cacheClusterEnabled",
"=",
"False",
",",
"cacheClusterSize",
"=",
"'0.5'",
",",
"variables",
"=",
"None",
",",
"region",
"=",
"None",
",",
... | Creates a new API stage for a given restApiId and deploymentId.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.create_api_stage restApiId stagename deploymentId \\
description='' cacheClusterEnabled=True|False cacheClusterSize='0.5' variables='{"name": "value"}' | [
"Creates",
"a",
"new",
"API",
"stage",
"for",
"a",
"given",
"restApiId",
"and",
"deploymentId",
"."
] | python | train | 48.416667 |
bmcfee/muda | muda/base.py | https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/base.py#L227-L242 | def transform(self, jam):
'''Apply the sequence of transformations to a single jam object.
Parameters
----------
jam : jams.JAMS
The jam object to transform
Yields
------
jam_out : jams.JAMS
The jam objects produced by the transformation ... | [
"def",
"transform",
"(",
"self",
",",
"jam",
")",
":",
"for",
"output",
"in",
"self",
".",
"__recursive_transform",
"(",
"jam",
",",
"self",
".",
"steps",
")",
":",
"yield",
"output"
] | Apply the sequence of transformations to a single jam object.
Parameters
----------
jam : jams.JAMS
The jam object to transform
Yields
------
jam_out : jams.JAMS
The jam objects produced by the transformation sequence | [
"Apply",
"the",
"sequence",
"of",
"transformations",
"to",
"a",
"single",
"jam",
"object",
"."
] | python | valid | 26.125 |
raphaelvallat/pingouin | pingouin/power.py | https://github.com/raphaelvallat/pingouin/blob/58b19fa4fffbfe09d58b456e3926a148249e4d9b/pingouin/power.py#L523-L667 | def power_corr(r=None, n=None, power=None, alpha=0.05, tail='two-sided'):
"""
Evaluate power, sample size, correlation coefficient or
significance level of a correlation test.
Parameters
----------
r : float
Correlation coefficient.
n : int
Number of observations (sample siz... | [
"def",
"power_corr",
"(",
"r",
"=",
"None",
",",
"n",
"=",
"None",
",",
"power",
"=",
"None",
",",
"alpha",
"=",
"0.05",
",",
"tail",
"=",
"'two-sided'",
")",
":",
"# Check the number of arguments that are None",
"n_none",
"=",
"sum",
"(",
"[",
"v",
"is"... | Evaluate power, sample size, correlation coefficient or
significance level of a correlation test.
Parameters
----------
r : float
Correlation coefficient.
n : int
Number of observations (sample size).
power : float
Test power (= 1 - type II error).
alpha : float
... | [
"Evaluate",
"power",
"sample",
"size",
"correlation",
"coefficient",
"or",
"significance",
"level",
"of",
"a",
"correlation",
"test",
"."
] | python | train | 32.296552 |
genialis/genesis-pyapi | genesis/genesis.py | https://github.com/genialis/genesis-pyapi/blob/dfe9bcc8b332a8b9873db4ab9994b0cc10eb209a/genesis/genesis.py#L108-L157 | def data(self, **query):
"""Query for Data object annotation."""
objects = self.cache['objects']
data = self.api.data.get(**query)['objects']
data_objects = []
for d in data:
_id = d['id']
if _id in objects:
# Update existing object
... | [
"def",
"data",
"(",
"self",
",",
"*",
"*",
"query",
")",
":",
"objects",
"=",
"self",
".",
"cache",
"[",
"'objects'",
"]",
"data",
"=",
"self",
".",
"api",
".",
"data",
".",
"get",
"(",
"*",
"*",
"query",
")",
"[",
"'objects'",
"]",
"data_objects... | Query for Data object annotation. | [
"Query",
"for",
"Data",
"object",
"annotation",
"."
] | python | test | 37.1 |
gccxml/pygccxml | pygccxml/parser/declarations_cache.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/declarations_cache.py#L17-L34 | def file_signature(filename):
"""
Return a signature for a file.
"""
if not os.path.isfile(filename):
return None
if not os.path.exists(filename):
return None
# Duplicate auto-generated files can be recognized with the sha1 hash.
sig = hashlib.sha1()
with open(filename... | [
"def",
"file_signature",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"None",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"None",
"# Duplicate aut... | Return a signature for a file. | [
"Return",
"a",
"signature",
"for",
"a",
"file",
"."
] | python | train | 21.722222 |
Nachtfeuer/pipeline | spline/components/tasks.py | https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/components/tasks.py#L98-L127 | def prepare_shell_data(self, shells, key, entry):
"""Prepare one shell or docker task."""
if self.can_process_shell(entry):
if key in ['python']:
entry['type'] = key
if 'with' in entry and isinstance(entry['with'], str):
rendered_with = ast.litera... | [
"def",
"prepare_shell_data",
"(",
"self",
",",
"shells",
",",
"key",
",",
"entry",
")",
":",
"if",
"self",
".",
"can_process_shell",
"(",
"entry",
")",
":",
"if",
"key",
"in",
"[",
"'python'",
"]",
":",
"entry",
"[",
"'type'",
"]",
"=",
"key",
"if",
... | Prepare one shell or docker task. | [
"Prepare",
"one",
"shell",
"or",
"docker",
"task",
"."
] | python | train | 47.333333 |
nephila/django-knocker | knocker/consumers.py | https://github.com/nephila/django-knocker/blob/d25380d43a1f91285f1581dcf9db8510fe87f354/knocker/consumers.py#L9-L18 | def ws_connect(message):
"""
Channels connection setup.
Register the current client on the related Group according to the language
"""
prefix, language = message['path'].strip('/').split('/')
gr = Group('knocker-{0}'.format(language))
gr.add(message.reply_channel)
message.channel_session... | [
"def",
"ws_connect",
"(",
"message",
")",
":",
"prefix",
",",
"language",
"=",
"message",
"[",
"'path'",
"]",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"gr",
"=",
"Group",
"(",
"'knocker-{0}'",
".",
"format",
"(",
"language",
")",... | Channels connection setup.
Register the current client on the related Group according to the language | [
"Channels",
"connection",
"setup",
".",
"Register",
"the",
"current",
"client",
"on",
"the",
"related",
"Group",
"according",
"to",
"the",
"language"
] | python | train | 38.2 |
pybel/pybel-tools | src/pybel_tools/mutation/expansion.py | https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/expansion.py#L299-L324 | def expand_internal(universe: BELGraph, graph: BELGraph, edge_predicates: EdgePredicates = None) -> None:
"""Edges between entities in the sub-graph that pass the given filters.
:param universe: The full graph
:param graph: A sub-graph to find the upstream information
:param edge_predicates: Optional l... | [
"def",
"expand_internal",
"(",
"universe",
":",
"BELGraph",
",",
"graph",
":",
"BELGraph",
",",
"edge_predicates",
":",
"EdgePredicates",
"=",
"None",
")",
"->",
"None",
":",
"edge_filter",
"=",
"and_edge_predicates",
"(",
"edge_predicates",
")",
"for",
"u",
"... | Edges between entities in the sub-graph that pass the given filters.
:param universe: The full graph
:param graph: A sub-graph to find the upstream information
:param edge_predicates: Optional list of edge filter functions (graph, node, node, key, data) -> bool | [
"Edges",
"between",
"entities",
"in",
"the",
"sub",
"-",
"graph",
"that",
"pass",
"the",
"given",
"filters",
"."
] | python | valid | 39.346154 |
Fizzadar/pyinfra | pyinfra/modules/mysql.py | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/mysql.py#L306-L328 | def dump(
state, host,
remote_filename, database=None,
# Details for speaking to MySQL via `mysql` CLI
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
'''
Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to d... | [
"def",
"dump",
"(",
"state",
",",
"host",
",",
"remote_filename",
",",
"database",
"=",
"None",
",",
"# Details for speaking to MySQL via `mysql` CLI",
"mysql_user",
"=",
"None",
",",
"mysql_password",
"=",
"None",
",",
"mysql_host",
"=",
"None",
",",
"mysql_port"... | Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to dump
+ remote_filename: name of the file to dump the SQL to
+ mysql_*: global module arguments, see above | [
"Dump",
"a",
"MySQL",
"database",
"into",
"a",
".",
"sql",
"file",
".",
"Requires",
"mysqldump",
"."
] | python | train | 28.652174 |
apache/airflow | scripts/perf/scheduler_ops_metrics.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/scripts/perf/scheduler_ops_metrics.py#L103-L135 | def heartbeat(self):
"""
Override the scheduler heartbeat to determine when the test is complete
"""
super(SchedulerMetricsJob, self).heartbeat()
session = settings.Session()
# Get all the relevant task instances
TI = TaskInstance
successful_tis = (
... | [
"def",
"heartbeat",
"(",
"self",
")",
":",
"super",
"(",
"SchedulerMetricsJob",
",",
"self",
")",
".",
"heartbeat",
"(",
")",
"session",
"=",
"settings",
".",
"Session",
"(",
")",
"# Get all the relevant task instances",
"TI",
"=",
"TaskInstance",
"successful_ti... | Override the scheduler heartbeat to determine when the test is complete | [
"Override",
"the",
"scheduler",
"heartbeat",
"to",
"determine",
"when",
"the",
"test",
"is",
"complete"
] | python | test | 38.818182 |
SatelliteQE/nailgun | nailgun/entities.py | https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L4684-L4692 | def create(self, create_missing=None):
"""Manually fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1216236
<https://bugzilla.redhat.com/show_bug.cgi?id=1216236>`_.
"""
attrs = self.create_json(create_missing)
return Location(self... | [
"def",
"create",
"(",
"self",
",",
"create_missing",
"=",
"None",
")",
":",
"attrs",
"=",
"self",
".",
"create_json",
"(",
"create_missing",
")",
"return",
"Location",
"(",
"self",
".",
"_server_config",
",",
"id",
"=",
"attrs",
"[",
"'id'",
"]",
")",
... | Manually fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1216236
<https://bugzilla.redhat.com/show_bug.cgi?id=1216236>`_. | [
"Manually",
"fetch",
"a",
"complete",
"set",
"of",
"attributes",
"for",
"this",
"entity",
"."
] | python | train | 39 |
SpriteLink/NIPAP | nipap/nipap/backend.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap/nipap/backend.py#L3954-L4050 | def search_asn(self, auth, query, search_options=None):
""" Search ASNs for entries matching 'query'
* `auth` [BaseAuth]
AAA options.
* `query` [dict_to_sql]
How the search should be performed.
* `search_options` [options_dict]
... | [
"def",
"search_asn",
"(",
"self",
",",
"auth",
",",
"query",
",",
"search_options",
"=",
"None",
")",
":",
"if",
"search_options",
"is",
"None",
":",
"search_options",
"=",
"{",
"}",
"#",
"# sanitize search options and set default if option missing",
"#",
"# max_r... | Search ASNs for entries matching 'query'
* `auth` [BaseAuth]
AAA options.
* `query` [dict_to_sql]
How the search should be performed.
* `search_options` [options_dict]
Search options, see below.
Returns a list of dicts.
... | [
"Search",
"ASNs",
"for",
"entries",
"matching",
"query"
] | python | train | 39.494845 |
blockstack/blockstack-core | blockstack/lib/snv.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/snv.py#L58-L68 | def get_bitcoind_client():
"""
Connect to the bitcoind node
"""
bitcoind_opts = get_bitcoin_opts()
bitcoind_host = bitcoind_opts['bitcoind_server']
bitcoind_port = bitcoind_opts['bitcoind_port']
bitcoind_user = bitcoind_opts['bitcoind_user']
bitcoind_passwd = bitcoind_opts['bitcoind_pass... | [
"def",
"get_bitcoind_client",
"(",
")",
":",
"bitcoind_opts",
"=",
"get_bitcoin_opts",
"(",
")",
"bitcoind_host",
"=",
"bitcoind_opts",
"[",
"'bitcoind_server'",
"]",
"bitcoind_port",
"=",
"bitcoind_opts",
"[",
"'bitcoind_port'",
"]",
"bitcoind_user",
"=",
"bitcoind_o... | Connect to the bitcoind node | [
"Connect",
"to",
"the",
"bitcoind",
"node"
] | python | train | 39.454545 |
SALib/SALib | src/SALib/sample/morris/local.py | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/local.py#L91-L121 | def sum_distances(self, indices, distance_matrix):
"""Calculate combinatorial distance between a select group of
trajectories, indicated by indices
Arguments
---------
indices : tuple
distance_matrix : numpy.ndarray (M,M)
Returns
-------
numpy.nd... | [
"def",
"sum_distances",
"(",
"self",
",",
"indices",
",",
"distance_matrix",
")",
":",
"combs_tup",
"=",
"np",
".",
"array",
"(",
"tuple",
"(",
"combinations",
"(",
"indices",
",",
"2",
")",
")",
")",
"# Put indices from tuples into two-dimensional array.",
"com... | Calculate combinatorial distance between a select group of
trajectories, indicated by indices
Arguments
---------
indices : tuple
distance_matrix : numpy.ndarray (M,M)
Returns
-------
numpy.ndarray
Notes
-----
This function can p... | [
"Calculate",
"combinatorial",
"distance",
"between",
"a",
"select",
"group",
"of",
"trajectories",
"indicated",
"by",
"indices"
] | python | train | 32.548387 |
gholt/swiftly | swiftly/cli/iomanager.py | https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L98-L108 | def os_path_to_client_path(self, os_path):
"""
Converts an operating system path into a client path by
replacing instances of os.path.sep with '/'.
Note: If the client path contains any instances of '/'
already, they will be replaced with '-'.
"""
if os.path.sep ... | [
"def",
"os_path_to_client_path",
"(",
"self",
",",
"os_path",
")",
":",
"if",
"os",
".",
"path",
".",
"sep",
"==",
"'/'",
":",
"return",
"os_path",
"return",
"os_path",
".",
"replace",
"(",
"'/'",
",",
"'-'",
")",
".",
"replace",
"(",
"os",
".",
"pat... | Converts an operating system path into a client path by
replacing instances of os.path.sep with '/'.
Note: If the client path contains any instances of '/'
already, they will be replaced with '-'. | [
"Converts",
"an",
"operating",
"system",
"path",
"into",
"a",
"client",
"path",
"by",
"replacing",
"instances",
"of",
"os",
".",
"path",
".",
"sep",
"with",
"/",
"."
] | python | test | 37.363636 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L403-L409 | def yank_last_arg(event):
"""
Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line.
"""
n = (event.arg if event.arg_present else None)
event.current_buffer.yank_last_arg(n) | [
"def",
"yank_last_arg",
"(",
"event",
")",
":",
"n",
"=",
"(",
"event",
".",
"arg",
"if",
"event",
".",
"arg_present",
"else",
"None",
")",
"event",
".",
"current_buffer",
".",
"yank_last_arg",
"(",
"n",
")"
] | Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line. | [
"Like",
"yank_nth_arg",
"but",
"if",
"no",
"argument",
"has",
"been",
"given",
"yank",
"the",
"last",
"word",
"of",
"each",
"line",
"."
] | python | train | 32.142857 |
rycus86/prometheus_flask_exporter | prometheus_flask_exporter/__init__.py | https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L480-L495 | def do_not_track():
"""
Decorator to skip the default metrics collection for the method.
*Note*: explicit metrics decorators will still collect the data
"""
def decorator(f):
@functools.wraps(f)
def func(*args, **kwargs):
request.prom_do_... | [
"def",
"do_not_track",
"(",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
".",
"prom_do_not_track",
"=",
"True",
"retu... | Decorator to skip the default metrics collection for the method.
*Note*: explicit metrics decorators will still collect the data | [
"Decorator",
"to",
"skip",
"the",
"default",
"metrics",
"collection",
"for",
"the",
"method",
"."
] | python | train | 25.875 |
rabitt/pysox | sox/file_info.py | https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L134-L153 | def num_samples(input_filepath):
'''
Show number of samples (0 if unavailable).
Parameters
----------
input_filepath : str
Path to audio file.
Returns
-------
n_samples : int
total number of samples in audio file.
Returns 0 if empty or unavailable
'''
va... | [
"def",
"num_samples",
"(",
"input_filepath",
")",
":",
"validate_input_file",
"(",
"input_filepath",
")",
"output",
"=",
"soxi",
"(",
"input_filepath",
",",
"'s'",
")",
"if",
"output",
"==",
"'0'",
":",
"logger",
".",
"warning",
"(",
"\"Number of samples unavail... | Show number of samples (0 if unavailable).
Parameters
----------
input_filepath : str
Path to audio file.
Returns
-------
n_samples : int
total number of samples in audio file.
Returns 0 if empty or unavailable | [
"Show",
"number",
"of",
"samples",
"(",
"0",
"if",
"unavailable",
")",
"."
] | python | valid | 24.85 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_util.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L192-L208 | def decode_and_resize(image_str_tensor):
"""Decodes jpeg string, resizes it and returns a uint8 tensor."""
# These constants are set by Inception v3's expectations.
height = 299
width = 299
channels = 3
image = tf.image.decode_jpeg(image_str_tensor, channels=channels)
# Note resize expects a batch_size,... | [
"def",
"decode_and_resize",
"(",
"image_str_tensor",
")",
":",
"# These constants are set by Inception v3's expectations.",
"height",
"=",
"299",
"width",
"=",
"299",
"channels",
"=",
"3",
"image",
"=",
"tf",
".",
"image",
".",
"decode_jpeg",
"(",
"image_str_tensor",
... | Decodes jpeg string, resizes it and returns a uint8 tensor. | [
"Decodes",
"jpeg",
"string",
"resizes",
"it",
"and",
"returns",
"a",
"uint8",
"tensor",
"."
] | python | train | 38.294118 |
graphql-python/graphql-core | graphql/execution/values.py | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/values.py#L34-L86 | def get_variable_values(
schema, # type: GraphQLSchema
definition_asts, # type: List[VariableDefinition]
inputs, # type: Any
):
# type: (...) -> Dict[str, Any]
"""Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the inp... | [
"def",
"get_variable_values",
"(",
"schema",
",",
"# type: GraphQLSchema",
"definition_asts",
",",
"# type: List[VariableDefinition]",
"inputs",
",",
"# type: Any",
")",
":",
"# type: (...) -> Dict[str, Any]",
"if",
"inputs",
"is",
"None",
":",
"inputs",
"=",
"{",
"}",
... | Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the input cannot be parsed to match the variable definitions, a GraphQLError will be thrown. | [
"Prepares",
"an",
"object",
"map",
"of",
"variables",
"of",
"the",
"correct",
"type",
"based",
"on",
"the",
"provided",
"variable",
"definitions",
"and",
"arbitrary",
"input",
".",
"If",
"the",
"input",
"cannot",
"be",
"parsed",
"to",
"match",
"the",
"variab... | python | train | 39.226415 |
Chilipp/psyplot | psyplot/data.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3855-L4013 | def array_info(self, dump=None, paths=None, attrs=True,
standardize_dims=True, pwd=None, use_rel_paths=True,
alternative_paths={}, ds_description={'fname', 'store'},
full_ds=True, copy=False, **kwargs):
"""
Get dimension informations on you arrays... | [
"def",
"array_info",
"(",
"self",
",",
"dump",
"=",
"None",
",",
"paths",
"=",
"None",
",",
"attrs",
"=",
"True",
",",
"standardize_dims",
"=",
"True",
",",
"pwd",
"=",
"None",
",",
"use_rel_paths",
"=",
"True",
",",
"alternative_paths",
"=",
"{",
"}",... | Get dimension informations on you arrays
This method returns a dictionary containing informations on the
array in this instance
Parameters
----------
dump: bool
If True and the dataset has not been dumped so far, it is dumped to
a temporary file or the o... | [
"Get",
"dimension",
"informations",
"on",
"you",
"arrays"
] | python | train | 42.314465 |
brainiak/brainiak | brainiak/isc.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/isc.py#L1386-L1519 | def phaseshift_isc(data, pairwise=False, summary_statistic='median',
n_shifts=1000, tolerate_nans=True, random_state=None):
"""Phase randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where response time seri... | [
"def",
"phaseshift_isc",
"(",
"data",
",",
"pairwise",
"=",
"False",
",",
"summary_statistic",
"=",
"'median'",
",",
"n_shifts",
"=",
"1000",
",",
"tolerate_nans",
"=",
"True",
",",
"random_state",
"=",
"None",
")",
":",
"# Check response time series input format"... | Phase randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where response time series
are phase randomized prior to computing ISC. If pairwise,
apply phase randomization to each subject and compute pairwise
ISCs. If leave-... | [
"Phase",
"randomization",
"for",
"one",
"-",
"sample",
"ISC",
"test"
] | python | train | 42.850746 |
astroML/gatspy | gatspy/datasets/rrlyrae.py | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L125-L173 | def get_lightcurve(self, star_id, return_1d=True):
"""Get the light curves for the given ID
Parameters
----------
star_id : int
A valid integer star id representing an object in the dataset
return_1d : boolean (default=True)
Specify whether to return 1D a... | [
"def",
"get_lightcurve",
"(",
"self",
",",
"star_id",
",",
"return_1d",
"=",
"True",
")",
":",
"filename",
"=",
"'{0}/{1}.dat'",
".",
"format",
"(",
"self",
".",
"dirname",
",",
"star_id",
")",
"try",
":",
"data",
"=",
"np",
".",
"loadtxt",
"(",
"self"... | Get the light curves for the given ID
Parameters
----------
star_id : int
A valid integer star id representing an object in the dataset
return_1d : boolean (default=True)
Specify whether to return 1D arrays of (t, y, dy, filts) or
2D arrays of (t, y, ... | [
"Get",
"the",
"light",
"curves",
"for",
"the",
"given",
"ID"
] | python | train | 33.714286 |
greenelab/PathCORE-T | pathcore/network.py | https://github.com/greenelab/PathCORE-T/blob/9d079d5ebffea2fe9fb9ab557588d51ad67d2c9c/pathcore/network.py#L568-L652 | def _pathway_feature_permutation(pathway_feature_tuples,
permutation_max_iters):
"""Permute the pathways across features for one side in the
network. Used in `permute_pathways_across_features`
Parameters
-----------
pathway_feature_tuples : list(tup(str, int))
... | [
"def",
"_pathway_feature_permutation",
"(",
"pathway_feature_tuples",
",",
"permutation_max_iters",
")",
":",
"pathways",
",",
"features",
"=",
"[",
"list",
"(",
"elements_at_position",
")",
"for",
"elements_at_position",
"in",
"zip",
"(",
"*",
"pathway_feature_tuples",... | Permute the pathways across features for one side in the
network. Used in `permute_pathways_across_features`
Parameters
-----------
pathway_feature_tuples : list(tup(str, int))
a tuple list [(pathway, feature)] where the pathway, feature pairing
indicates that a pathway was overrepresented ... | [
"Permute",
"the",
"pathways",
"across",
"features",
"for",
"one",
"side",
"in",
"the",
"network",
".",
"Used",
"in",
"permute_pathways_across_features"
] | python | train | 43.964706 |
tensorflow/cleverhans | cleverhans/plot/success_fail.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/success_fail.py#L18-L54 | def plot_report_from_path(path, success_name=DEFAULT_SUCCESS_NAME,
fail_names=DEFAULT_FAIL_NAMES, label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True):
"""
Plots a success-fail curve fr... | [
"def",
"plot_report_from_path",
"(",
"path",
",",
"success_name",
"=",
"DEFAULT_SUCCESS_NAME",
",",
"fail_names",
"=",
"DEFAULT_FAIL_NAMES",
",",
"label",
"=",
"None",
",",
"is_max_confidence",
"=",
"True",
",",
"linewidth",
"=",
"LINEWIDTH",
",",
"plot_upper_bound"... | Plots a success-fail curve from a confidence report stored on disk,
:param path: string filepath for the stored report.
(Should be the output of make_confidence_report*.py)
:param success_name: The name (confidence report key) of the data that
should be used to measure success rate
:param fail_names: A li... | [
"Plots",
"a",
"success",
"-",
"fail",
"curve",
"from",
"a",
"confidence",
"report",
"stored",
"on",
"disk",
":",
"param",
"path",
":",
"string",
"filepath",
"for",
"the",
"stored",
"report",
".",
"(",
"Should",
"be",
"the",
"output",
"of",
"make_confidence... | python | train | 57.972973 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/textio.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/textio.py#L197-L235 | def integer_list_file(cls, filename):
"""
Read a list of integers from a file.
The file format is:
- # anywhere in the line begins a comment
- leading and trailing spaces are ignored
- empty lines are ignored
- integers can be specified as:
- dec... | [
"def",
"integer_list_file",
"(",
"cls",
",",
"filename",
")",
":",
"count",
"=",
"0",
"result",
"=",
"list",
"(",
")",
"fd",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"for",
"line",
"in",
"fd",
":",
"count",
"=",
"count",
"+",
"1",
"if",
"'#... | Read a list of integers from a file.
The file format is:
- # anywhere in the line begins a comment
- leading and trailing spaces are ignored
- empty lines are ignored
- integers can be specified as:
- decimal numbers ("100" is 100)
- hexadecimal numb... | [
"Read",
"a",
"list",
"of",
"integers",
"from",
"a",
"file",
"."
] | python | train | 31.923077 |
shaunduncan/smokesignal | smokesignal.py | https://github.com/shaunduncan/smokesignal/blob/7906ad0e469b5d4121377c9ee67f77d2f140f2b9/smokesignal.py#L242-L249 | def clear(*signals):
"""
Clears all callbacks for a particular signal or signals
"""
signals = signals if signals else receivers.keys()
for signal in signals:
receivers[signal].clear() | [
"def",
"clear",
"(",
"*",
"signals",
")",
":",
"signals",
"=",
"signals",
"if",
"signals",
"else",
"receivers",
".",
"keys",
"(",
")",
"for",
"signal",
"in",
"signals",
":",
"receivers",
"[",
"signal",
"]",
".",
"clear",
"(",
")"
] | Clears all callbacks for a particular signal or signals | [
"Clears",
"all",
"callbacks",
"for",
"a",
"particular",
"signal",
"or",
"signals"
] | python | train | 25.75 |
icholy/durationpy | durationpy/duration.py | https://github.com/icholy/durationpy/blob/c67ec62dc6e28807c8a06a23074459cf1671aac0/durationpy/duration.py#L33-L58 | def from_str(duration):
"""Parse a duration string to a datetime.timedelta"""
if duration in ("0", "+0", "-0"):
return datetime.timedelta()
pattern = re.compile('([\d\.]+)([a-zµμ]+)')
total = 0
sign = -1 if duration[0] == '-' else 1
matches = pattern.findall(duration)
if not len(m... | [
"def",
"from_str",
"(",
"duration",
")",
":",
"if",
"duration",
"in",
"(",
"\"0\"",
",",
"\"+0\"",
",",
"\"-0\"",
")",
":",
"return",
"datetime",
".",
"timedelta",
"(",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'([\\d\\.]+)([a-zµμ]+)')",
"",
"tota... | Parse a duration string to a datetime.timedelta | [
"Parse",
"a",
"duration",
"string",
"to",
"a",
"datetime",
".",
"timedelta"
] | python | train | 31.730769 |
deepmipt/DeepPavlov | deeppavlov/agents/rich_content/default_rich_content.py | https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/agents/rich_content/default_rich_content.py#L152-L170 | def json(self) -> dict:
"""Returns json compatible state of the ButtonsFrame instance.
Returns json compatible state of the ButtonsFrame instance including
all nested buttons.
Returns:
control_json: Json representation of ButtonsFrame state.
"""
content = {}... | [
"def",
"json",
"(",
"self",
")",
"->",
"dict",
":",
"content",
"=",
"{",
"}",
"if",
"self",
".",
"text",
":",
"content",
"[",
"'text'",
"]",
"=",
"self",
".",
"text",
"content",
"[",
"'controls'",
"]",
"=",
"[",
"control",
".",
"json",
"(",
")",
... | Returns json compatible state of the ButtonsFrame instance.
Returns json compatible state of the ButtonsFrame instance including
all nested buttons.
Returns:
control_json: Json representation of ButtonsFrame state. | [
"Returns",
"json",
"compatible",
"state",
"of",
"the",
"ButtonsFrame",
"instance",
"."
] | python | test | 27.526316 |
corydolphin/flask-cors | flask_cors/core.py | https://github.com/corydolphin/flask-cors/blob/13fbb1ea4c1bb422de91a726c3c7f1038d3743a3/flask_cors/core.py#L349-L378 | def serialize_options(opts):
"""
A helper method to serialize and processes the options dictionary.
"""
options = (opts or {}).copy()
for key in opts.keys():
if key not in DEFAULT_OPTIONS:
LOG.warning("Unknown option passed to Flask-CORS: %s", key)
# Ensure origins is a li... | [
"def",
"serialize_options",
"(",
"opts",
")",
":",
"options",
"=",
"(",
"opts",
"or",
"{",
"}",
")",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"opts",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"DEFAULT_OPTIONS",
":",
"LOG",
".",
"war... | A helper method to serialize and processes the options dictionary. | [
"A",
"helper",
"method",
"to",
"serialize",
"and",
"processes",
"the",
"options",
"dictionary",
"."
] | python | valid | 38.966667 |
openearth/bmi-python | bmi/wrapper.py | https://github.com/openearth/bmi-python/blob/2f53f24d45515eb0711c2d28ddd6c1582045248f/bmi/wrapper.py#L429-L438 | def inq_compound(self, name):
"""
Return the number of fields and size (not yet) of a compound type.
"""
name = create_string_buffer(name)
self.library.inq_compound.argtypes = [c_char_p, POINTER(c_int)]
self.library.inq_compound.restype = None
nfields = c_int()
... | [
"def",
"inq_compound",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"create_string_buffer",
"(",
"name",
")",
"self",
".",
"library",
".",
"inq_compound",
".",
"argtypes",
"=",
"[",
"c_char_p",
",",
"POINTER",
"(",
"c_int",
")",
"]",
"self",
".",
"... | Return the number of fields and size (not yet) of a compound type. | [
"Return",
"the",
"number",
"of",
"fields",
"and",
"size",
"(",
"not",
"yet",
")",
"of",
"a",
"compound",
"type",
"."
] | python | train | 39.3 |
apache/airflow | airflow/contrib/hooks/mongo_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L281-L297 | def delete_many(self, mongo_collection, filter_doc, mongo_db=None, **kwargs):
"""
Deletes one or more documents in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
:param mongo_collection: The name of the co... | [
"def",
"delete_many",
"(",
"self",
",",
"mongo_collection",
",",
"filter_doc",
",",
"mongo_db",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"collection",
"=",
"self",
".",
"get_collection",
"(",
"mongo_collection",
",",
"mongo_db",
"=",
"mongo_db",
")",
... | Deletes one or more documents in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
:param mongo_collection: The name of the collection to delete from.
:type mongo_collection: str
:param filter_doc: A query th... | [
"Deletes",
"one",
"or",
"more",
"documents",
"in",
"a",
"mongo",
"collection",
".",
"https",
":",
"//",
"api",
".",
"mongodb",
".",
"com",
"/",
"python",
"/",
"current",
"/",
"api",
"/",
"pymongo",
"/",
"collection",
".",
"html#pymongo",
".",
"collection... | python | test | 46.352941 |
learningequality/morango | morango/api/permissions.py | https://github.com/learningequality/morango/blob/c3ec2554b026f65ac5f0fc5c9d439277fbac14f9/morango/api/permissions.py#L15-L43 | def authenticate_credentials(self, userargs, password, request=None):
"""
Authenticate the userargs and password against Django auth backends.
The "userargs" string may be just the username, or a querystring-encoded set of params.
"""
credentials = {
'password': pass... | [
"def",
"authenticate_credentials",
"(",
"self",
",",
"userargs",
",",
"password",
",",
"request",
"=",
"None",
")",
":",
"credentials",
"=",
"{",
"'password'",
":",
"password",
"}",
"if",
"\"=\"",
"not",
"in",
"userargs",
":",
"# if it doesn't seem to be in quer... | Authenticate the userargs and password against Django auth backends.
The "userargs" string may be just the username, or a querystring-encoded set of params. | [
"Authenticate",
"the",
"userargs",
"and",
"password",
"against",
"Django",
"auth",
"backends",
".",
"The",
"userargs",
"string",
"may",
"be",
"just",
"the",
"username",
"or",
"a",
"querystring",
"-",
"encoded",
"set",
"of",
"params",
"."
] | python | valid | 36.793103 |
apache/incubator-mxnet | example/gluon/lipnet/utils/download_data.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/download_data.py#L28-L52 | def download_mp4(from_idx, to_idx, _params):
"""
download mp4s
"""
succ = set()
fail = set()
for idx in range(from_idx, to_idx):
name = 's' + str(idx)
save_folder = '{src_path}/{nm}'.format(src_path=_params['src_path'], nm=name)
if idx == 0 or os.path.isdir(save_folder):
... | [
"def",
"download_mp4",
"(",
"from_idx",
",",
"to_idx",
",",
"_params",
")",
":",
"succ",
"=",
"set",
"(",
")",
"fail",
"=",
"set",
"(",
")",
"for",
"idx",
"in",
"range",
"(",
"from_idx",
",",
"to_idx",
")",
":",
"name",
"=",
"'s'",
"+",
"str",
"(... | download mp4s | [
"download",
"mp4s"
] | python | train | 37.4 |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2552-L2572 | def _parse_prefix_as_idd(idd_pattern, number):
"""Strips the IDD from the start of the number if present.
Helper function used by _maybe_strip_i18n_prefix_and_normalize().
Returns a 2-tuple:
- Boolean indicating if IDD was stripped
- Number with IDD stripped
"""
match = idd_pattern.mat... | [
"def",
"_parse_prefix_as_idd",
"(",
"idd_pattern",
",",
"number",
")",
":",
"match",
"=",
"idd_pattern",
".",
"match",
"(",
"number",
")",
"if",
"match",
":",
"match_end",
"=",
"match",
".",
"end",
"(",
")",
"# Only strip this if the first digit after the match is... | Strips the IDD from the start of the number if present.
Helper function used by _maybe_strip_i18n_prefix_and_normalize().
Returns a 2-tuple:
- Boolean indicating if IDD was stripped
- Number with IDD stripped | [
"Strips",
"the",
"IDD",
"from",
"the",
"start",
"of",
"the",
"number",
"if",
"present",
"."
] | python | train | 38.666667 |
Unidata/siphon | siphon/simplewebservice/iastate.py | https://github.com/Unidata/siphon/blob/53fb0d84fbce1c18c8e81c9e68bc81620ee0a6ac/siphon/simplewebservice/iastate.py#L53-L75 | def request_all_data(cls, time, pressure=None, **kwargs):
"""Retrieve upper air observations from Iowa State's archive for all stations.
Parameters
----------
time : datetime
The date and time of the desired observation.
pressure : float, optional
The ma... | [
"def",
"request_all_data",
"(",
"cls",
",",
"time",
",",
"pressure",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"endpoint",
"=",
"cls",
"(",
")",
"df",
"=",
"endpoint",
".",
"_get_data",
"(",
"time",
",",
"None",
",",
"pressure",
",",
"*",
"*"... | Retrieve upper air observations from Iowa State's archive for all stations.
Parameters
----------
time : datetime
The date and time of the desired observation.
pressure : float, optional
The mandatory pressure level at which to request data (in hPa). If none is ... | [
"Retrieve",
"upper",
"air",
"observations",
"from",
"Iowa",
"State",
"s",
"archive",
"for",
"all",
"stations",
"."
] | python | train | 31.826087 |
cortical-io/retina-sdk.py | retinasdk/full_client.py | https://github.com/cortical-io/retina-sdk.py/blob/474c13ad399fe1e974d2650335537608f4456b07/retinasdk/full_client.py#L116-L126 | def getTokensForText(self, body, POStags=None):
"""Get tokenized input text
Args:
body, str: The text to be tokenized (required)
POStags, str: Specify desired POS types (optional)
Returns:
list of str
Raises:
CorticalioException: if the req... | [
"def",
"getTokensForText",
"(",
"self",
",",
"body",
",",
"POStags",
"=",
"None",
")",
":",
"return",
"self",
".",
"_text",
".",
"getTokensForText",
"(",
"self",
".",
"_retina",
",",
"body",
",",
"POStags",
")"
] | Get tokenized input text
Args:
body, str: The text to be tokenized (required)
POStags, str: Specify desired POS types (optional)
Returns:
list of str
Raises:
CorticalioException: if the request was not successful | [
"Get",
"tokenized",
"input",
"text",
"Args",
":",
"body",
"str",
":",
"The",
"text",
"to",
"be",
"tokenized",
"(",
"required",
")",
"POStags",
"str",
":",
"Specify",
"desired",
"POS",
"types",
"(",
"optional",
")",
"Returns",
":",
"list",
"of",
"str",
... | python | train | 37.909091 |
pypa/pipenv | pipenv/vendor/pexpect/screen.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L138-L144 | def pretty (self):
'''This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box.'''
top_bot = u'+' + u'-'*self.cols + u'+\n'
return top_bot + u'\n'.join([u'|'+line+u'|' ... | [
"def",
"pretty",
"(",
"self",
")",
":",
"top_bot",
"=",
"u'+'",
"+",
"u'-'",
"*",
"self",
".",
"cols",
"+",
"u'+\\n'",
"return",
"top_bot",
"+",
"u'\\n'",
".",
"join",
"(",
"[",
"u'|'",
"+",
"line",
"+",
"u'|'",
"for",
"line",
"in",
"unicode",
"(",... | This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box. | [
"This",
"returns",
"a",
"copy",
"of",
"the",
"screen",
"as",
"a",
"unicode",
"string",
"with",
"an",
"ASCII",
"text",
"box",
"around",
"the",
"screen",
"border",
".",
"This",
"is",
"similar",
"to",
"__str__",
"/",
"__unicode__",
"except",
"that",
"it",
"... | python | train | 53.142857 |
marcomusy/vtkplotter | vtkplotter/analysis.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1696-L1729 | def convexHull(actor_or_list, alphaConstant=0):
"""
Create a 3D Delaunay triangulation of input points.
:param actor_or_list: can be either an ``Actor`` or a list of 3D points.
:param float alphaConstant: For a non-zero alpha value, only verts, edges, faces,
or tetra contained within the circum... | [
"def",
"convexHull",
"(",
"actor_or_list",
",",
"alphaConstant",
"=",
"0",
")",
":",
"if",
"vu",
".",
"isSequence",
"(",
"actor_or_list",
")",
":",
"actor",
"=",
"vs",
".",
"Points",
"(",
"actor_or_list",
")",
"else",
":",
"actor",
"=",
"actor_or_list",
... | Create a 3D Delaunay triangulation of input points.
:param actor_or_list: can be either an ``Actor`` or a list of 3D points.
:param float alphaConstant: For a non-zero alpha value, only verts, edges, faces,
or tetra contained within the circumsphere (of radius alpha) will be output.
Otherwise, ... | [
"Create",
"a",
"3D",
"Delaunay",
"triangulation",
"of",
"input",
"points",
"."
] | python | train | 33.529412 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAData/base_datastruct.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L1180-L1199 | def select_day(self, day):
"""选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description]
"""
def _select_day(day):
return self.data.loc[day, slice(None)]
... | [
"def",
"select_day",
"(",
"self",
",",
"day",
")",
":",
"def",
"_select_day",
"(",
"day",
")",
":",
"return",
"self",
".",
"data",
".",
"loc",
"[",
"day",
",",
"slice",
"(",
"None",
")",
"]",
"try",
":",
"return",
"self",
".",
"new",
"(",
"_selec... | 选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description] | [
"选取日期",
"(",
"一般用于分钟线",
")"
] | python | train | 23.45 |
tanghaibao/jcvi | jcvi/formats/bed.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/bed.py#L956-L981 | def mergebydepth(args):
"""
%prog mergebydepth reads.bed genome.fasta
Similar to mergeBed, but only returns regions beyond certain depth.
"""
p = OptionParser(mergebydepth.__doc__)
p.add_option("--mindepth", default=3, type="int",
help="Minimum depth required")
opts, args =... | [
"def",
"mergebydepth",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mergebydepth",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--mindepth\"",
",",
"default",
"=",
"3",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Minimum depth requi... | %prog mergebydepth reads.bed genome.fasta
Similar to mergeBed, but only returns regions beyond certain depth. | [
"%prog",
"mergebydepth",
"reads",
".",
"bed",
"genome",
".",
"fasta"
] | python | train | 32.384615 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tex.py#L865-L976 | def generate_common(env):
"""Add internal Builders and construction variables for LaTeX to an Environment."""
# Add OSX system paths so TeX tools can be found
# when a list of tools is given the exists() method is not called
generate_darwin(env)
# A generic tex file Action, sufficient for all tex ... | [
"def",
"generate_common",
"(",
"env",
")",
":",
"# Add OSX system paths so TeX tools can be found",
"# when a list of tools is given the exists() method is not called",
"generate_darwin",
"(",
"env",
")",
"# A generic tex file Action, sufficient for all tex files.",
"global",
"TeXAction"... | Add internal Builders and construction variables for LaTeX to an Environment. | [
"Add",
"internal",
"Builders",
"and",
"construction",
"variables",
"for",
"LaTeX",
"to",
"an",
"Environment",
"."
] | python | train | 41.75 |
awacha/credolib | credolib/atsas.py | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L443-L518 | def gnom(curve, Rmax, outputfilename=None, Npoints_realspace=None, initial_alpha=None):
"""Run GNOM on the dataset.
Inputs:
curve: an instance of sastool.classes2.Curve or anything which has a
save() method, saving the scattering curve to a given .dat file,
in q=4*pi*sin(theta)/... | [
"def",
"gnom",
"(",
"curve",
",",
"Rmax",
",",
"outputfilename",
"=",
"None",
",",
"Npoints_realspace",
"=",
"None",
",",
"initial_alpha",
"=",
"None",
")",
":",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
"prefix",
"=",
"'credolib_gnom'",
")",
"as",... | Run GNOM on the dataset.
Inputs:
curve: an instance of sastool.classes2.Curve or anything which has a
save() method, saving the scattering curve to a given .dat file,
in q=4*pi*sin(theta)/lambda [1/nm] units
Rmax: the estimated maximum extent of the scattering object, in nm.... | [
"Run",
"GNOM",
"on",
"the",
"dataset",
"."
] | python | train | 55.210526 |
brutasse/graphite-api | graphite_api/_vendor/whisper.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L727-L739 | def info(path):
"""info(path)
path is a string
"""
fh = None
try:
fh = open(path,'rb')
return __readHeader(fh)
finally:
if fh:
fh.close()
return None | [
"def",
"info",
"(",
"path",
")",
":",
"fh",
"=",
"None",
"try",
":",
"fh",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"return",
"__readHeader",
"(",
"fh",
")",
"finally",
":",
"if",
"fh",
":",
"fh",
".",
"close",
"(",
")",
"return",
"None"
] | info(path)
path is a string | [
"info",
"(",
"path",
")"
] | python | train | 12.769231 |
shoebot/shoebot | lib/graph/proximity.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/proximity.py#L23-L46 | def depth_first_search(root, visit=lambda node: False, traversable=lambda node, edge: True):
""" Simple, multi-purpose depth-first search.
Visits all the nodes connected to the root, depth-first.
The visit function is called on each node.
Recursion will stop if it returns True, and ubsequently dfs... | [
"def",
"depth_first_search",
"(",
"root",
",",
"visit",
"=",
"lambda",
"node",
":",
"False",
",",
"traversable",
"=",
"lambda",
"node",
",",
"edge",
":",
"True",
")",
":",
"stop",
"=",
"visit",
"(",
"root",
")",
"root",
".",
"_visited",
"=",
"True",
... | Simple, multi-purpose depth-first search.
Visits all the nodes connected to the root, depth-first.
The visit function is called on each node.
Recursion will stop if it returns True, and ubsequently dfs() will return True.
The traversable function takes the current node and edge,
and returns Tru... | [
"Simple",
"multi",
"-",
"purpose",
"depth",
"-",
"first",
"search",
".",
"Visits",
"all",
"the",
"nodes",
"connected",
"to",
"the",
"root",
"depth",
"-",
"first",
".",
"The",
"visit",
"function",
"is",
"called",
"on",
"each",
"node",
".",
"Recursion",
"w... | python | valid | 38.791667 |
numenta/nupic | examples/tm/tm_high_order.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/tm/tm_high_order.py#L53-L75 | def corruptVector(v1, noiseLevel, numActiveCols):
"""
Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits.
@param v1 (array) binary vector whose copy will be corrupted
@param noiseLevel (float) amount of noise to be applied on the new vector
@param numActiveCols (int) num... | [
"def",
"corruptVector",
"(",
"v1",
",",
"noiseLevel",
",",
"numActiveCols",
")",
":",
"size",
"=",
"len",
"(",
"v1",
")",
"v2",
"=",
"np",
".",
"zeros",
"(",
"size",
",",
"dtype",
"=",
"\"uint32\"",
")",
"bitsToSwap",
"=",
"int",
"(",
"noiseLevel",
"... | Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits.
@param v1 (array) binary vector whose copy will be corrupted
@param noiseLevel (float) amount of noise to be applied on the new vector
@param numActiveCols (int) number of sparse columns that represent an input
@return... | [
"Corrupts",
"a",
"copy",
"of",
"a",
"binary",
"vector",
"by",
"inverting",
"noiseLevel",
"percent",
"of",
"its",
"bits",
"."
] | python | valid | 31 |
Esri/ArcREST | src/arcrest/common/symbology.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/symbology.py#L240-L247 | def value(self):
"""gets the color value"""
return {
"type" : self._type,
"style" : self._style,
"color" : self._color.value,
"width" : self._width
} | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"{",
"\"type\"",
":",
"self",
".",
"_type",
",",
"\"style\"",
":",
"self",
".",
"_style",
",",
"\"color\"",
":",
"self",
".",
"_color",
".",
"value",
",",
"\"width\"",
":",
"self",
".",
"_width",
"}"
] | gets the color value | [
"gets",
"the",
"color",
"value"
] | python | train | 26.75 |
tensorflow/tensor2tensor | tensor2tensor/utils/pruning_utils.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/pruning_utils.py#L27-L33 | def weight(w, sparsity):
"""Weight-level magnitude pruning."""
w_shape = common_layers.shape_list(w)
k = int(np.prod(w_shape[:-1]))
count = tf.to_int32(k * sparsity)
mask = common_layers.weight_targeting(w, count)
return (1 - mask) * w | [
"def",
"weight",
"(",
"w",
",",
"sparsity",
")",
":",
"w_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"w",
")",
"k",
"=",
"int",
"(",
"np",
".",
"prod",
"(",
"w_shape",
"[",
":",
"-",
"1",
"]",
")",
")",
"count",
"=",
"tf",
".",
"to_in... | Weight-level magnitude pruning. | [
"Weight",
"-",
"level",
"magnitude",
"pruning",
"."
] | python | train | 34.428571 |
mwouts/jupytext | jupytext/contentsmanager.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/contentsmanager.py#L222-L293 | def save(self, model, path=''):
"""Save the file model and return the model with no content."""
if model['type'] != 'notebook':
return super(TextFileContentsManager, self).save(model, path)
nbk = model['content']
try:
metadata = nbk.get('metadata')
re... | [
"def",
"save",
"(",
"self",
",",
"model",
",",
"path",
"=",
"''",
")",
":",
"if",
"model",
"[",
"'type'",
"]",
"!=",
"'notebook'",
":",
"return",
"super",
"(",
"TextFileContentsManager",
",",
"self",
")",
".",
"save",
"(",
"model",
",",
"path",
")",
... | Save the file model and return the model with no content. | [
"Save",
"the",
"file",
"model",
"and",
"return",
"the",
"model",
"with",
"no",
"content",
"."
] | python | train | 44.458333 |
cmorisse/ikp3db | ikp3db.py | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L228-L284 | def send(self, command, _id=None, result={}, frames=[], threads=None,
error_messages=[], warning_messages=[], info_messages=[],
exception=None):
""" Build a message from parameters and send it to debugger.
:param command: The command sent to the debugger client.
... | [
"def",
"send",
"(",
"self",
",",
"command",
",",
"_id",
"=",
"None",
",",
"result",
"=",
"{",
"}",
",",
"frames",
"=",
"[",
"]",
",",
"threads",
"=",
"None",
",",
"error_messages",
"=",
"[",
"]",
",",
"warning_messages",
"=",
"[",
"]",
",",
"info... | Build a message from parameters and send it to debugger.
:param command: The command sent to the debugger client.
:type command: str
:param _id: Unique id of the sent message. Right now, it's always `None`
for messages by debugger to client.
:type _i... | [
"Build",
"a",
"message",
"from",
"parameters",
"and",
"send",
"it",
"to",
"debugger",
".",
":",
"param",
"command",
":",
"The",
"command",
"sent",
"to",
"the",
"debugger",
"client",
".",
":",
"type",
"command",
":",
"str",
":",
"param",
"_id",
":",
"Un... | python | train | 41.526316 |
onnx/onnxmltools | onnxmltools/convert/coreml/shape_calculators/OneHotEncoder.py | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/shape_calculators/OneHotEncoder.py#L12-L36 | def calculate_one_hot_encoder_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, 1] ---> [N, C']
C' is the total number of categorical values.
'''
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
if operator.inputs[0].type.shape[1] ... | [
"def",
"calculate_one_hot_encoder_output_shapes",
"(",
"operator",
")",
":",
"check_input_and_output_numbers",
"(",
"operator",
",",
"input_count_range",
"=",
"1",
",",
"output_count_range",
"=",
"1",
")",
"if",
"operator",
".",
"inputs",
"[",
"0",
"]",
".",
"type... | Allowed input/output patterns are
1. [N, 1] ---> [N, C']
C' is the total number of categorical values. | [
"Allowed",
"input",
"/",
"output",
"patterns",
"are",
"1",
".",
"[",
"N",
"1",
"]",
"---",
">",
"[",
"N",
"C",
"]"
] | python | train | 45.92 |
tanghaibao/jcvi | jcvi/compara/quota.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/quota.py#L152-L198 | def format_lp(nodes, constraints_x, qa, constraints_y, qb):
"""
Maximize
4 x1 + 2 x2 + 3 x3 + x4
Subject To
x1 + x2 <= 1
End
"""
lp_handle = cStringIO.StringIO()
lp_handle.write("Maximize\n ")
records = 0
for i, score in nodes:
lp_handle.write("+ %d x%d " % (score,... | [
"def",
"format_lp",
"(",
"nodes",
",",
"constraints_x",
",",
"qa",
",",
"constraints_y",
",",
"qb",
")",
":",
"lp_handle",
"=",
"cStringIO",
".",
"StringIO",
"(",
")",
"lp_handle",
".",
"write",
"(",
"\"Maximize\\n \"",
")",
"records",
"=",
"0",
"for",
"... | Maximize
4 x1 + 2 x2 + 3 x3 + x4
Subject To
x1 + x2 <= 1
End | [
"Maximize",
"4",
"x1",
"+",
"2",
"x2",
"+",
"3",
"x3",
"+",
"x4",
"Subject",
"To",
"x1",
"+",
"x2",
"<",
"=",
"1",
"End"
] | python | train | 27.553191 |
Kortemme-Lab/pull_into_place | pull_into_place/pipeline.py | https://github.com/Kortemme-Lab/pull_into_place/blob/247f303100a612cc90cf31c86e4fe5052eb28c8d/pull_into_place/pipeline.py#L844-L863 | def load_loops(directory, loops_path=None):
"""
Return a list of tuples indicating the start and end points of the loops
that were sampled in the given directory.
"""
if loops_path is None:
workspace = workspace_from_dir(directory)
loops_path = workspace.loops_path
from klab.ro... | [
"def",
"load_loops",
"(",
"directory",
",",
"loops_path",
"=",
"None",
")",
":",
"if",
"loops_path",
"is",
"None",
":",
"workspace",
"=",
"workspace_from_dir",
"(",
"directory",
")",
"loops_path",
"=",
"workspace",
".",
"loops_path",
"from",
"klab",
".",
"ro... | Return a list of tuples indicating the start and end points of the loops
that were sampled in the given directory. | [
"Return",
"a",
"list",
"of",
"tuples",
"indicating",
"the",
"start",
"and",
"end",
"points",
"of",
"the",
"loops",
"that",
"were",
"sampled",
"in",
"the",
"given",
"directory",
"."
] | python | train | 40.25 |
eumis/pyviews | pyviews/core/ioc.py | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/ioc.py#L81-L83 | def register(key, initializer: callable, param=None):
'''Adds resolver to global container'''
get_current_scope().container.register(key, initializer, param) | [
"def",
"register",
"(",
"key",
",",
"initializer",
":",
"callable",
",",
"param",
"=",
"None",
")",
":",
"get_current_scope",
"(",
")",
".",
"container",
".",
"register",
"(",
"key",
",",
"initializer",
",",
"param",
")"
] | Adds resolver to global container | [
"Adds",
"resolver",
"to",
"global",
"container"
] | python | train | 54.333333 |
ClearcodeHQ/matchbox | src/matchbox/index.py | https://github.com/ClearcodeHQ/matchbox/blob/22f5bd163ad22ceacb0fcd5d4ddae9069d1a94f4/src/matchbox/index.py#L153-L180 | def add_match(self, entity, *traits):
"""
Add a matching entity to the index.
We have to maintain the constraints of the data layout:
- `self.mismatch_unknown` must still contain all matched entities
- each key of the index must mismatch all known matching entities excep... | [
"def",
"add_match",
"(",
"self",
",",
"entity",
",",
"*",
"traits",
")",
":",
"# The index traits of `traits_indexed_by` might have already been used to index some other entities. Those",
"# relations are to be preserved. If the trait was not used to index any entity, we initialize them to m... | Add a matching entity to the index.
We have to maintain the constraints of the data layout:
- `self.mismatch_unknown` must still contain all matched entities
- each key of the index must mismatch all known matching entities except those this particular key
explicitly inclu... | [
"Add",
"a",
"matching",
"entity",
"to",
"the",
"index",
"."
] | python | train | 50.928571 |
jupyter-widgets/ipywidgets | ipywidgets/widgets/widget.py | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L117-L130 | def _remove_buffers(state):
"""Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memo... | [
"def",
"_remove_buffers",
"(",
"state",
")",
":",
"buffer_paths",
",",
"buffers",
"=",
"[",
"]",
",",
"[",
"]",
"state",
"=",
"_separate_buffers",
"(",
"state",
",",
"[",
"]",
",",
"buffer_paths",
",",
"buffers",
")",
"return",
"state",
",",
"buffer_path... | Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memoryview(ar2)}}
>>> _remove_buffe... | [
"Return",
"(",
"state_without_buffers",
"buffer_paths",
"buffers",
")",
"for",
"binary",
"message",
"parts"
] | python | train | 46.5 |
pmichali/whodunit | whodunit/__init__.py | https://github.com/pmichali/whodunit/blob/eed9107533766d716469e35fbb647a39dfa07035/whodunit/__init__.py#L195-L218 | def collect_blame_info(cls, matches):
"""Runs git blame on files, for the specified sets of line ranges.
If no line range tuples are provided, it will do all lines.
"""
old_area = None
for filename, ranges in matches:
area, name = os.path.split(filename)
... | [
"def",
"collect_blame_info",
"(",
"cls",
",",
"matches",
")",
":",
"old_area",
"=",
"None",
"for",
"filename",
",",
"ranges",
"in",
"matches",
":",
"area",
",",
"name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
"if",
"not",
"area",
... | Runs git blame on files, for the specified sets of line ranges.
If no line range tuples are provided, it will do all lines. | [
"Runs",
"git",
"blame",
"on",
"files",
"for",
"the",
"specified",
"sets",
"of",
"line",
"ranges",
"."
] | python | train | 39.5 |
pydata/xarray | xarray/core/coordinates.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/coordinates.py#L93-L101 | def _merge_raw(self, other):
"""For use with binary arithmetic."""
if other is None:
variables = OrderedDict(self.variables)
else:
# don't align because we already called xarray.align
variables = expand_and_merge_variables(
[self.variables, oth... | [
"def",
"_merge_raw",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"None",
":",
"variables",
"=",
"OrderedDict",
"(",
"self",
".",
"variables",
")",
"else",
":",
"# don't align because we already called xarray.align",
"variables",
"=",
"expand_and_merg... | For use with binary arithmetic. | [
"For",
"use",
"with",
"binary",
"arithmetic",
"."
] | python | train | 39 |
GNS3/gns3-server | gns3server/controller/snapshot.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/snapshot.py#L75-L92 | def restore(self):
"""
Restore the snapshot
"""
yield from self._project.delete_on_computes()
# We don't send close notif to clients because the close / open dance is purely internal
yield from self._project.close(ignore_notification=True)
self._project.controlle... | [
"def",
"restore",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"_project",
".",
"delete_on_computes",
"(",
")",
"# We don't send close notif to clients because the close / open dance is purely internal",
"yield",
"from",
"self",
".",
"_project",
".",
"close",
"(... | Restore the snapshot | [
"Restore",
"the",
"snapshot"
] | python | train | 48.388889 |
rerb/django-fortune | fortune/views.py | https://github.com/rerb/django-fortune/blob/f84d34f616ecabd4fab8351ad7d3062cc9d6b127/fortune/views.py#L30-L35 | def loaded(self, request, *args, **kwargs):
"""Return a list of loaded Packs.
"""
serializer = self.get_serializer(list(Pack.objects.all()),
many=True)
return Response(serializer.data) | [
"def",
"loaded",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"serializer",
"=",
"self",
".",
"get_serializer",
"(",
"list",
"(",
"Pack",
".",
"objects",
".",
"all",
"(",
")",
")",
",",
"many",
"=",
"True",
")... | Return a list of loaded Packs. | [
"Return",
"a",
"list",
"of",
"loaded",
"Packs",
"."
] | python | train | 42 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py#L825-L839 | def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_info
... | [
"def",
"show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_port",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_fabric_trunk_info",
"=",
"ET",
".",
"Element"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 55.933333 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/generator/mavgen_swift.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/generator/mavgen_swift.py#L328-L362 | def generate_enums_info(enums, msgs):
"""Add camel case swift names for enums an entries, descriptions and sort enums alphabetically"""
for enum in enums:
enum.swift_name = camel_case_from_underscores(enum.name)
enum.raw_value_type = get_enum_raw_type(enum, msgs)
enum.formatted_descrip... | [
"def",
"generate_enums_info",
"(",
"enums",
",",
"msgs",
")",
":",
"for",
"enum",
"in",
"enums",
":",
"enum",
".",
"swift_name",
"=",
"camel_case_from_underscores",
"(",
"enum",
".",
"name",
")",
"enum",
".",
"raw_value_type",
"=",
"get_enum_raw_type",
"(",
... | Add camel case swift names for enums an entries, descriptions and sort enums alphabetically | [
"Add",
"camel",
"case",
"swift",
"names",
"for",
"enums",
"an",
"entries",
"descriptions",
"and",
"sort",
"enums",
"alphabetically"
] | python | train | 41.685714 |
pycontribs/pyrax | pyrax/clouddatabases.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/clouddatabases.py#L683-L696 | def _configure_manager(self):
"""
Creates a manager to handle the instances, and another
to handle flavors.
"""
self._manager = CloudDatabaseManager(self,
resource_class=CloudDatabaseInstance, response_key="instance",
uri_base="instances")
... | [
"def",
"_configure_manager",
"(",
"self",
")",
":",
"self",
".",
"_manager",
"=",
"CloudDatabaseManager",
"(",
"self",
",",
"resource_class",
"=",
"CloudDatabaseInstance",
",",
"response_key",
"=",
"\"instance\"",
",",
"uri_base",
"=",
"\"instances\"",
")",
"self"... | Creates a manager to handle the instances, and another
to handle flavors. | [
"Creates",
"a",
"manager",
"to",
"handle",
"the",
"instances",
"and",
"another",
"to",
"handle",
"flavors",
"."
] | python | train | 45.214286 |
anrosent/perg | enum.py | https://github.com/anrosent/perg/blob/53293f7ed5e0f2e45fb185b60e344ea8436f02aa/enum.py#L88-L100 | def enum_subpattern(p):
subpattern_id, d = p
patterns = list(enum_gen(d))
'''
if subpattern_id:
subpat_iter = EnumSubpatternIterator(subpattern_id, patterns)
SUBPATTERNS[subpattern_id] = subpat_iter
return subpat_iter
else:
return patterns
'''
return patt... | [
"def",
"enum_subpattern",
"(",
"p",
")",
":",
"subpattern_id",
",",
"d",
"=",
"p",
"patterns",
"=",
"list",
"(",
"enum_gen",
"(",
"d",
")",
")",
"return",
"patterns"
] | if subpattern_id:
subpat_iter = EnumSubpatternIterator(subpattern_id, patterns)
SUBPATTERNS[subpattern_id] = subpat_iter
return subpat_iter
else:
return patterns | [
"if",
"subpattern_id",
":",
"subpat_iter",
"=",
"EnumSubpatternIterator",
"(",
"subpattern_id",
"patterns",
")",
"SUBPATTERNS",
"[",
"subpattern_id",
"]",
"=",
"subpat_iter",
"return",
"subpat_iter",
"else",
":",
"return",
"patterns"
] | python | train | 24 |
SetBased/py-stratum | pystratum/RoutineLoaderHelper.py | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L599-L617 | def _print_sql_with_error(self, sql, error_line):
"""
Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted.
:param str sql: The SQL statement.
:param int error_line: The line where the error occurs.
"""
if os.linesep i... | [
"def",
"_print_sql_with_error",
"(",
"self",
",",
"sql",
",",
"error_line",
")",
":",
"if",
"os",
".",
"linesep",
"in",
"sql",
":",
"lines",
"=",
"sql",
".",
"split",
"(",
"os",
".",
"linesep",
")",
"digits",
"=",
"math",
".",
"ceil",
"(",
"math",
... | Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted.
:param str sql: The SQL statement.
:param int error_line: The line where the error occurs. | [
"Writes",
"a",
"SQL",
"statement",
"with",
"an",
"syntax",
"error",
"to",
"the",
"output",
".",
"The",
"line",
"where",
"the",
"error",
"occurs",
"is",
"highlighted",
"."
] | python | train | 40.578947 |
IntelPython/mkl_fft | mkl_fft/_numpy_fft.py | https://github.com/IntelPython/mkl_fft/blob/54b3271d64666f9af9f11418b4ca43d69054eb94/mkl_fft/_numpy_fft.py#L682-L778 | def ifftn(a, s=None, axes=None, norm=None):
"""
Compute the N-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the N-dimensional discrete
Fourier Transform over any number of axes in an M-dimensional array by
means of the Fast Fourier Transform (FFT). In other ... | [
"def",
"ifftn",
"(",
"a",
",",
"s",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"norm",
"=",
"None",
")",
":",
"unitary",
"=",
"_unitary",
"(",
"norm",
")",
"output",
"=",
"mkl_fft",
".",
"ifftn",
"(",
"a",
",",
"s",
",",
"axes",
")",
"if",
"... | Compute the N-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the N-dimensional discrete
Fourier Transform over any number of axes in an M-dimensional array by
means of the Fast Fourier Transform (FFT). In other words,
``ifftn(fftn(a)) == a`` to within numerical a... | [
"Compute",
"the",
"N",
"-",
"dimensional",
"inverse",
"discrete",
"Fourier",
"Transform",
"."
] | python | train | 39.845361 |
r4fek/django-cassandra-engine | django_cassandra_engine/base/operations.py | https://github.com/r4fek/django-cassandra-engine/blob/b43f8fddd4bba143f03f73f8bbfc09e6b32c699b/django_cassandra_engine/base/operations.py#L36-L47 | def sql_flush(self, style, tables, sequences, allow_cascade=False):
"""
Truncate all existing tables in current keyspace.
:returns: an empty list
"""
for table in tables:
qs = "TRUNCATE {}".format(table)
self.connection.connection.execute(qs)
re... | [
"def",
"sql_flush",
"(",
"self",
",",
"style",
",",
"tables",
",",
"sequences",
",",
"allow_cascade",
"=",
"False",
")",
":",
"for",
"table",
"in",
"tables",
":",
"qs",
"=",
"\"TRUNCATE {}\"",
".",
"format",
"(",
"table",
")",
"self",
".",
"connection",
... | Truncate all existing tables in current keyspace.
:returns: an empty list | [
"Truncate",
"all",
"existing",
"tables",
"in",
"current",
"keyspace",
"."
] | python | train | 26.333333 |
bukun/TorCMS | torcms/model/user_model.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L186-L195 | def update_time_login(u_name):
'''
Update the login time for user.
'''
entry = TabMember.update(
time_login=tools.timestamp()
).where(
TabMember.user_name == u_name
)
entry.execute() | [
"def",
"update_time_login",
"(",
"u_name",
")",
":",
"entry",
"=",
"TabMember",
".",
"update",
"(",
"time_login",
"=",
"tools",
".",
"timestamp",
"(",
")",
")",
".",
"where",
"(",
"TabMember",
".",
"user_name",
"==",
"u_name",
")",
"entry",
".",
"execute... | Update the login time for user. | [
"Update",
"the",
"login",
"time",
"for",
"user",
"."
] | python | train | 25.3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.