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 |
|---|---|---|---|---|---|---|---|---|---|
PaloAltoNetworks/pancloud | pancloud/directorysync.py | https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/directorysync.py#L88-L116 | def count(self, object_class=None, params=None, **kwargs): # pragma: no cover
"""Retrieve the attribute configuration object.
Retrieve a count of all directory entries that belong to the
identified objectClass. The count is limited to a single domain.
Args:
params (dict): ... | [
"def",
"count",
"(",
"self",
",",
"object_class",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"path",
"=",
"\"/directory-sync-service/v1/{}/count\"",
".",
"format",
"(",
"object_class",
")",
"r",
"=",
"se... | Retrieve the attribute configuration object.
Retrieve a count of all directory entries that belong to the
identified objectClass. The count is limited to a single domain.
Args:
params (dict): Payload/request dictionary.
object_class (str): Directory object class.
... | [
"Retrieve",
"the",
"attribute",
"configuration",
"object",
"."
] | python | train | 30.517241 |
pantsbuild/pants | src/python/pants/base/payload.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/payload.py#L72-L78 | def add_fields(self, field_dict):
"""Add a mapping of field names to PayloadField instances.
:API: public
"""
for key, field in field_dict.items():
self.add_field(key, field) | [
"def",
"add_fields",
"(",
"self",
",",
"field_dict",
")",
":",
"for",
"key",
",",
"field",
"in",
"field_dict",
".",
"items",
"(",
")",
":",
"self",
".",
"add_field",
"(",
"key",
",",
"field",
")"
] | Add a mapping of field names to PayloadField instances.
:API: public | [
"Add",
"a",
"mapping",
"of",
"field",
"names",
"to",
"PayloadField",
"instances",
"."
] | python | train | 27.285714 |
Robpol86/etaprogress | etaprogress/components/misc.py | https://github.com/Robpol86/etaprogress/blob/224e8a248c2bf820bad218763281914ad3983fff/etaprogress/components/misc.py#L84-L120 | def get_info(handle):
"""Get information about this current console window (for Microsoft Windows only).
Raises IOError if attempt to get information fails (if there is no console window).
Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method.
... | [
"def",
"get_info",
"(",
"handle",
")",
":",
"# Query Win32 API.",
"csbi",
"=",
"_WindowsCSBI",
".",
"CSBI",
"(",
")",
"try",
":",
"if",
"not",
"_WindowsCSBI",
".",
"WINDLL",
".",
"kernel32",
".",
"GetConsoleScreenBufferInfo",
"(",
"handle",
",",
"ctypes",
".... | Get information about this current console window (for Microsoft Windows only).
Raises IOError if attempt to get information fails (if there is no console window).
Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method.
Positional arguments:
... | [
"Get",
"information",
"about",
"this",
"current",
"console",
"window",
"(",
"for",
"Microsoft",
"Windows",
"only",
")",
"."
] | python | train | 47.810811 |
dossier/dossier.web | dossier/extraction/usernames.py | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/extraction/usernames.py#L15-L30 | def usernames(urls):
'''Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list.
'''
usernames = StringCounter()
for url, count in urls.items():
uparse = urlparse(url)
path = uparse.path
hostname = uparse.hostname
... | [
"def",
"usernames",
"(",
"urls",
")",
":",
"usernames",
"=",
"StringCounter",
"(",
")",
"for",
"url",
",",
"count",
"in",
"urls",
".",
"items",
"(",
")",
":",
"uparse",
"=",
"urlparse",
"(",
"url",
")",
"path",
"=",
"uparse",
".",
"path",
"hostname",... | Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list. | [
"Take",
"an",
"iterable",
"of",
"urls",
"of",
"normalized",
"URL",
"or",
"file",
"paths",
"and",
"attempt",
"to",
"extract",
"usernames",
".",
"Returns",
"a",
"list",
"."
] | python | train | 33.125 |
carljm/django-adminfiles | adminfiles/flickr.py | https://github.com/carljm/django-adminfiles/blob/b01dc7be266305d575c11d5ff9a37ccac04a78c2/adminfiles/flickr.py#L443-L466 | def _load_properties(self):
"""Load User properties from Flickr."""
method = 'flickr.people.getInfo'
data = _doget(method, user_id=self.__id)
self.__loaded = True
person = data.rsp.person
self.__isadmin = person.isadmin
self.__ispro = person.ispro
... | [
"def",
"_load_properties",
"(",
"self",
")",
":",
"method",
"=",
"'flickr.people.getInfo'",
"data",
"=",
"_doget",
"(",
"method",
",",
"user_id",
"=",
"self",
".",
"__id",
")",
"self",
".",
"__loaded",
"=",
"True",
"person",
"=",
"data",
".",
"rsp",
".",... | Load User properties from Flickr. | [
"Load",
"User",
"properties",
"from",
"Flickr",
"."
] | python | train | 39.541667 |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tag.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L388-L392 | def build(self, words):
"""Construct dictionary DAWG from tokenized words."""
words = [self._normalize(tokens) for tokens in words]
self._dawg = dawg.CompletionDAWG(words)
self._loaded_model = True | [
"def",
"build",
"(",
"self",
",",
"words",
")",
":",
"words",
"=",
"[",
"self",
".",
"_normalize",
"(",
"tokens",
")",
"for",
"tokens",
"in",
"words",
"]",
"self",
".",
"_dawg",
"=",
"dawg",
".",
"CompletionDAWG",
"(",
"words",
")",
"self",
".",
"_... | Construct dictionary DAWG from tokenized words. | [
"Construct",
"dictionary",
"DAWG",
"from",
"tokenized",
"words",
"."
] | python | train | 45 |
pivotal-energy-solutions/django-datatable-view | datatableview/helpers.py | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/helpers.py#L402-L428 | def make_processor(func, arg=None):
"""
A pre-called processor that wraps the execution of the target callable ``func``.
This is useful for when ``func`` is a third party mapping function that can take your column's
value and return an expected result, but doesn't understand all of the extra kwargs tha... | [
"def",
"make_processor",
"(",
"func",
",",
"arg",
"=",
"None",
")",
":",
"def",
"helper",
"(",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"kwargs",
".",
"get",
"(",
"'default_value'",
")",
"if",
"value",
"is",
"N... | A pre-called processor that wraps the execution of the target callable ``func``.
This is useful for when ``func`` is a third party mapping function that can take your column's
value and return an expected result, but doesn't understand all of the extra kwargs that get
sent to processor callbacks. Because ... | [
"A",
"pre",
"-",
"called",
"processor",
"that",
"wraps",
"the",
"execution",
"of",
"the",
"target",
"callable",
"func",
"."
] | python | train | 47.296296 |
ClimateImpactLab/DataFS | datafs/config/helpers.py | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/config/helpers.py#L25-L155 | def get_api(
profile=None,
config_file=None,
requirements=None):
'''
Generate a datafs.DataAPI object from a config profile
``get_api`` generates a DataAPI object based on a
pre-configured datafs profile specified in your datafs
config file.
To create a datafs config fi... | [
"def",
"get_api",
"(",
"profile",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"requirements",
"=",
"None",
")",
":",
"config",
"=",
"ConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"config",
".",
"read_config",
"(",
")",
"if",
"profile",
... | Generate a datafs.DataAPI object from a config profile
``get_api`` generates a DataAPI object based on a
pre-configured datafs profile specified in your datafs
config file.
To create a datafs config file, use the command line
tool ``datafs configure --helper`` or export an existing
DataAPI obj... | [
"Generate",
"a",
"datafs",
".",
"DataAPI",
"object",
"from",
"a",
"config",
"profile"
] | python | train | 29.954198 |
ff0000/scarlet | scarlet/assets/crops.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/assets/crops.py#L223-L233 | def scale_and_crop(im, crop_spec):
"""
Scale and Crop.
"""
im = im.crop((crop_spec.x, crop_spec.y, crop_spec.x2, crop_spec.y2))
if crop_spec.width and crop_spec.height:
im = im.resize((crop_spec.width, crop_spec.height),
resample=Image.ANTIALIAS)
return im | [
"def",
"scale_and_crop",
"(",
"im",
",",
"crop_spec",
")",
":",
"im",
"=",
"im",
".",
"crop",
"(",
"(",
"crop_spec",
".",
"x",
",",
"crop_spec",
".",
"y",
",",
"crop_spec",
".",
"x2",
",",
"crop_spec",
".",
"y2",
")",
")",
"if",
"crop_spec",
".",
... | Scale and Crop. | [
"Scale",
"and",
"Crop",
"."
] | python | train | 27.181818 |
dicaso/leopard | leopard/__init__.py | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L135-L145 | def listFigures(self,walkTrace=tuple(),case=None,element=None):
"""List section figures.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'figure':
caption,fig = element
try:
print(walkTrace,fig._leopardref,caption)
... | [
"def",
"listFigures",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
")",
":",
"if",
"case",
"==",
"'sectionmain'",
":",
"print",
"(",
"walkTrace",
",",
"self",
".",
"title",
")",
"if",
... | List section figures. | [
"List",
"section",
"figures",
"."
] | python | train | 41.454545 |
stevearc/dql | dql/models.py | https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L592-L617 | def pformat(self):
""" Pretty string format """
lines = []
lines.append(("%s (%s)" % (self.name, self.status)).center(50, "-"))
lines.append("items: {0:,} ({1:,} bytes)".format(self.item_count, self.size))
cap = self.consumed_capacity.get("__table__", {})
read = "Read: " ... | [
"def",
"pformat",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"lines",
".",
"append",
"(",
"(",
"\"%s (%s)\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"status",
")",
")",
".",
"center",
"(",
"50",
",",
"\"-\"",
")",
")",
"lines",
".... | Pretty string format | [
"Pretty",
"string",
"format"
] | python | train | 41.769231 |
oauthlib/oauthlib | oauthlib/oauth2/rfc6749/grant_types/base.py | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/base.py#L166-L178 | def validate_scopes(self, request):
"""
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
if not request.scopes:
request.scopes = utils.scope_to_list(request.scope) or utils.scope_to_list(
self.request_validator.get_default_s... | [
"def",
"validate_scopes",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"request",
".",
"scopes",
":",
"request",
".",
"scopes",
"=",
"utils",
".",
"scope_to_list",
"(",
"request",
".",
"scope",
")",
"or",
"utils",
".",
"scope_to_list",
"(",
"self"... | :param request: OAuthlib request.
:type request: oauthlib.common.Request | [
":",
"param",
"request",
":",
"OAuthlib",
"request",
".",
":",
"type",
"request",
":",
"oauthlib",
".",
"common",
".",
"Request"
] | python | train | 54.769231 |
DistrictDataLabs/yellowbrick | yellowbrick/features/rankd.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/rankd.py#L122-L146 | def transform(self, X, **kwargs):
"""
The transform method is the primary drawing hook for ranking classes.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
kwargs : dict
Pass generic arguments... | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"ranks_",
"=",
"self",
".",
"rank",
"(",
"X",
")",
"self",
".",
"draw",
"(",
"*",
"*",
"kwargs",
")",
"# Return the X matrix, unchanged",
"return",
"X"
] | The transform method is the primary drawing hook for ranking classes.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
kwargs : dict
Pass generic arguments to the drawing method
Returns
------... | [
"The",
"transform",
"method",
"is",
"the",
"primary",
"drawing",
"hook",
"for",
"ranking",
"classes",
"."
] | python | train | 31.08 |
Azure/azure-sdk-for-python | azure-cognitiveservices-language-spellcheck/azure/cognitiveservices/language/spellcheck/spell_check_api.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-cognitiveservices-language-spellcheck/azure/cognitiveservices/language/spellcheck/spell_check_api.py#L69-L371 | def spell_checker(
self, text, accept_language=None, pragma=None, user_agent=None, client_id=None, client_ip=None, location=None, action_type=None, app_name=None, country_code=None, client_machine_name=None, doc_id=None, market=None, session_id=None, set_lang=None, user_id=None, mode=None, pre_context_text=... | [
"def",
"spell_checker",
"(",
"self",
",",
"text",
",",
"accept_language",
"=",
"None",
",",
"pragma",
"=",
"None",
",",
"user_agent",
"=",
"None",
",",
"client_id",
"=",
"None",
",",
"client_ip",
"=",
"None",
",",
"location",
"=",
"None",
",",
"action_ty... | The Bing Spell Check API lets you perform contextual grammar and spell
checking. Bing has developed a web-based spell-checker that leverages
machine learning and statistical machine translation to dynamically
train a constantly evolving and highly contextual algorithm. The
spell-checker ... | [
"The",
"Bing",
"Spell",
"Check",
"API",
"lets",
"you",
"perform",
"contextual",
"grammar",
"and",
"spell",
"checking",
".",
"Bing",
"has",
"developed",
"a",
"web",
"-",
"based",
"spell",
"-",
"checker",
"that",
"leverages",
"machine",
"learning",
"and",
"sta... | python | test | 63.828383 |
cosven/feeluown-core | fuocore/xiami/api.py | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/xiami/api.py#L54-L72 | def _sign_payload(self, payload):
"""使用 appkey 对 payload 进行签名,返回新的请求参数
"""
app_key = self._app_key
t = int(time.time() * 1000)
requestStr = {
'header': self._req_header,
'model': payload
}
data = json.dumps({'requestStr': json.dumps(request... | [
"def",
"_sign_payload",
"(",
"self",
",",
"payload",
")",
":",
"app_key",
"=",
"self",
".",
"_app_key",
"t",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
"requestStr",
"=",
"{",
"'header'",
":",
"self",
".",
"_req_header",
",",
... | 使用 appkey 对 payload 进行签名,返回新的请求参数 | [
"使用",
"appkey",
"对",
"payload",
"进行签名,返回新的请求参数"
] | python | train | 31.684211 |
gwpy/gwpy | gwpy/frequencyseries/frequencyseries.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/frequencyseries/frequencyseries.py#L393-L411 | def from_pycbc(cls, fs, copy=True):
"""Convert a `pycbc.types.frequencyseries.FrequencySeries` into
a `FrequencySeries`
Parameters
----------
fs : `pycbc.types.frequencyseries.FrequencySeries`
the input PyCBC `~pycbc.types.frequencyseries.FrequencySeries`
... | [
"def",
"from_pycbc",
"(",
"cls",
",",
"fs",
",",
"copy",
"=",
"True",
")",
":",
"return",
"cls",
"(",
"fs",
".",
"data",
",",
"f0",
"=",
"0",
",",
"df",
"=",
"fs",
".",
"delta_f",
",",
"epoch",
"=",
"fs",
".",
"epoch",
",",
"copy",
"=",
"copy... | Convert a `pycbc.types.frequencyseries.FrequencySeries` into
a `FrequencySeries`
Parameters
----------
fs : `pycbc.types.frequencyseries.FrequencySeries`
the input PyCBC `~pycbc.types.frequencyseries.FrequencySeries`
array
copy : `bool`, optional, defaul... | [
"Convert",
"a",
"pycbc",
".",
"types",
".",
"frequencyseries",
".",
"FrequencySeries",
"into",
"a",
"FrequencySeries"
] | python | train | 33 |
proycon/clam | clam/common/data.py | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L204-L228 | def attachviewers(self, profiles):
"""Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate"""
if self.metadata:
template = None
for profile in profiles:
if isinstance(self, CLAMInputFile):
... | [
"def",
"attachviewers",
"(",
"self",
",",
"profiles",
")",
":",
"if",
"self",
".",
"metadata",
":",
"template",
"=",
"None",
"for",
"profile",
"in",
"profiles",
":",
"if",
"isinstance",
"(",
"self",
",",
"CLAMInputFile",
")",
":",
"for",
"t",
"in",
"pr... | Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate | [
"Attach",
"viewers",
"*",
"and",
"converters",
"*",
"to",
"file",
"automatically",
"scan",
"all",
"profiles",
"for",
"outputtemplate",
"or",
"inputtemplate"
] | python | train | 49.2 |
mwickert/scikit-dsp-comm | sk_dsp_comm/rtlsdr_helper.py | https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/rtlsdr_helper.py#L72-L92 | def mono_FM(x,fs=2.4e6,file_name='test.wav'):
"""
Decimate complex baseband input by 10
Design 1st decimation lowpass filter (f_c = 200 KHz)
"""
b = signal.firwin(64,2*200e3/float(fs))
# Filter and decimate (should be polyphase)
y = signal.lfilter(b,1,x)
z = ss.downsample(y,10)
... | [
"def",
"mono_FM",
"(",
"x",
",",
"fs",
"=",
"2.4e6",
",",
"file_name",
"=",
"'test.wav'",
")",
":",
"b",
"=",
"signal",
".",
"firwin",
"(",
"64",
",",
"2",
"*",
"200e3",
"/",
"float",
"(",
"fs",
")",
")",
"# Filter and decimate (should be polyphase)\r",
... | Decimate complex baseband input by 10
Design 1st decimation lowpass filter (f_c = 200 KHz) | [
"Decimate",
"complex",
"baseband",
"input",
"by",
"10",
"Design",
"1st",
"decimation",
"lowpass",
"filter",
"(",
"f_c",
"=",
"200",
"KHz",
")"
] | python | valid | 33.666667 |
dmcc/PyStanfordDependencies | StanfordDependencies/JPypeBackend.py | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/JPypeBackend.py#L159-L190 | def _get_deps(self, tree, include_punct, representation, universal):
"""Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation."""
if universal:
converter = self.universal_converter
if self.universal_converter == self.converte... | [
"def",
"_get_deps",
"(",
"self",
",",
"tree",
",",
"include_punct",
",",
"representation",
",",
"universal",
")",
":",
"if",
"universal",
":",
"converter",
"=",
"self",
".",
"universal_converter",
"if",
"self",
".",
"universal_converter",
"==",
"self",
".",
... | Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation. | [
"Get",
"a",
"list",
"of",
"dependencies",
"from",
"a",
"Stanford",
"Tree",
"for",
"a",
"specific",
"Stanford",
"Dependencies",
"representation",
"."
] | python | train | 41.375 |
pysathq/pysat | pysat/solvers.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L2798-L2805 | def get_core(self):
"""
Get an unsatisfiable core if the formula was previously
unsatisfied.
"""
if self.minicard and self.status == False:
return pysolvers.minicard_core(self.minicard) | [
"def",
"get_core",
"(",
"self",
")",
":",
"if",
"self",
".",
"minicard",
"and",
"self",
".",
"status",
"==",
"False",
":",
"return",
"pysolvers",
".",
"minicard_core",
"(",
"self",
".",
"minicard",
")"
] | Get an unsatisfiable core if the formula was previously
unsatisfied. | [
"Get",
"an",
"unsatisfiable",
"core",
"if",
"the",
"formula",
"was",
"previously",
"unsatisfied",
"."
] | python | train | 29.875 |
Erotemic/utool | utool/util_iter.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L17-L24 | def wrap_iterable(obj):
"""
Returns:
wrapped_obj, was_scalar
"""
was_scalar = not isiterable(obj)
wrapped_obj = [obj] if was_scalar else obj
return wrapped_obj, was_scalar | [
"def",
"wrap_iterable",
"(",
"obj",
")",
":",
"was_scalar",
"=",
"not",
"isiterable",
"(",
"obj",
")",
"wrapped_obj",
"=",
"[",
"obj",
"]",
"if",
"was_scalar",
"else",
"obj",
"return",
"wrapped_obj",
",",
"was_scalar"
] | Returns:
wrapped_obj, was_scalar | [
"Returns",
":",
"wrapped_obj",
"was_scalar"
] | python | train | 24.5 |
jxtech/wechatpy | wechatpy/enterprise/client/api/chat.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/enterprise/client/api/chat.py#L135-L159 | def send_text(self, sender, receiver_type, receiver_id, content):
"""
发送文本消息
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明
:param sender: 发送人
:param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊
:param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id... | [
"def",
"send_text",
"(",
"self",
",",
"sender",
",",
"receiver_type",
",",
"receiver_id",
",",
"content",
")",
":",
"data",
"=",
"{",
"'receiver'",
":",
"{",
"'type'",
":",
"receiver_type",
",",
"'id'",
":",
"receiver_id",
",",
"}",
",",
"'sender'",
":",... | 发送文本消息
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明
:param sender: 发送人
:param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊
:param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id|会话id
:param content: 消息内容
:return: 返回的 JSON 数据包 | [
"发送文本消息"
] | python | train | 27.88 |
jingming/spotify | spotify/auth/util.py | https://github.com/jingming/spotify/blob/d92c71073b2515f3c850604114133a7d2022d1a4/spotify/auth/util.py#L19-L32 | def user_token(scopes, client_id=None, client_secret=None, redirect_uri=None):
"""
Generate a user access token
:param List[str] scopes: Scopes to get
:param str client_id: Spotify Client ID
:param str client_secret: Spotify Client secret
:param str redirect_uri: Spotify redirect URI
:retur... | [
"def",
"user_token",
"(",
"scopes",
",",
"client_id",
"=",
"None",
",",
"client_secret",
"=",
"None",
",",
"redirect_uri",
"=",
"None",
")",
":",
"webbrowser",
".",
"open_new",
"(",
"authorize_url",
"(",
"client_id",
"=",
"client_id",
",",
"redirect_uri",
"=... | Generate a user access token
:param List[str] scopes: Scopes to get
:param str client_id: Spotify Client ID
:param str client_secret: Spotify Client secret
:param str redirect_uri: Spotify redirect URI
:return: Generated access token
:rtype: User | [
"Generate",
"a",
"user",
"access",
"token"
] | python | train | 45.571429 |
planetlabs/planet-client-python | planet/api/utils.py | https://github.com/planetlabs/planet-client-python/blob/1c62ce7d416819951dddee0c22068fef6d40b027/planet/api/utils.py#L287-L297 | def probably_wkt(text):
'''Quick check to determine if the provided text looks like WKT'''
valid = False
valid_types = set([
'POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT',
'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION',
])
matched = re.match(r'(\w+)\s*\([^)]+\)', text.strip... | [
"def",
"probably_wkt",
"(",
"text",
")",
":",
"valid",
"=",
"False",
"valid_types",
"=",
"set",
"(",
"[",
"'POINT'",
",",
"'LINESTRING'",
",",
"'POLYGON'",
",",
"'MULTIPOINT'",
",",
"'MULTILINESTRING'",
",",
"'MULTIPOLYGON'",
",",
"'GEOMETRYCOLLECTION'",
",",
... | Quick check to determine if the provided text looks like WKT | [
"Quick",
"check",
"to",
"determine",
"if",
"the",
"provided",
"text",
"looks",
"like",
"WKT"
] | python | train | 36.545455 |
PaulHancock/Aegean | AegeanTools/MIMAS.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/MIMAS.py#L229-L267 | def mask_catalog(regionfile, infile, outfile, negate=False, racol='ra', deccol='dec'):
"""
Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region
If negate=False then remove the rows with ra/dec outside the region.
Parameters
----------
regionfile : str... | [
"def",
"mask_catalog",
"(",
"regionfile",
",",
"infile",
",",
"outfile",
",",
"negate",
"=",
"False",
",",
"racol",
"=",
"'ra'",
",",
"deccol",
"=",
"'dec'",
")",
":",
"logging",
".",
"info",
"(",
"\"Loading region from {0}\"",
".",
"format",
"(",
"regionf... | Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region
If negate=False then remove the rows with ra/dec outside the region.
Parameters
----------
regionfile : str
A file which can be loaded as a :class:`AegeanTools.regions.Region`.
The catalogue... | [
"Apply",
"a",
"region",
"file",
"as",
"a",
"mask",
"to",
"a",
"catalog",
"removing",
"all",
"the",
"rows",
"with",
"ra",
"/",
"dec",
"inside",
"the",
"region",
"If",
"negate",
"=",
"False",
"then",
"remove",
"the",
"rows",
"with",
"ra",
"/",
"dec",
"... | python | train | 30.923077 |
allenai/allennlp | allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L133-L136 | def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""Follow Figure 1 (left) for connections."""
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward) | [
"def",
"forward",
"(",
"self",
",",
"x",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
")",
"->",
"torch",
".",
"Tensor",
":",
"x",
"=",
"self",
".",
"sublayer",
"[",
"0",
"]",
"(",
"x",
",",
"lambda",
"x",
":",
"self",... | Follow Figure 1 (left) for connections. | [
"Follow",
"Figure",
"1",
"(",
"left",
")",
"for",
"connections",
"."
] | python | train | 62.25 |
DeV1doR/aioethereum | aioethereum/management/admin.py | https://github.com/DeV1doR/aioethereum/blob/85eb46550d862b3ccc309914ea871ca1c7b42157/aioethereum/management/admin.py#L80-L104 | def admin_startWS(self, host='localhost', port=8546, cors=None, apis=None):
"""https://github.com/ethereum/go-ethereum/wiki/Management-APIs#admin_startws
:param host: Network interface to open the listener socket (optional)
:type host: str
:param port: Network port to open the listener... | [
"def",
"admin_startWS",
"(",
"self",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"8546",
",",
"cors",
"=",
"None",
",",
"apis",
"=",
"None",
")",
":",
"if",
"cors",
"is",
"None",
":",
"cors",
"=",
"[",
"]",
"if",
"apis",
"is",
"None",
":",... | https://github.com/ethereum/go-ethereum/wiki/Management-APIs#admin_startws
:param host: Network interface to open the listener socket (optional)
:type host: str
:param port: Network port to open the listener socket (optional)
:type port: int
:param cors: Cross-origin resource ... | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"ethereum",
"/",
"go",
"-",
"ethereum",
"/",
"wiki",
"/",
"Management",
"-",
"APIs#admin_startws"
] | python | train | 34.96 |
zengbin93/zb | zb/visz/stacked_bar_chart.py | https://github.com/zengbin93/zb/blob/ccdb384a0b5801b459933220efcb71972c2b89a7/zb/visz/stacked_bar_chart.py#L29-L38 | def compute_ratio(x):
"""
计算每一类数据的占比
"""
sum_ = sum(x)
ratios = []
for i in x:
ratio = i / sum_
ratios.append(ratio)
return ratios | [
"def",
"compute_ratio",
"(",
"x",
")",
":",
"sum_",
"=",
"sum",
"(",
"x",
")",
"ratios",
"=",
"[",
"]",
"for",
"i",
"in",
"x",
":",
"ratio",
"=",
"i",
"/",
"sum_",
"ratios",
".",
"append",
"(",
"ratio",
")",
"return",
"ratios"
] | 计算每一类数据的占比 | [
"计算每一类数据的占比"
] | python | train | 20.1 |
roclark/sportsreference | sportsreference/nfl/boxscore.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/boxscore.py#L323-L361 | def _parse_game_date_and_location(self, boxscore):
"""
Retrieve the game's date and location.
The games' meta information, such as date, location, attendance, and
duration, follow a complex parsing scheme that changes based on the
layout of the page. The information should be ab... | [
"def",
"_parse_game_date_and_location",
"(",
"self",
",",
"boxscore",
")",
":",
"scheme",
"=",
"BOXSCORE_SCHEME",
"[",
"\"game_info\"",
"]",
"items",
"=",
"[",
"i",
".",
"text",
"(",
")",
"for",
"i",
"in",
"boxscore",
"(",
"scheme",
")",
".",
"items",
"(... | Retrieve the game's date and location.
The games' meta information, such as date, location, attendance, and
duration, follow a complex parsing scheme that changes based on the
layout of the page. The information should be able to be parsed and set
regardless of the order and how much in... | [
"Retrieve",
"the",
"game",
"s",
"date",
"and",
"location",
"."
] | python | train | 41.923077 |
scopus-api/scopus | scopus/abstract_retrieval.py | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L788-L798 | def _parse_pages(self, unicode=False):
"""Auxiliary function to parse and format page range of a document."""
if self.pageRange:
pages = 'pp. {}'.format(self.pageRange)
elif self.startingPage:
pages = 'pp. {}-{}'.format(self.startingPage, self.endingPage)
else:
pages = '(no pages... | [
"def",
"_parse_pages",
"(",
"self",
",",
"unicode",
"=",
"False",
")",
":",
"if",
"self",
".",
"pageRange",
":",
"pages",
"=",
"'pp. {}'",
".",
"format",
"(",
"self",
".",
"pageRange",
")",
"elif",
"self",
".",
"startingPage",
":",
"pages",
"=",
"'pp. ... | Auxiliary function to parse and format page range of a document. | [
"Auxiliary",
"function",
"to",
"parse",
"and",
"format",
"page",
"range",
"of",
"a",
"document",
"."
] | python | train | 35.181818 |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L556-L563 | def command(self, cluster_id, command, *args):
"""Call a ShardedCluster method."""
cluster = self._storage[cluster_id]
try:
return getattr(cluster, command)(*args)
except AttributeError:
raise ValueError("Cannot issue the command %r to ShardedCluster %s"
... | [
"def",
"command",
"(",
"self",
",",
"cluster_id",
",",
"command",
",",
"*",
"args",
")",
":",
"cluster",
"=",
"self",
".",
"_storage",
"[",
"cluster_id",
"]",
"try",
":",
"return",
"getattr",
"(",
"cluster",
",",
"command",
")",
"(",
"*",
"args",
")"... | Call a ShardedCluster method. | [
"Call",
"a",
"ShardedCluster",
"method",
"."
] | python | train | 44.625 |
numenta/nupic | src/nupic/swarming/hypersearch_v2.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch_v2.py#L431-L516 | def getParticleInfos(self, swarmId=None, genIdx=None, completed=None,
matured=None, lastDescendent=False):
"""Return a list of particleStates for all particles we know about in
the given swarm, their model Ids, and metric results.
Parameters:
-------------------------------------... | [
"def",
"getParticleInfos",
"(",
"self",
",",
"swarmId",
"=",
"None",
",",
"genIdx",
"=",
"None",
",",
"completed",
"=",
"None",
",",
"matured",
"=",
"None",
",",
"lastDescendent",
"=",
"False",
")",
":",
"# The indexes of all the models in this swarm. This list ex... | Return a list of particleStates for all particles we know about in
the given swarm, their model Ids, and metric results.
Parameters:
---------------------------------------------------------------------
swarmId: A string representation of the sorted list of encoders in this
swarm. For... | [
"Return",
"a",
"list",
"of",
"particleStates",
"for",
"all",
"particles",
"we",
"know",
"about",
"in",
"the",
"given",
"swarm",
"their",
"model",
"Ids",
"and",
"metric",
"results",
"."
] | python | valid | 36.848837 |
romana/vpc-router | vpcrouter/monitor/plugins/multi.py | https://github.com/romana/vpc-router/blob/d696c2e023f1111ceb61f9c6fbabfafed8e14040/vpcrouter/monitor/plugins/multi.py#L67-L75 | def update(self, data_set):
"""
Refresh the time of all specified elements in the supplied data set.
"""
now = time.time()
for d in data_set:
self.timed_data[d] = now
self._expire_data() | [
"def",
"update",
"(",
"self",
",",
"data_set",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"for",
"d",
"in",
"data_set",
":",
"self",
".",
"timed_data",
"[",
"d",
"]",
"=",
"now",
"self",
".",
"_expire_data",
"(",
")"
] | Refresh the time of all specified elements in the supplied data set. | [
"Refresh",
"the",
"time",
"of",
"all",
"specified",
"elements",
"in",
"the",
"supplied",
"data",
"set",
"."
] | python | train | 26.555556 |
saltstack/salt | salt/modules/vsphere.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L7201-L7214 | def _get_esxi_proxy_details():
'''
Returns the running esxi's proxy details
'''
det = __proxy__['esxi.get_details']()
host = det.get('host')
if det.get('vcenter'):
host = det['vcenter']
esxi_hosts = None
if det.get('esxi_host'):
esxi_hosts = [det['esxi_host']]
return ... | [
"def",
"_get_esxi_proxy_details",
"(",
")",
":",
"det",
"=",
"__proxy__",
"[",
"'esxi.get_details'",
"]",
"(",
")",
"host",
"=",
"det",
".",
"get",
"(",
"'host'",
")",
"if",
"det",
".",
"get",
"(",
"'vcenter'",
")",
":",
"host",
"=",
"det",
"[",
"'vc... | Returns the running esxi's proxy details | [
"Returns",
"the",
"running",
"esxi",
"s",
"proxy",
"details"
] | python | train | 35.285714 |
awslabs/serverless-application-model | samtranslator/model/api/api_generator.py | https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/api/api_generator.py#L110-L138 | def _construct_body_s3_dict(self):
"""Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.
:returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition
:rtype: dict
"""
if isinstance(self.definit... | [
"def",
"_construct_body_s3_dict",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"definition_uri",
",",
"dict",
")",
":",
"if",
"not",
"self",
".",
"definition_uri",
".",
"get",
"(",
"\"Bucket\"",
",",
"None",
")",
"or",
"not",
"self",
".",... | Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.
:returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition
:rtype: dict | [
"Constructs",
"the",
"RestApi",
"s",
"BodyS3Location",
"property",
"_",
"from",
"the",
"SAM",
"Api",
"s",
"DefinitionUri",
"property",
"."
] | python | train | 47.586207 |
Chilipp/docrep | docrep/__init__.py | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L836-L856 | def keep_types_s(s, types):
"""
Keep the given types from a string
Same as :meth:`keep_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
Th... | [
"def",
"keep_types_s",
"(",
"s",
",",
"types",
")",
":",
"patt",
"=",
"'|'",
".",
"join",
"(",
"'(?<=\\n)'",
"+",
"s",
"+",
"'\\n(?s).+?\\n(?=\\S+|$)'",
"for",
"s",
"in",
"types",
")",
"return",
"''",
".",
"join",
"(",
"re",
".",
"findall",
"(",
"pat... | Keep the given types from a string
Same as :meth:`keep_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
The type identifiers to keep
Returns
... | [
"Keep",
"the",
"given",
"types",
"from",
"a",
"string"
] | python | train | 29.095238 |
Erotemic/utool | utool/util_alg.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2049-L2064 | def safe_pdist(arr, *args, **kwargs):
"""
Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.distance.pdist
TODO: move to vtool
"""
if arr is None or len(arr) < 2:
return None
else:
import vtool as vt
arr_ = vt.atleast_nd(arr, 2)
return spdis... | [
"def",
"safe_pdist",
"(",
"arr",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"arr",
"is",
"None",
"or",
"len",
"(",
"arr",
")",
"<",
"2",
":",
"return",
"None",
"else",
":",
"import",
"vtool",
"as",
"vt",
"arr_",
"=",
"vt",
".",
... | Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.distance.pdist
TODO: move to vtool | [
"Kwargs",
":",
"metric",
"=",
"ut",
".",
"absdiff",
"SeeAlso",
":",
"scipy",
".",
"spatial",
".",
"distance",
".",
"pdist"
] | python | train | 20.9375 |
aiidalab/aiidalab-widgets-base | aiidalab_widgets_base/computers.py | https://github.com/aiidalab/aiidalab-widgets-base/blob/291a9b159eac902aee655862322670ec1b0cd5b1/aiidalab_widgets_base/computers.py#L247-L308 | def on_setup_ssh(self, b):
"""ATTENTION: modifying the order of operations in this function can lead to unexpected problems"""
with self._setup_ssh_out:
clear_output()
self._ssh_keygen()
#temporary passwords
password = self.__password
proxy_pa... | [
"def",
"on_setup_ssh",
"(",
"self",
",",
"b",
")",
":",
"with",
"self",
".",
"_setup_ssh_out",
":",
"clear_output",
"(",
")",
"self",
".",
"_ssh_keygen",
"(",
")",
"#temporary passwords",
"password",
"=",
"self",
".",
"__password",
"proxy_password",
"=",
"se... | ATTENTION: modifying the order of operations in this function can lead to unexpected problems | [
"ATTENTION",
":",
"modifying",
"the",
"order",
"of",
"operations",
"in",
"this",
"function",
"can",
"lead",
"to",
"unexpected",
"problems"
] | python | train | 45.435484 |
log2timeline/dfvfs | dfvfs/vfs/data_range_file_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/data_range_file_system.py#L37-L66 | def _Open(self, path_spec, mode='rb'):
"""Opens the file system defined by path specification.
Args:
path_spec (PathSpec): a path specification.
mode (Optional[str]): file access mode. The default is 'rb' which
represents read-only binary.
Raises:
AccessError: if the access to ... | [
"def",
"_Open",
"(",
"self",
",",
"path_spec",
",",
"mode",
"=",
"'rb'",
")",
":",
"if",
"not",
"path_spec",
".",
"HasParent",
"(",
")",
":",
"raise",
"errors",
".",
"PathSpecError",
"(",
"'Unsupported path specification without parent.'",
")",
"range_offset",
... | Opens the file system defined by path specification.
Args:
path_spec (PathSpec): a path specification.
mode (Optional[str]): file access mode. The default is 'rb' which
represents read-only binary.
Raises:
AccessError: if the access to open the file was denied.
IOError: if th... | [
"Opens",
"the",
"file",
"system",
"defined",
"by",
"path",
"specification",
"."
] | python | train | 35.9 |
Azure/azure-sdk-for-python | azure-servicemanagement-legacy/azure/servicemanagement/_serialization.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/_serialization.py#L1439-L1493 | def xml_to_namespace(xmlstr):
'''Converts xml response to service bus namespace
The xml format for namespace:
<entry>
<id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id>
<title type="text">myunittests</title>
<updated>2012-08-22T16:48:10Z</updated>
<content type="application/xml">
<Namesp... | [
"def",
"xml_to_namespace",
"(",
"xmlstr",
")",
":",
"xmldoc",
"=",
"minidom",
".",
"parseString",
"(",
"xmlstr",
")",
"namespace",
"=",
"ServiceBusNamespace",
"(",
")",
"mappings",
"=",
"(",
"(",
"'Name'",
",",
"'name'",
",",
"None",
")",
",",
"(",
"'Reg... | Converts xml response to service bus namespace
The xml format for namespace:
<entry>
<id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id>
<title type="text">myunittests</title>
<updated>2012-08-22T16:48:10Z</updated>
<content type="application/xml">
<NamespaceDescription
xmlns="http://sche... | [
"Converts",
"xml",
"response",
"to",
"service",
"bus",
"namespace"
] | python | test | 43.145455 |
elastic/elasticsearch-dsl-py | elasticsearch_dsl/index.py | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L364-L371 | def delete(self, using=None, **kwargs):
"""
Deletes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.delete`` unchanged.
"""
return self._get_connection(using).indices.delete(index=self._name, **kwargs) | [
"def",
"delete",
"(",
"self",
",",
"using",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_get_connection",
"(",
"using",
")",
".",
"indices",
".",
"delete",
"(",
"index",
"=",
"self",
".",
"_name",
",",
"*",
"*",
"kwargs"... | Deletes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.delete`` unchanged. | [
"Deletes",
"the",
"index",
"in",
"elasticsearch",
"."
] | python | train | 37.25 |
GaretJax/lancet | lancet/commands/workflow.py | https://github.com/GaretJax/lancet/blob/cf438c5c6166b18ee0dc5ffce55220793019bb95/lancet/commands/workflow.py#L78-L135 | def workon(ctx, issue_id, new, base_branch):
"""
Start work on a given issue.
This command retrieves the issue from the issue tracker, creates and checks
out a new aptly-named branch, puts the issue in the configured active,
status, assigns it to you and starts a correctly linked Harvest timer.
... | [
"def",
"workon",
"(",
"ctx",
",",
"issue_id",
",",
"new",
",",
"base_branch",
")",
":",
"lancet",
"=",
"ctx",
".",
"obj",
"if",
"not",
"issue_id",
"and",
"not",
"new",
":",
"raise",
"click",
".",
"UsageError",
"(",
"\"Provide either an issue ID or the --new ... | Start work on a given issue.
This command retrieves the issue from the issue tracker, creates and checks
out a new aptly-named branch, puts the issue in the configured active,
status, assigns it to you and starts a correctly linked Harvest timer.
If a branch with the same name as the one to be created... | [
"Start",
"work",
"on",
"a",
"given",
"issue",
"."
] | python | train | 36 |
saltstack/salt | salt/modules/groupadd.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L81-L106 | def delete(name, root=None):
'''
Remove the named group
name
Name group to delete
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' group.delete foo
'''
cmd = ['groupdel']
if root is not None:
cmd.extend(('-R', root))
... | [
"def",
"delete",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'groupdel'",
"]",
"if",
"root",
"is",
"not",
"None",
":",
"cmd",
".",
"extend",
"(",
"(",
"'-R'",
",",
"root",
")",
")",
"cmd",
".",
"append",
"(",
"name",
")",... | Remove the named group
name
Name group to delete
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' group.delete foo | [
"Remove",
"the",
"named",
"group"
] | python | train | 15.461538 |
rosenbrockc/ci | pyci/server.py | https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L83-L161 | def process_pulls(self, testpulls=None, testarchive=None, expected=None):
"""Runs self.find_pulls() *and* processes the pull requests unit tests,
status updates and wiki page creations.
:arg expected: for unit testing the output results that would be returned
from running the tests in... | [
"def",
"process_pulls",
"(",
"self",
",",
"testpulls",
"=",
"None",
",",
"testarchive",
"=",
"None",
",",
"expected",
"=",
"None",
")",
":",
"from",
"datetime",
"import",
"datetime",
"pulls",
"=",
"self",
".",
"find_pulls",
"(",
"None",
"if",
"testpulls",
... | Runs self.find_pulls() *and* processes the pull requests unit tests,
status updates and wiki page creations.
:arg expected: for unit testing the output results that would be returned
from running the tests in real time. | [
"Runs",
"self",
".",
"find_pulls",
"()",
"*",
"and",
"*",
"processes",
"the",
"pull",
"requests",
"unit",
"tests",
"status",
"updates",
"and",
"wiki",
"page",
"creations",
"."
] | python | train | 58.417722 |
moonso/loqusdb | loqusdb/utils/load.py | https://github.com/moonso/loqusdb/blob/792dcd0d461aff5adc703c49eebf58964913a513/loqusdb/utils/load.py#L153-L177 | def load_case(adapter, case_obj, update=False):
"""Load a case to the database
Args:
adapter: Connection to database
case_obj: dict
update(bool): If existing case should be updated
Returns:
case_obj(models.Case)
"""
# Check if the case already exists in database.
... | [
"def",
"load_case",
"(",
"adapter",
",",
"case_obj",
",",
"update",
"=",
"False",
")",
":",
"# Check if the case already exists in database.",
"existing_case",
"=",
"adapter",
".",
"case",
"(",
"case_obj",
")",
"if",
"existing_case",
":",
"if",
"not",
"update",
... | Load a case to the database
Args:
adapter: Connection to database
case_obj: dict
update(bool): If existing case should be updated
Returns:
case_obj(models.Case) | [
"Load",
"a",
"case",
"to",
"the",
"database"
] | python | train | 27.64 |
google/python-gflags | gflags/flagvalues.py | https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/flagvalues.py#L1196-L1208 | def AppendFlagsIntoFile(self, filename):
"""Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
Args:
filename: string, name o... | [
"def",
"AppendFlagsIntoFile",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'a'",
")",
"as",
"out_file",
":",
"out_file",
".",
"write",
"(",
"self",
".",
"FlagsIntoString",
"(",
")",
")"
] | Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
Args:
filename: string, name of the file. | [
"Appends",
"all",
"flags",
"assignments",
"from",
"this",
"FlagInfo",
"object",
"to",
"a",
"file",
"."
] | python | train | 31.846154 |
apache/incubator-mxnet | amalgamation/python/mxnet_predict.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/python/mxnet_predict.py#L173-L204 | def reshape(self, input_shapes):
"""Change the input shape of the predictor.
Parameters
----------
input_shapes : dict of str to tuple
The new shape of input data.
Examples
--------
>>> predictor.reshape({'data':data_shape_tuple})
"""
... | [
"def",
"reshape",
"(",
"self",
",",
"input_shapes",
")",
":",
"indptr",
"=",
"[",
"0",
"]",
"sdata",
"=",
"[",
"]",
"keys",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"input_shapes",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
... | Change the input shape of the predictor.
Parameters
----------
input_shapes : dict of str to tuple
The new shape of input data.
Examples
--------
>>> predictor.reshape({'data':data_shape_tuple}) | [
"Change",
"the",
"input",
"shape",
"of",
"the",
"predictor",
"."
] | python | train | 30.78125 |
astropy/astropy-healpix | astropy_healpix/healpy.py | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L113-L116 | def pix2vec(nside, ipix, nest=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`."""
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
return ang2vec(*_lonlat_to_healpy(lon, lat)) | [
"def",
"pix2vec",
"(",
"nside",
",",
"ipix",
",",
"nest",
"=",
"False",
")",
":",
"lon",
",",
"lat",
"=",
"healpix_to_lonlat",
"(",
"ipix",
",",
"nside",
",",
"order",
"=",
"'nested'",
"if",
"nest",
"else",
"'ring'",
")",
"return",
"ang2vec",
"(",
"*... | Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`. | [
"Drop",
"-",
"in",
"replacement",
"for",
"healpy",
"~healpy",
".",
"pixelfunc",
".",
"pix2vec",
"."
] | python | train | 58.75 |
gmr/queries | queries/pool.py | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/pool.py#L237-L254 | def free(self, connection):
"""Free the connection from use by the session that was using it.
:param connection: The connection to free
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
"""
LOGGER.debug('Pool %s freeing connection %s', se... | [
"def",
"free",
"(",
"self",
",",
"connection",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Pool %s freeing connection %s'",
",",
"self",
".",
"id",
",",
"id",
"(",
"connection",
")",
")",
"try",
":",
"self",
".",
"connection_handle",
"(",
"connection",
")",
... | Free the connection from use by the session that was using it.
:param connection: The connection to free
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError | [
"Free",
"the",
"connection",
"from",
"use",
"by",
"the",
"session",
"that",
"was",
"using",
"it",
"."
] | python | train | 39.611111 |
wakatime/wakatime | wakatime/packages/requests/utils.py | https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/requests/utils.py#L244-L268 | def to_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to... | [
"def",
"to_key_val_list",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"bytes",
",",
"bool",
",",
"int",
")",
")",
":",
"raise",
"ValueError",
"(",
"'cannot encode o... | Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
Val... | [
"Take",
"an",
"object",
"and",
"test",
"to",
"see",
"if",
"it",
"can",
"be",
"represented",
"as",
"a",
"dictionary",
".",
"If",
"it",
"can",
"be",
"return",
"a",
"list",
"of",
"tuples",
"e",
".",
"g",
"."
] | python | train | 27.12 |
gwastro/pycbc | pycbc/inference/models/base.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L125-L164 | def logjacobian(self, **params):
r"""Returns the log of the jacobian needed to transform pdfs in the
``variable_params`` parameter space to the ``sampling_params``
parameter space.
Let :math:`\mathbf{x}` be the set of variable parameters,
:math:`\mathbf{y} = f(\mathbf{x})` the s... | [
"def",
"logjacobian",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"numpy",
".",
"log",
"(",
"abs",
"(",
"transforms",
".",
"compute_jacobian",
"(",
"params",
",",
"self",
".",
"sampling_transforms",
",",
"inverse",
"=",
"True",
")",
")",
... | r"""Returns the log of the jacobian needed to transform pdfs in the
``variable_params`` parameter space to the ``sampling_params``
parameter space.
Let :math:`\mathbf{x}` be the set of variable parameters,
:math:`\mathbf{y} = f(\mathbf{x})` the set of sampling parameters, and
:m... | [
"r",
"Returns",
"the",
"log",
"of",
"the",
"jacobian",
"needed",
"to",
"transform",
"pdfs",
"in",
"the",
"variable_params",
"parameter",
"space",
"to",
"the",
"sampling_params",
"parameter",
"space",
"."
] | python | train | 33.3 |
davidfokkema/artist | artist/multi_plot.py | https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/multi_plot.py#L314-L322 | def set_xticks(self, row, column, ticks):
"""Manually specify the x-axis tick values.
:param row,column: specify the subplot.
:param ticks: list of tick values.
"""
subplot = self.get_subplot_at(row, column)
subplot.set_xticks(ticks) | [
"def",
"set_xticks",
"(",
"self",
",",
"row",
",",
"column",
",",
"ticks",
")",
":",
"subplot",
"=",
"self",
".",
"get_subplot_at",
"(",
"row",
",",
"column",
")",
"subplot",
".",
"set_xticks",
"(",
"ticks",
")"
] | Manually specify the x-axis tick values.
:param row,column: specify the subplot.
:param ticks: list of tick values. | [
"Manually",
"specify",
"the",
"x",
"-",
"axis",
"tick",
"values",
"."
] | python | train | 30.555556 |
kaste/mockito-python | mockito/mockito.py | https://github.com/kaste/mockito-python/blob/d6b22b003f56ee5b156dbd9d8ba209faf35b6713/mockito/mockito.py#L364-L379 | def verifyZeroInteractions(*objs):
"""Verify that no methods have been called on given objs.
Note that strict mocks usually throw early on unexpected, unstubbed
invocations. Partial mocks ('monkeypatched' objects or modules) do not
support this functionality at all, bc only for the stubbed invocations
... | [
"def",
"verifyZeroInteractions",
"(",
"*",
"objs",
")",
":",
"for",
"obj",
"in",
"objs",
":",
"theMock",
"=",
"_get_mock_or_raise",
"(",
"obj",
")",
"if",
"len",
"(",
"theMock",
".",
"invocations",
")",
">",
"0",
":",
"raise",
"VerificationError",
"(",
"... | Verify that no methods have been called on given objs.
Note that strict mocks usually throw early on unexpected, unstubbed
invocations. Partial mocks ('monkeypatched' objects or modules) do not
support this functionality at all, bc only for the stubbed invocations
the actual usage gets recorded. So thi... | [
"Verify",
"that",
"no",
"methods",
"have",
"been",
"called",
"on",
"given",
"objs",
"."
] | python | train | 38.25 |
spyder-ide/spyder-kernels | spyder_kernels/utils/nsview.py | https://github.com/spyder-ide/spyder-kernels/blob/2c5b36cdb797b8aba77bc406ca96f5e079c4aaca/spyder_kernels/utils/nsview.py#L551-L577 | def is_supported(value, check_all=False, filters=None, iterate=False):
"""Return True if the value is supported, False otherwise"""
assert filters is not None
if value is None:
return True
if not is_editable_type(value):
return False
elif not isinstance(value, filters):
retur... | [
"def",
"is_supported",
"(",
"value",
",",
"check_all",
"=",
"False",
",",
"filters",
"=",
"None",
",",
"iterate",
"=",
"False",
")",
":",
"assert",
"filters",
"is",
"not",
"None",
"if",
"value",
"is",
"None",
":",
"return",
"True",
"if",
"not",
"is_edi... | Return True if the value is supported, False otherwise | [
"Return",
"True",
"if",
"the",
"value",
"is",
"supported",
"False",
"otherwise"
] | python | train | 38.074074 |
diux-dev/ncluster | ncluster/util.py | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L157-L162 | def assert_script_in_current_directory():
"""Assert fail if current directory is different from location of the script"""
script = sys.argv[0]
assert os.path.abspath(os.path.dirname(script)) == os.path.abspath(
'.'), f"Change into directory of script {script} and run again." | [
"def",
"assert_script_in_current_directory",
"(",
")",
":",
"script",
"=",
"sys",
".",
"argv",
"[",
"0",
"]",
"assert",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"script",
")",
")",
"==",
"os",
".",
"path",
".",
... | Assert fail if current directory is different from location of the script | [
"Assert",
"fail",
"if",
"current",
"directory",
"is",
"different",
"from",
"location",
"of",
"the",
"script"
] | python | train | 46.833333 |
funilrys/PyFunceble | PyFunceble/production.py | https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/production.py#L393-L409 | def _does_require_deprecation(self):
"""
Check if we have to put the previous version into the deprecated list.
"""
for index, version_number in enumerate(self.current_version[0][:2]):
# We loop through the 2 last elements of the version.
if version_number > sel... | [
"def",
"_does_require_deprecation",
"(",
"self",
")",
":",
"for",
"index",
",",
"version_number",
"in",
"enumerate",
"(",
"self",
".",
"current_version",
"[",
"0",
"]",
"[",
":",
"2",
"]",
")",
":",
"# We loop through the 2 last elements of the version.",
"if",
... | Check if we have to put the previous version into the deprecated list. | [
"Check",
"if",
"we",
"have",
"to",
"put",
"the",
"previous",
"version",
"into",
"the",
"deprecated",
"list",
"."
] | python | test | 35.235294 |
pysathq/pysat | pysat/formula.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L264-L311 | def id(self, obj):
"""
The method is to be used to assign an integer variable ID for a
given new object. If the object already has an ID, no new ID is
created and the old one is returned instead.
An object can be anything. In some cases it is convenient to use
... | [
"def",
"id",
"(",
"self",
",",
"obj",
")",
":",
"vid",
"=",
"self",
".",
"obj2id",
"[",
"obj",
"]",
"if",
"vid",
"not",
"in",
"self",
".",
"id2obj",
":",
"self",
".",
"id2obj",
"[",
"vid",
"]",
"=",
"obj",
"return",
"vid"
] | The method is to be used to assign an integer variable ID for a
given new object. If the object already has an ID, no new ID is
created and the old one is returned instead.
An object can be anything. In some cases it is convenient to use
string variable names.
... | [
"The",
"method",
"is",
"to",
"be",
"used",
"to",
"assign",
"an",
"integer",
"variable",
"ID",
"for",
"a",
"given",
"new",
"object",
".",
"If",
"the",
"object",
"already",
"has",
"an",
"ID",
"no",
"new",
"ID",
"is",
"created",
"and",
"the",
"old",
"on... | python | train | 28.354167 |
Unidata/MetPy | metpy/plots/ctables.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/plots/ctables.py#L130-L146 | def scan_resource(self, pkg, path):
r"""Scan a resource directory for colortable files and add them to the registry.
Parameters
----------
pkg : str
The package containing the resource directory
path : str
The path to the directory with the color tables
... | [
"def",
"scan_resource",
"(",
"self",
",",
"pkg",
",",
"path",
")",
":",
"for",
"fname",
"in",
"resource_listdir",
"(",
"pkg",
",",
"path",
")",
":",
"if",
"fname",
".",
"endswith",
"(",
"TABLE_EXT",
")",
":",
"table_path",
"=",
"posixpath",
".",
"join"... | r"""Scan a resource directory for colortable files and add them to the registry.
Parameters
----------
pkg : str
The package containing the resource directory
path : str
The path to the directory with the color tables | [
"r",
"Scan",
"a",
"resource",
"directory",
"for",
"colortable",
"files",
"and",
"add",
"them",
"to",
"the",
"registry",
"."
] | python | train | 40.411765 |
Jajcus/pyxmpp2 | pyxmpp2/jid.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L212-L260 | def __prepare_domain(data):
"""Prepare domainpart of the JID.
:Parameters:
- `data`: Domain part of the JID
:Types:
- `data`: `unicode`
:raise JIDError: if the domain name is too long.
"""
# pylint: disable=R0912
if not data:
... | [
"def",
"__prepare_domain",
"(",
"data",
")",
":",
"# pylint: disable=R0912",
"if",
"not",
"data",
":",
"raise",
"JIDError",
"(",
"\"Domain must be given\"",
")",
"data",
"=",
"unicode",
"(",
"data",
")",
"if",
"not",
"data",
":",
"raise",
"JIDError",
"(",
"\... | Prepare domainpart of the JID.
:Parameters:
- `data`: Domain part of the JID
:Types:
- `data`: `unicode`
:raise JIDError: if the domain name is too long. | [
"Prepare",
"domainpart",
"of",
"the",
"JID",
"."
] | python | valid | 37.673469 |
googlefonts/fontbakery | Lib/fontbakery/commands/check_profile.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/commands/check_profile.py#L193-L206 | def get_profile():
""" Prefetch the profile module, to fill some holes in the help text."""
argument_parser = ThrowingArgumentParser(add_help=False)
argument_parser.add_argument('profile')
try:
args, _ = argument_parser.parse_known_args()
except ArgumentParserError:
# silently fails, the main parser w... | [
"def",
"get_profile",
"(",
")",
":",
"argument_parser",
"=",
"ThrowingArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"argument_parser",
".",
"add_argument",
"(",
"'profile'",
")",
"try",
":",
"args",
",",
"_",
"=",
"argument_parser",
".",
"parse_known_args... | Prefetch the profile module, to fill some holes in the help text. | [
"Prefetch",
"the",
"profile",
"module",
"to",
"fill",
"some",
"holes",
"in",
"the",
"help",
"text",
"."
] | python | train | 37.5 |
binux/pyspider | pyspider/scheduler/scheduler.py | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L616-L620 | def _dump_cnt(self):
'''Dump counters to file'''
self._cnt['1h'].dump(os.path.join(self.data_path, 'scheduler.1h'))
self._cnt['1d'].dump(os.path.join(self.data_path, 'scheduler.1d'))
self._cnt['all'].dump(os.path.join(self.data_path, 'scheduler.all')) | [
"def",
"_dump_cnt",
"(",
"self",
")",
":",
"self",
".",
"_cnt",
"[",
"'1h'",
"]",
".",
"dump",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"'scheduler.1h'",
")",
")",
"self",
".",
"_cnt",
"[",
"'1d'",
"]",
".",
"dump"... | Dump counters to file | [
"Dump",
"counters",
"to",
"file"
] | python | train | 55.8 |
romana/vpc-router | vpcrouter/watcher/plugins/configfile.py | https://github.com/romana/vpc-router/blob/d696c2e023f1111ceb61f9c6fbabfafed8e14040/vpcrouter/watcher/plugins/configfile.py#L198-L209 | def check_arguments(cls, conf):
"""
Sanity checks for options needed for configfile mode.
"""
try:
# Check we have access to the config file
f = open(conf['file'], "r")
f.close()
except IOError as e:
raise ArgsError("Cannot open co... | [
"def",
"check_arguments",
"(",
"cls",
",",
"conf",
")",
":",
"try",
":",
"# Check we have access to the config file",
"f",
"=",
"open",
"(",
"conf",
"[",
"'file'",
"]",
",",
"\"r\"",
")",
"f",
".",
"close",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
... | Sanity checks for options needed for configfile mode. | [
"Sanity",
"checks",
"for",
"options",
"needed",
"for",
"configfile",
"mode",
"."
] | python | train | 31.416667 |
inveniosoftware/invenio-files-rest | invenio_files_rest/models.py | https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1353-L1365 | def delete(cls, object_version, key=None):
"""Delete tags.
:param object_version: The object version instance or id.
:param key: Key of the tag to delete.
Default: delete all tags.
"""
with db.session.begin_nested():
q = cls.query.filter_by(
... | [
"def",
"delete",
"(",
"cls",
",",
"object_version",
",",
"key",
"=",
"None",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"q",
"=",
"cls",
".",
"query",
".",
"filter_by",
"(",
"version_id",
"=",
"as_object_version_id",
"(... | Delete tags.
:param object_version: The object version instance or id.
:param key: Key of the tag to delete.
Default: delete all tags. | [
"Delete",
"tags",
"."
] | python | train | 34.076923 |
conchoecia/gloTK | gloTK/wrappers.py | https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/gloTK/wrappers.py#L208-L217 | def run_jar(self, mem=None):
"""
Special case of run() when the executable is a JAR file.
"""
cmd = config.get_command('java')
if mem:
cmd.append('-Xmx%s' % mem)
cmd.append('-jar')
cmd += self.cmd
self.run(cmd) | [
"def",
"run_jar",
"(",
"self",
",",
"mem",
"=",
"None",
")",
":",
"cmd",
"=",
"config",
".",
"get_command",
"(",
"'java'",
")",
"if",
"mem",
":",
"cmd",
".",
"append",
"(",
"'-Xmx%s'",
"%",
"mem",
")",
"cmd",
".",
"append",
"(",
"'-jar'",
")",
"c... | Special case of run() when the executable is a JAR file. | [
"Special",
"case",
"of",
"run",
"()",
"when",
"the",
"executable",
"is",
"a",
"JAR",
"file",
"."
] | python | train | 27.7 |
pybel/pybel | src/pybel/struct/filters/node_filters.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_filters.py#L29-L36 | def invert_node_predicate(node_predicate: NodePredicate) -> NodePredicate: # noqa: D202
"""Build a node predicate that is the inverse of the given node predicate."""
def inverse_predicate(graph: BELGraph, node: BaseEntity) -> bool:
"""Return the inverse of the enclosed node predicate applied to the gr... | [
"def",
"invert_node_predicate",
"(",
"node_predicate",
":",
"NodePredicate",
")",
"->",
"NodePredicate",
":",
"# noqa: D202",
"def",
"inverse_predicate",
"(",
"graph",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
")",
"->",
"bool",
":",
"\"\"\"Return the inverse... | Build a node predicate that is the inverse of the given node predicate. | [
"Build",
"a",
"node",
"predicate",
"that",
"is",
"the",
"inverse",
"of",
"the",
"given",
"node",
"predicate",
"."
] | python | train | 50.75 |
callowayproject/Transmogrify | transmogrify/filesystem/s3.py | https://github.com/callowayproject/Transmogrify/blob/f1f891b8b923b3a1ede5eac7f60531c1c472379e/transmogrify/filesystem/s3.py#L42-L57 | def get_file(original_file):
"""
original file should be s3://bucketname/path/to/file.txt
returns a Buffer with the file in it
"""
import cStringIO
import boto3
s3 = boto3.resource('s3')
bucket_name, object_key = _parse_s3_file(original_file)
logger.debug("Downloading {0} from {1}".... | [
"def",
"get_file",
"(",
"original_file",
")",
":",
"import",
"cStringIO",
"import",
"boto3",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"'s3'",
")",
"bucket_name",
",",
"object_key",
"=",
"_parse_s3_file",
"(",
"original_file",
")",
"logger",
".",
"debug",
"(... | original file should be s3://bucketname/path/to/file.txt
returns a Buffer with the file in it | [
"original",
"file",
"should",
"be",
"s3",
":",
"//",
"bucketname",
"/",
"path",
"/",
"to",
"/",
"file",
".",
"txt"
] | python | train | 30.75 |
uber/tchannel-python | crossdock/server/server.py | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/crossdock/server/server.py#L23-L43 | def serve():
"""main entry point"""
logging.getLogger().setLevel(logging.DEBUG)
logging.info('Python Tornado Crossdock Server Starting ...')
tracer = Tracer(
service_name='python',
reporter=NullReporter(),
sampler=ConstSampler(decision=True))
opentracing.tracer = tracer
... | [
"def",
"serve",
"(",
")",
":",
"logging",
".",
"getLogger",
"(",
")",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"logging",
".",
"info",
"(",
"'Python Tornado Crossdock Server Starting ...'",
")",
"tracer",
"=",
"Tracer",
"(",
"service_name",
"=",
"... | main entry point | [
"main",
"entry",
"point"
] | python | train | 30.52381 |
mgagne/wafflehaus.iweb | wafflehaus/iweb/keystone/user_filter/blacklist.py | https://github.com/mgagne/wafflehaus.iweb/blob/8ac625582c1180391fe022d1db19f70a2dfb376a/wafflehaus/iweb/keystone/user_filter/blacklist.py#L89-L96 | def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def blacklist(app):
return BlacklistFilter(app, conf)
return blacklist | [
"def",
"filter_factory",
"(",
"global_conf",
",",
"*",
"*",
"local_conf",
")",
":",
"conf",
"=",
"global_conf",
".",
"copy",
"(",
")",
"conf",
".",
"update",
"(",
"local_conf",
")",
"def",
"blacklist",
"(",
"app",
")",
":",
"return",
"BlacklistFilter",
"... | Returns a WSGI filter app for use with paste.deploy. | [
"Returns",
"a",
"WSGI",
"filter",
"app",
"for",
"use",
"with",
"paste",
".",
"deploy",
"."
] | python | train | 31 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L315-L325 | def _save_image(self, name, format='PNG'):
""" Shows a save dialog for the ImageResource with 'name'.
"""
dialog = QtGui.QFileDialog(self._control, 'Save Image')
dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
dialog.setDefaultSuffix(format.lower())
dialog.setNameFilte... | [
"def",
"_save_image",
"(",
"self",
",",
"name",
",",
"format",
"=",
"'PNG'",
")",
":",
"dialog",
"=",
"QtGui",
".",
"QFileDialog",
"(",
"self",
".",
"_control",
",",
"'Save Image'",
")",
"dialog",
".",
"setAcceptMode",
"(",
"QtGui",
".",
"QFileDialog",
"... | Shows a save dialog for the ImageResource with 'name'. | [
"Shows",
"a",
"save",
"dialog",
"for",
"the",
"ImageResource",
"with",
"name",
"."
] | python | test | 46.818182 |
jwodder/doapi | doapi/doapi.py | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/doapi.py#L524-L560 | def wait_actions_on_objects(self, objects, wait_interval=None,
wait_time=None):
"""
.. versionadded:: 0.2.0
Poll the server periodically until the most recent action on each
resource in ``objects`` has finished, yielding each resource's fin... | [
"def",
"wait_actions_on_objects",
"(",
"self",
",",
"objects",
",",
"wait_interval",
"=",
"None",
",",
"wait_time",
"=",
"None",
")",
":",
"acts",
"=",
"[",
"]",
"for",
"o",
"in",
"objects",
":",
"a",
"=",
"o",
".",
"fetch_last_action",
"(",
")",
"if",... | .. versionadded:: 0.2.0
Poll the server periodically until the most recent action on each
resource in ``objects`` has finished, yielding each resource's final
state when the corresponding action is done.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any
remaini... | [
"..",
"versionadded",
"::",
"0",
".",
"2",
".",
"0"
] | python | train | 44 |
h2non/paco | paco/pipe.py | https://github.com/h2non/paco/blob/1e5ef4df317e7cbbcefdf67d8dee28ce90538f3d/paco/pipe.py#L75-L108 | def overload(fn):
"""
Overload a given callable object to be used with ``|`` operator
overloading.
This is especially used for composing a pipeline of
transformation over a single data set.
Arguments:
fn (function): target function to decorate.
Raises:
TypeError: if functi... | [
"def",
"overload",
"(",
"fn",
")",
":",
"if",
"not",
"isfunction",
"(",
"fn",
")",
":",
"raise",
"TypeError",
"(",
"'paco: fn must be a callable object'",
")",
"spec",
"=",
"getargspec",
"(",
"fn",
")",
"args",
"=",
"spec",
".",
"args",
"if",
"not",
"spe... | Overload a given callable object to be used with ``|`` operator
overloading.
This is especially used for composing a pipeline of
transformation over a single data set.
Arguments:
fn (function): target function to decorate.
Raises:
TypeError: if function or coroutine function is no... | [
"Overload",
"a",
"given",
"callable",
"object",
"to",
"be",
"used",
"with",
"|",
"operator",
"overloading",
"."
] | python | train | 27.352941 |
manns/pyspread | pyspread/src/gui/_grid.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_grid.py#L172-L304 | def _bind(self):
"""Bind events to handlers"""
main_window = self.main_window
handlers = self.handlers
c_handlers = self.cell_handlers
# Non wx.Grid events
self.Bind(wx.EVT_MOUSEWHEEL, handlers.OnMouseWheel)
self.Bind(wx.EVT_KEY_DOWN, handlers.OnKey)
... | [
"def",
"_bind",
"(",
"self",
")",
":",
"main_window",
"=",
"self",
".",
"main_window",
"handlers",
"=",
"self",
".",
"handlers",
"c_handlers",
"=",
"self",
".",
"cell_handlers",
"# Non wx.Grid events",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_MOUSEWHEEL",
"... | Bind events to handlers | [
"Bind",
"events",
"to",
"handlers"
] | python | train | 44.819549 |
apache/incubator-mxnet | tools/launch.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/launch.py#L31-L54 | def dmlc_opts(opts):
"""convert from mxnet's opts to dmlc's opts
"""
args = ['--num-workers', str(opts.num_workers),
'--num-servers', str(opts.num_servers),
'--cluster', opts.launcher,
'--host-file', opts.hostfile,
'--sync-dst-dir', opts.sync_dst_dir]
# c... | [
"def",
"dmlc_opts",
"(",
"opts",
")",
":",
"args",
"=",
"[",
"'--num-workers'",
",",
"str",
"(",
"opts",
".",
"num_workers",
")",
",",
"'--num-servers'",
",",
"str",
"(",
"opts",
".",
"num_servers",
")",
",",
"'--cluster'",
",",
"opts",
".",
"launcher",
... | convert from mxnet's opts to dmlc's opts | [
"convert",
"from",
"mxnet",
"s",
"opts",
"to",
"dmlc",
"s",
"opts"
] | python | train | 33.5 |
tariqdaouda/pyGeno | pyGeno/tools/UsefulFunctions.py | https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/UsefulFunctions.py#L153-L174 | def complementTab(seq=[]):
"""returns a list of complementary sequence without inversing it"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R': 'Y', 'Y': 'R', 'M': 'K', 'K': 'M',
'W': 'W', 'S': 'S', 'B': 'V', 'D': 'H', 'H': 'D', 'V': 'B', 'N': 'N', 'a': 't',
'c': 'g... | [
"def",
"complementTab",
"(",
"seq",
"=",
"[",
"]",
")",
":",
"complement",
"=",
"{",
"'A'",
":",
"'T'",
",",
"'C'",
":",
"'G'",
",",
"'G'",
":",
"'C'",
",",
"'T'",
":",
"'A'",
",",
"'R'",
":",
"'Y'",
",",
"'Y'",
":",
"'R'",
",",
"'M'",
":",
... | returns a list of complementary sequence without inversing it | [
"returns",
"a",
"list",
"of",
"complementary",
"sequence",
"without",
"inversing",
"it"
] | python | train | 44.772727 |
saltstack/salt | salt/modules/minion.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/minion.py#L75-L142 | def kill(timeout=15):
'''
Kill the salt minion.
timeout
int seconds to wait for the minion to die.
If you have a monitor that restarts ``salt-minion`` when it dies then this is
a great way to restart after a minion upgrade.
CLI example::
>$ salt minion[12] minion.kill
... | [
"def",
"kill",
"(",
"timeout",
"=",
"15",
")",
":",
"ret",
"=",
"{",
"'killed'",
":",
"None",
",",
"'retcode'",
":",
"1",
",",
"}",
"comment",
"=",
"[",
"]",
"pid",
"=",
"__grains__",
".",
"get",
"(",
"'pid'",
")",
"if",
"not",
"pid",
":",
"com... | Kill the salt minion.
timeout
int seconds to wait for the minion to die.
If you have a monitor that restarts ``salt-minion`` when it dies then this is
a great way to restart after a minion upgrade.
CLI example::
>$ salt minion[12] minion.kill
minion1:
----------
... | [
"Kill",
"the",
"salt",
"minion",
"."
] | python | train | 30.720588 |
ontio/ontology-python-sdk | ontology/account/account.py | https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/account/account.py#L108-L130 | def export_gcm_encrypted_private_key(self, password: str, salt: str, n: int = 16384) -> str:
"""
This interface is used to export an AES algorithm encrypted private key with the mode of GCM.
:param password: the secret pass phrase to generate the keys from.
:param salt: A string to use ... | [
"def",
"export_gcm_encrypted_private_key",
"(",
"self",
",",
"password",
":",
"str",
",",
"salt",
":",
"str",
",",
"n",
":",
"int",
"=",
"16384",
")",
"->",
"str",
":",
"r",
"=",
"8",
"p",
"=",
"8",
"dk_len",
"=",
"64",
"scrypt",
"=",
"Scrypt",
"("... | This interface is used to export an AES algorithm encrypted private key with the mode of GCM.
:param password: the secret pass phrase to generate the keys from.
:param salt: A string to use for better protection from dictionary attacks.
This value does not need to be kept secret, ... | [
"This",
"interface",
"is",
"used",
"to",
"export",
"an",
"AES",
"algorithm",
"encrypted",
"private",
"key",
"with",
"the",
"mode",
"of",
"GCM",
"."
] | python | train | 54.565217 |
log2timeline/plaso | plaso/storage/fake/writer.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/fake/writer.py#L214-L234 | def CreateTaskStorage(self, task):
"""Creates a task storage.
Args:
task (Task): task.
Returns:
FakeStorageWriter: storage writer.
Raises:
IOError: if the task storage already exists.
OSError: if the task storage already exists.
"""
if task.identifier in self._task_sto... | [
"def",
"CreateTaskStorage",
"(",
"self",
",",
"task",
")",
":",
"if",
"task",
".",
"identifier",
"in",
"self",
".",
"_task_storage_writers",
":",
"raise",
"IOError",
"(",
"'Storage writer for task: {0:s} already exists.'",
".",
"format",
"(",
"task",
".",
"identif... | Creates a task storage.
Args:
task (Task): task.
Returns:
FakeStorageWriter: storage writer.
Raises:
IOError: if the task storage already exists.
OSError: if the task storage already exists. | [
"Creates",
"a",
"task",
"storage",
"."
] | python | train | 29.904762 |
jciskey/pygraph | pygraph/classes/directed_graph.py | https://github.com/jciskey/pygraph/blob/037bb2f32503fecb60d62921f9766d54109f15e2/pygraph/classes/directed_graph.py#L100-L104 | def adjacent(self, node_a, node_b):
"""Determines whether there is an edge from node_a to node_b.
Returns True if such an edge exists, otherwise returns False."""
neighbors = self.neighbors(node_a)
return node_b in neighbors | [
"def",
"adjacent",
"(",
"self",
",",
"node_a",
",",
"node_b",
")",
":",
"neighbors",
"=",
"self",
".",
"neighbors",
"(",
"node_a",
")",
"return",
"node_b",
"in",
"neighbors"
] | Determines whether there is an edge from node_a to node_b.
Returns True if such an edge exists, otherwise returns False. | [
"Determines",
"whether",
"there",
"is",
"an",
"edge",
"from",
"node_a",
"to",
"node_b",
".",
"Returns",
"True",
"if",
"such",
"an",
"edge",
"exists",
"otherwise",
"returns",
"False",
"."
] | python | train | 50.4 |
pycontribs/pyrax | pyrax/clouddatabases.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/clouddatabases.py#L736-L742 | def create_user(self, instance, name, password, database_names, host=None):
"""
Creates a user with the specified name and password, and gives that
user access to the specified database(s).
"""
return instance.create_user(name=name, password=password,
database_nam... | [
"def",
"create_user",
"(",
"self",
",",
"instance",
",",
"name",
",",
"password",
",",
"database_names",
",",
"host",
"=",
"None",
")",
":",
"return",
"instance",
".",
"create_user",
"(",
"name",
"=",
"name",
",",
"password",
"=",
"password",
",",
"datab... | Creates a user with the specified name and password, and gives that
user access to the specified database(s). | [
"Creates",
"a",
"user",
"with",
"the",
"specified",
"name",
"and",
"password",
"and",
"gives",
"that",
"user",
"access",
"to",
"the",
"specified",
"database",
"(",
"s",
")",
"."
] | python | train | 49 |
numenta/nupic | src/nupic/data/generators/data_generator.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/data_generator.py#L50-L56 | def getDescription(self):
"""Returns a description of the dataset"""
description = {'name':self.name, 'fields':[f.name for f in self.fields], \
'numRecords by field':[f.numRecords for f in self.fields]}
return description | [
"def",
"getDescription",
"(",
"self",
")",
":",
"description",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'fields'",
":",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"self",
".",
"fields",
"]",
",",
"'numRecords by field'",
":",
"[",
"f",
".",
... | Returns a description of the dataset | [
"Returns",
"a",
"description",
"of",
"the",
"dataset"
] | python | valid | 33.571429 |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L155-L163 | def update(self):
"""Update the data from the thermostat. Always sets the current time."""
_LOGGER.debug("Querying the device..")
time = datetime.now()
value = struct.pack('BBBBBBB', PROP_INFO_QUERY,
time.year % 100, time.month, time.day,
... | [
"def",
"update",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Querying the device..\"",
")",
"time",
"=",
"datetime",
".",
"now",
"(",
")",
"value",
"=",
"struct",
".",
"pack",
"(",
"'BBBBBBB'",
",",
"PROP_INFO_QUERY",
",",
"time",
".",
"year"... | Update the data from the thermostat. Always sets the current time. | [
"Update",
"the",
"data",
"from",
"the",
"thermostat",
".",
"Always",
"sets",
"the",
"current",
"time",
"."
] | python | train | 46 |
tjcsl/ion | intranet/apps/eighth/models.py | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L551-L558 | def date_in_past(self):
"""Is the block's date in the past?
(Has it not yet happened?)
"""
now = datetime.datetime.now()
return (now.date() > self.date) | [
"def",
"date_in_past",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"return",
"(",
"now",
".",
"date",
"(",
")",
">",
"self",
".",
"date",
")"
] | Is the block's date in the past?
(Has it not yet happened?) | [
"Is",
"the",
"block",
"s",
"date",
"in",
"the",
"past?"
] | python | train | 23.375 |
totalgood/nlpia | src/nlpia/loaders.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L544-L546 | def series_lstrip(series, startswith='http://', ignorecase=True):
""" Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str """
return series_strip(series, startswith=startswith, endswith=None, startsorendswith=None, ignorecase=ignorecase) | [
"def",
"series_lstrip",
"(",
"series",
",",
"startswith",
"=",
"'http://'",
",",
"ignorecase",
"=",
"True",
")",
":",
"return",
"series_strip",
"(",
"series",
",",
"startswith",
"=",
"startswith",
",",
"endswith",
"=",
"None",
",",
"startsorendswith",
"=",
"... | Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str | [
"Strip",
"a",
"suffix",
"str",
"(",
"endswith",
"str",
")",
"from",
"a",
"df",
"columns",
"or",
"pd",
".",
"Series",
"of",
"type",
"str"
] | python | train | 90.666667 |
onicagroup/runway | runway/blueprints/staticsite/staticsite.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/blueprints/staticsite/staticsite.py#L366-L372 | def get_cf_distribution_class():
"""Return the correct troposphere CF distribution class."""
if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'):
cf_dist = cloudfront.Distribution
cf_dist.props['DistributionConfig'] = (DistributionConfig, True)
return cf_dist
return clo... | [
"def",
"get_cf_distribution_class",
"(",
")",
":",
"if",
"LooseVersion",
"(",
"troposphere",
".",
"__version__",
")",
"==",
"LooseVersion",
"(",
"'2.4.0'",
")",
":",
"cf_dist",
"=",
"cloudfront",
".",
"Distribution",
"cf_dist",
".",
"props",
"[",
"'DistributionC... | Return the correct troposphere CF distribution class. | [
"Return",
"the",
"correct",
"troposphere",
"CF",
"distribution",
"class",
"."
] | python | train | 47.714286 |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L1093-L1112 | def _iso_name_and_parent_from_path(self, iso_path):
# type: (bytes) -> Tuple[bytes, dr.DirectoryRecord]
'''
An internal method to find the parent directory record and name given an
ISO path. If the parent is found, return a tuple containing the
basename of the path and the paren... | [
"def",
"_iso_name_and_parent_from_path",
"(",
"self",
",",
"iso_path",
")",
":",
"# type: (bytes) -> Tuple[bytes, dr.DirectoryRecord]",
"splitpath",
"=",
"utils",
".",
"split_path",
"(",
"iso_path",
")",
"name",
"=",
"splitpath",
".",
"pop",
"(",
")",
"parent",
"=",... | An internal method to find the parent directory record and name given an
ISO path. If the parent is found, return a tuple containing the
basename of the path and the parent directory record object.
Parameters:
iso_path - The absolute ISO path to the entry on the ISO.
Returns:
... | [
"An",
"internal",
"method",
"to",
"find",
"the",
"parent",
"directory",
"record",
"and",
"name",
"given",
"an",
"ISO",
"path",
".",
"If",
"the",
"parent",
"is",
"found",
"return",
"a",
"tuple",
"containing",
"the",
"basename",
"of",
"the",
"path",
"and",
... | python | train | 39.35 |
a1ezzz/wasp-general | wasp_general/task/thread.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/thread.py#L237-L245 | def thread_exception(self, raised_exception):
""" Callback for handling exception, that are raised inside :meth:`.WThreadTask.thread_started`
:param raised_exception: raised exception
:return: None
"""
print('Thread execution was stopped by the exception. Exception: %s' % str(raised_exception))
print('Trac... | [
"def",
"thread_exception",
"(",
"self",
",",
"raised_exception",
")",
":",
"print",
"(",
"'Thread execution was stopped by the exception. Exception: %s'",
"%",
"str",
"(",
"raised_exception",
")",
")",
"print",
"(",
"'Traceback:'",
")",
"print",
"(",
"traceback",
".",... | Callback for handling exception, that are raised inside :meth:`.WThreadTask.thread_started`
:param raised_exception: raised exception
:return: None | [
"Callback",
"for",
"handling",
"exception",
"that",
"are",
"raised",
"inside",
":",
"meth",
":",
".",
"WThreadTask",
".",
"thread_started"
] | python | train | 39.111111 |
astropy/photutils | photutils/segmentation/properties.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L838-L865 | def source_sum_err(self):
"""
The uncertainty of `~photutils.SourceProperties.source_sum`,
propagated from the input ``error`` array.
``source_sum_err`` is the quadrature sum of the total errors
over the non-masked pixels within the source segment:
.. math:: \\Delta F =... | [
"def",
"source_sum_err",
"(",
"self",
")",
":",
"if",
"self",
".",
"_error",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_error_unit",
"# table output needs unit",
"else",
":",
"... | The uncertainty of `~photutils.SourceProperties.source_sum`,
propagated from the input ``error`` array.
``source_sum_err`` is the quadrature sum of the total errors
over the non-masked pixels within the source segment:
.. math:: \\Delta F = \\sqrt{\\sum_{i \\in S}
\\s... | [
"The",
"uncertainty",
"of",
"~photutils",
".",
"SourceProperties",
".",
"source_sum",
"propagated",
"from",
"the",
"input",
"error",
"array",
"."
] | python | train | 37.964286 |
saltstack/salt | salt/netapi/rest_tornado/saltnado.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L1073-L1111 | def job_not_running(self, jid, tgt, tgt_type, minions, is_finished):
'''
Return a future which will complete once jid (passed in) is no longer
running on tgt
'''
ping_pub_data = yield self.saltclients['local'](tgt,
'saltutil... | [
"def",
"job_not_running",
"(",
"self",
",",
"jid",
",",
"tgt",
",",
"tgt_type",
",",
"minions",
",",
"is_finished",
")",
":",
"ping_pub_data",
"=",
"yield",
"self",
".",
"saltclients",
"[",
"'local'",
"]",
"(",
"tgt",
",",
"'saltutil.find_job'",
",",
"[",
... | Return a future which will complete once jid (passed in) is no longer
running on tgt | [
"Return",
"a",
"future",
"which",
"will",
"complete",
"once",
"jid",
"(",
"passed",
"in",
")",
"is",
"no",
"longer",
"running",
"on",
"tgt"
] | python | train | 48.384615 |
artefactual-labs/agentarchives | agentarchives/atom/client.py | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/atom/client.py#L266-L276 | def get_levels_of_description(self):
"""
Returns an array of all levels of description defined in this AtoM instance.
"""
if not hasattr(self, "levels_of_description"):
self.levels_of_description = [
item["name"]
for item in self._get(urljoin(s... | [
"def",
"get_levels_of_description",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"levels_of_description\"",
")",
":",
"self",
".",
"levels_of_description",
"=",
"[",
"item",
"[",
"\"name\"",
"]",
"for",
"item",
"in",
"self",
".",
"_get"... | Returns an array of all levels of description defined in this AtoM instance. | [
"Returns",
"an",
"array",
"of",
"all",
"levels",
"of",
"description",
"defined",
"in",
"this",
"AtoM",
"instance",
"."
] | python | train | 36.818182 |
gabstopper/smc-python | smc-monitoring/smc_monitoring/models/formats.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc-monitoring/smc_monitoring/models/formats.py#L101-L116 | def set_resolving(self, **kw):
"""
Certain log fields can be individually resolved. Use this
method to set these fields. Valid keyword arguments:
:param str timezone: string value to set timezone for audits
:param bool time_show_zone: show the time zone in the audit.
... | [
"def",
"set_resolving",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"if",
"'timezone'",
"in",
"kw",
"and",
"'time_show_zone'",
"not",
"in",
"kw",
":",
"kw",
".",
"update",
"(",
"time_show_zone",
"=",
"True",
")",
"self",
".",
"data",
"[",
"'resolving'"... | Certain log fields can be individually resolved. Use this
method to set these fields. Valid keyword arguments:
:param str timezone: string value to set timezone for audits
:param bool time_show_zone: show the time zone in the audit.
:param bool time_show_millis: show timezone in... | [
"Certain",
"log",
"fields",
"can",
"be",
"individually",
"resolved",
".",
"Use",
"this",
"method",
"to",
"set",
"these",
"fields",
".",
"Valid",
"keyword",
"arguments",
":",
":",
"param",
"str",
"timezone",
":",
"string",
"value",
"to",
"set",
"timezone",
... | python | train | 46.9375 |
danilobellini/audiolazy | audiolazy/lazy_io.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_io.py#L94-L128 | def chunks(seq, size=None, dfmt="f", byte_order=None, padval=0.):
"""
Chunk generator based on the array module (Python standard library).
See chunk.struct for more help. This strategy uses array.array (random access
by indexing management) instead of struct.Struct and blocks/deque (circular
queue appending)... | [
"def",
"chunks",
"(",
"seq",
",",
"size",
"=",
"None",
",",
"dfmt",
"=",
"\"f\"",
",",
"byte_order",
"=",
"None",
",",
"padval",
"=",
"0.",
")",
":",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"chunks",
".",
"size",
"chunk",
"=",
"array",
".",... | Chunk generator based on the array module (Python standard library).
See chunk.struct for more help. This strategy uses array.array (random access
by indexing management) instead of struct.Struct and blocks/deque (circular
queue appending) from the chunks.struct strategy.
Hint
----
Try each one to find th... | [
"Chunk",
"generator",
"based",
"on",
"the",
"array",
"module",
"(",
"Python",
"standard",
"library",
")",
"."
] | python | train | 27.142857 |
Syndace/python-omemo | omemo/sessionmanager.py | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L177-L437 | def __encryptKeyTransportMessage(
self,
bare_jids,
encryption_callback,
bundles = None,
expect_problems = None,
ignore_trust = False
):
"""
bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptog... | [
"def",
"__encryptKeyTransportMessage",
"(",
"self",
",",
"bare_jids",
",",
"encryption_callback",
",",
"bundles",
"=",
"None",
",",
"expect_problems",
"=",
"None",
",",
"ignore_trust",
"=",
"False",
")",
":",
"yield",
"self",
".",
"runInactiveDeviceCleanup",
"(",
... | bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything.
bundles: { [bare_jid: string] => { [device_id: int] => ExtendedPublicBu... | [
"bare_jids",
":",
"iterable<string",
">",
"encryption_callback",
":",
"A",
"function",
"which",
"is",
"called",
"using",
"an",
"instance",
"of",
"cryptography",
".",
"hazmat",
".",
"primitives",
".",
"ciphers",
".",
"CipherContext",
"which",
"you",
"can",
"use",... | python | train | 35.030651 |
dropbox/stone | stone/ir/data_types.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/ir/data_types.py#L1919-L1934 | def unwrap_aliases(data_type):
"""
Convenience method to unwrap all Alias(es) from around a DataType.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool]: The underlying data type and a bool indicating
whether the input type had at least one alia... | [
"def",
"unwrap_aliases",
"(",
"data_type",
")",
":",
"unwrapped_alias",
"=",
"False",
"while",
"is_alias",
"(",
"data_type",
")",
":",
"unwrapped_alias",
"=",
"True",
"data_type",
"=",
"data_type",
".",
"data_type",
"return",
"data_type",
",",
"unwrapped_alias"
] | Convenience method to unwrap all Alias(es) from around a DataType.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool]: The underlying data type and a bool indicating
whether the input type had at least one alias layer. | [
"Convenience",
"method",
"to",
"unwrap",
"all",
"Alias",
"(",
"es",
")",
"from",
"around",
"a",
"DataType",
"."
] | python | train | 30.5625 |
INM-6/hybridLFPy | examples/Hagen_et_al_2016_cercor/Fig3/Fig3.py | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/examples/Hagen_et_al_2016_cercor/Fig3/Fig3.py#L69-L108 | def run_sim(morphology='patdemo/cells/j4a.hoc',
cell_rotation=dict(x=4.99, y=-4.33, z=3.14),
closest_idx=dict(x=-200., y=0., z=800.)):
'''set up simple cell simulation with LFPs in the plane'''
# Create cell
cell = LFPy.Cell(morphology=morphology, **cell_parameters)
# Align cell... | [
"def",
"run_sim",
"(",
"morphology",
"=",
"'patdemo/cells/j4a.hoc'",
",",
"cell_rotation",
"=",
"dict",
"(",
"x",
"=",
"4.99",
",",
"y",
"=",
"-",
"4.33",
",",
"z",
"=",
"3.14",
")",
",",
"closest_idx",
"=",
"dict",
"(",
"x",
"=",
"-",
"200.",
",",
... | set up simple cell simulation with LFPs in the plane | [
"set",
"up",
"simple",
"cell",
"simulation",
"with",
"LFPs",
"in",
"the",
"plane"
] | python | train | 34.6 |
senaite/senaite.jsonapi | src/senaite/jsonapi/api.py | https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/api.py#L367-L395 | def get_parent_info(brain_or_object, endpoint=None):
"""Generate url information for the parent object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param endpoint: The named URL endpoint for the root of the item... | [
"def",
"get_parent_info",
"(",
"brain_or_object",
",",
"endpoint",
"=",
"None",
")",
":",
"# special case for the portal object",
"if",
"is_root",
"(",
"brain_or_object",
")",
":",
"return",
"{",
"}",
"# get the parent object",
"parent",
"=",
"get_parent",
"(",
"bra... | Generate url information for the parent object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param endpoint: The named URL endpoint for the root of the items
:type endpoint: str/unicode
:returns: URL informat... | [
"Generate",
"url",
"information",
"for",
"the",
"parent",
"object"
] | python | train | 32 |
mitsei/dlkit | dlkit/json_/commenting/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/commenting/sessions.py#L651-L667 | def get_comments(self):
"""Gets all comments.
return: (osid.commenting.CommentList) - a list of comments
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""... | [
"def",
"get_comments",
"(",
"self",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'commenting'",
",",
"collection",
"=",... | Gets all comments.
return: (osid.commenting.CommentList) - a list of comments
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"all",
"comments",
"."
] | python | train | 48 |
xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L1088-L1113 | def _parseExpression(self, src, returnList=False):
"""
expr
: term [ operator term ]*
;
"""
src, term = self._parseExpressionTerm(src)
operator = None
while src[:1] not in ('', ';', '{', '}', '[', ']', ')'):
for operator in self.ExpressionOpera... | [
"def",
"_parseExpression",
"(",
"self",
",",
"src",
",",
"returnList",
"=",
"False",
")",
":",
"src",
",",
"term",
"=",
"self",
".",
"_parseExpressionTerm",
"(",
"src",
")",
"operator",
"=",
"None",
"while",
"src",
"[",
":",
"1",
"]",
"not",
"in",
"(... | expr
: term [ operator term ]*
; | [
"expr",
":",
"term",
"[",
"operator",
"term",
"]",
"*",
";"
] | python | train | 33.423077 |
saltstack/salt | salt/modules/azurearm_resource.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L334-L362 | def deployment_check_existence(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Check the existence of a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-b... | [
"def",
"deployment_check_existence",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
... | .. versionadded:: 2019.2.0
Check the existence of a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.deployment_check_existence ... | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train | 26.413793 |
thespacedoctor/tastic | tastic/tastic.py | https://github.com/thespacedoctor/tastic/blob/a0a16cf329a50057906ac3f696bb60b6fcee25e0/tastic/tastic.py#L162-L186 | def tags(
self):
"""*The list of tags associated with this taskpaper object*
**Usage:**
..
project and task objects can have associated tags. To get a list of tags assigned to an object use:
.. code-block:: python
projectTag = aProject.t... | [
"def",
"tags",
"(",
"self",
")",
":",
"tags",
"=",
"[",
"]",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'@[^@]*'",
",",
"re",
".",
"S",
")",
"if",
"self",
".",
"meta",
"[",
"\"tagString\"",
"]",
":",
"matchList",
"=",
"regex",
".",
"findall",
"("... | *The list of tags associated with this taskpaper object*
**Usage:**
..
project and task objects can have associated tags. To get a list of tags assigned to an object use:
.. code-block:: python
projectTag = aProject.tags
taskTags = aTasks.ta... | [
"*",
"The",
"list",
"of",
"tags",
"associated",
"with",
"this",
"taskpaper",
"object",
"*"
] | python | train | 27.92 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/quaternion.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/quaternion.py#L514-L526 | def dcm(self, dcm):
"""
Set the DCM
:param dcm: Matrix3
"""
assert(isinstance(dcm, Matrix3))
self._dcm = dcm.copy()
# mark other representations as outdated, will get generated on next
# read
self._q = None
self._euler = None | [
"def",
"dcm",
"(",
"self",
",",
"dcm",
")",
":",
"assert",
"(",
"isinstance",
"(",
"dcm",
",",
"Matrix3",
")",
")",
"self",
".",
"_dcm",
"=",
"dcm",
".",
"copy",
"(",
")",
"# mark other representations as outdated, will get generated on next",
"# read",
"self"... | Set the DCM
:param dcm: Matrix3 | [
"Set",
"the",
"DCM",
":",
"param",
"dcm",
":",
"Matrix3"
] | python | train | 22.692308 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.