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 |
|---|---|---|---|---|---|---|---|---|---|
SBRG/ssbio | ssbio/complex/bioassembly.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/complex/bioassembly.py#L53-L69 | def load_bioassembly_info_from_file(self, biomol_num):
"""Load metadata about a bioassembly (such as chains and their transformations) from a structure file.
"""
# current functionality is to take in a pre-assembled bioassembly file, parse it's MODELs and get info from that
pass
... | [
"def",
"load_bioassembly_info_from_file",
"(",
"self",
",",
"biomol_num",
")",
":",
"# current functionality is to take in a pre-assembled bioassembly file, parse it's MODELs and get info from that",
"pass",
"from",
"Bio",
".",
"PDB",
"import",
"PDBParser",
"p",
"=",
"PDBParser",... | Load metadata about a bioassembly (such as chains and their transformations) from a structure file. | [
"Load",
"metadata",
"about",
"a",
"bioassembly",
"(",
"such",
"as",
"chains",
"and",
"their",
"transformations",
")",
"from",
"a",
"structure",
"file",
"."
] | python | train | 42.294118 |
cloudera/impyla | impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L2189-L2196 | def get_table(self, dbname, tbl_name):
"""
Parameters:
- dbname
- tbl_name
"""
self.send_get_table(dbname, tbl_name)
return self.recv_get_table() | [
"def",
"get_table",
"(",
"self",
",",
"dbname",
",",
"tbl_name",
")",
":",
"self",
".",
"send_get_table",
"(",
"dbname",
",",
"tbl_name",
")",
"return",
"self",
".",
"recv_get_table",
"(",
")"
] | Parameters:
- dbname
- tbl_name | [
"Parameters",
":",
"-",
"dbname",
"-",
"tbl_name"
] | python | train | 21 |
markuskiller/textblob-de | textblob_de/ext/_pattern/text/__init__.py | https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/__init__.py#L403-L425 | def apply(self, token, previous=(None, None), next=(None, None)):
""" Applies lexical rules to the given token, which is a [word, tag] list.
"""
w = token[0]
for r in self:
if r[1] in self._cmd: # Rule = ly hassuf 2 RB x
f, x, pos, cmd = bool(0), r[0], r[-2], ... | [
"def",
"apply",
"(",
"self",
",",
"token",
",",
"previous",
"=",
"(",
"None",
",",
"None",
")",
",",
"next",
"=",
"(",
"None",
",",
"None",
")",
")",
":",
"w",
"=",
"token",
"[",
"0",
"]",
"for",
"r",
"in",
"self",
":",
"if",
"r",
"[",
"1",... | Applies lexical rules to the given token, which is a [word, tag] list. | [
"Applies",
"lexical",
"rules",
"to",
"the",
"given",
"token",
"which",
"is",
"a",
"[",
"word",
"tag",
"]",
"list",
"."
] | python | train | 52.26087 |
breerly/threadloop | threadloop/threadloop.py | https://github.com/breerly/threadloop/blob/9d4f83660fd79fe15d741b831be9ee28dccacc30/threadloop/threadloop.py#L80-L91 | def is_ready(self):
"""Is thread & ioloop ready.
:returns bool:
"""
if not self._thread:
return False
if not self._ready.is_set():
return False
return True | [
"def",
"is_ready",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_thread",
":",
"return",
"False",
"if",
"not",
"self",
".",
"_ready",
".",
"is_set",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Is thread & ioloop ready.
:returns bool: | [
"Is",
"thread",
"&",
"ioloop",
"ready",
"."
] | python | train | 18.25 |
sqlboy/fileseq | src/fileseq/filesequence.py | https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L79-L91 | def copy(self):
"""
Create a deep copy of this sequence
Returns:
:obj:`.FileSequence`:
"""
fs = self.__class__.__new__(self.__class__)
fs.__dict__ = self.__dict__.copy()
fs._frameSet = None
if self._frameSet is not None:
fs._frameS... | [
"def",
"copy",
"(",
"self",
")",
":",
"fs",
"=",
"self",
".",
"__class__",
".",
"__new__",
"(",
"self",
".",
"__class__",
")",
"fs",
".",
"__dict__",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"fs",
".",
"_frameSet",
"=",
"None",
"if",
... | Create a deep copy of this sequence
Returns:
:obj:`.FileSequence`: | [
"Create",
"a",
"deep",
"copy",
"of",
"this",
"sequence"
] | python | train | 27.076923 |
ioos/compliance-checker | compliance_checker/cf/cf.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cf/cf.py#L1398-L1440 | def _check_flag_masks(self, ds, name):
'''
Check a variable's flag_masks attribute for compliance under CF
- flag_masks exists as an array
- flag_masks is the same dtype as the variable
- variable's dtype can support bit-field
- flag_masks is the same length as flag_mean... | [
"def",
"_check_flag_masks",
"(",
"self",
",",
"ds",
",",
"name",
")",
":",
"variable",
"=",
"ds",
".",
"variables",
"[",
"name",
"]",
"flag_masks",
"=",
"variable",
".",
"flag_masks",
"flag_meanings",
"=",
"getattr",
"(",
"ds",
",",
"'flag_meanings'",
",",... | Check a variable's flag_masks attribute for compliance under CF
- flag_masks exists as an array
- flag_masks is the same dtype as the variable
- variable's dtype can support bit-field
- flag_masks is the same length as flag_meanings
:param netCDF4.Dataset ds: An open netCDF dat... | [
"Check",
"a",
"variable",
"s",
"flag_masks",
"attribute",
"for",
"compliance",
"under",
"CF"
] | python | train | 43.348837 |
google/prettytensor | prettytensor/bookkeeper.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/bookkeeper.py#L565-L583 | def create_composite_loss(losses=None,
regularize=True,
include_marked=True,
name='cost'):
"""Creates a loss that is the sum of all specified losses.
Args:
losses: A sequence of losses to include.
regularize: Whether or not to in... | [
"def",
"create_composite_loss",
"(",
"losses",
"=",
"None",
",",
"regularize",
"=",
"True",
",",
"include_marked",
"=",
"True",
",",
"name",
"=",
"'cost'",
")",
":",
"books",
"=",
"for_default_graph",
"(",
")",
"return",
"books",
".",
"create_composite_loss",
... | Creates a loss that is the sum of all specified losses.
Args:
losses: A sequence of losses to include.
regularize: Whether or not to include regularization losses.
include_marked: Whether or not to use the marked losses.
name: The name for this variable.
Returns:
A single tensor that is the sum... | [
"Creates",
"a",
"loss",
"that",
"is",
"the",
"sum",
"of",
"all",
"specified",
"losses",
"."
] | python | train | 38.789474 |
matiasb/unpy2exe | unpy2exe.py | https://github.com/matiasb/unpy2exe/blob/7a579f323e2b46ec925281ede9d913b81aa7b781/unpy2exe.py#L77-L83 | def _resource_dump(pe, res):
"""Return the dump of the given resource."""
rva = res.data.struct.OffsetToData
size = res.data.struct.Size
dump = pe.get_data(rva, size)
return dump | [
"def",
"_resource_dump",
"(",
"pe",
",",
"res",
")",
":",
"rva",
"=",
"res",
".",
"data",
".",
"struct",
".",
"OffsetToData",
"size",
"=",
"res",
".",
"data",
".",
"struct",
".",
"Size",
"dump",
"=",
"pe",
".",
"get_data",
"(",
"rva",
",",
"size",
... | Return the dump of the given resource. | [
"Return",
"the",
"dump",
"of",
"the",
"given",
"resource",
"."
] | python | train | 27.571429 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/event.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/event.py#L595-L609 | def get_ntstatus_code(self):
"""
@rtype: int
@return: NTSTATUS status code that caused the exception.
@note: This method is only meaningful for in-page memory error
exceptions.
@raise NotImplementedError: Not an in-page memory error.
"""
if self.get... | [
"def",
"get_ntstatus_code",
"(",
"self",
")",
":",
"if",
"self",
".",
"get_exception_code",
"(",
")",
"!=",
"win32",
".",
"EXCEPTION_IN_PAGE_ERROR",
":",
"msg",
"=",
"\"This method is only meaningful \"",
"\"for in-page memory error exceptions.\"",
"raise",
"NotImplemente... | @rtype: int
@return: NTSTATUS status code that caused the exception.
@note: This method is only meaningful for in-page memory error
exceptions.
@raise NotImplementedError: Not an in-page memory error. | [
"@rtype",
":",
"int",
"@return",
":",
"NTSTATUS",
"status",
"code",
"that",
"caused",
"the",
"exception",
"."
] | python | train | 37.266667 |
ic-labs/django-icekit | icekit/publishing/models.py | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L365-L548 | def publishing_clone_relations(self, src_obj):
"""
Clone forward and reverse M2Ms.
This code is difficult to follow because the logic it applies is
confusing, but here is a summary that might help:
- when a draft object is published, the "current" and definitive
... | [
"def",
"publishing_clone_relations",
"(",
"self",
",",
"src_obj",
")",
":",
"def",
"clone_through_model_relationship",
"(",
"manager",
",",
"through_entry",
",",
"dst_obj",
",",
"rel_obj",
")",
":",
"dst_obj_filter",
"=",
"build_filter_for_through_field",
"(",
"manage... | Clone forward and reverse M2Ms.
This code is difficult to follow because the logic it applies is
confusing, but here is a summary that might help:
- when a draft object is published, the "current" and definitive
relationships are cloned to the published copy. The definitive
... | [
"Clone",
"forward",
"and",
"reverse",
"M2Ms",
"."
] | python | train | 50.983696 |
marvinpinto/charlesbot | charlesbot/plugins/ping_plugin.py | https://github.com/marvinpinto/charlesbot/blob/4bbc0de42313ea8aaaa8d0d36ff3e717575117b3/charlesbot/plugins/ping_plugin.py#L20-L23 | def schedule_ping_frequency(self): # pragma: no cover
"Send a ping message to slack every 20 seconds"
ping = crontab('* * * * * */20', func=self.send_ping, start=False)
ping.start() | [
"def",
"schedule_ping_frequency",
"(",
"self",
")",
":",
"# pragma: no cover",
"ping",
"=",
"crontab",
"(",
"'* * * * * */20'",
",",
"func",
"=",
"self",
".",
"send_ping",
",",
"start",
"=",
"False",
")",
"ping",
".",
"start",
"(",
")"
] | Send a ping message to slack every 20 seconds | [
"Send",
"a",
"ping",
"message",
"to",
"slack",
"every",
"20",
"seconds"
] | python | train | 50.75 |
Jammy2211/PyAutoLens | autolens/data/array/mask.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L54-L66 | def unmasked_for_shape_and_pixel_scale(cls, shape, pixel_scale, invert=False):
"""Setup a mask where all pixels are unmasked.
Parameters
----------
shape : (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pix... | [
"def",
"unmasked_for_shape_and_pixel_scale",
"(",
"cls",
",",
"shape",
",",
"pixel_scale",
",",
"invert",
"=",
"False",
")",
":",
"mask",
"=",
"np",
".",
"full",
"(",
"tuple",
"(",
"map",
"(",
"lambda",
"d",
":",
"int",
"(",
"d",
")",
",",
"shape",
"... | Setup a mask where all pixels are unmasked.
Parameters
----------
shape : (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel. | [
"Setup",
"a",
"mask",
"where",
"all",
"pixels",
"are",
"unmasked",
"."
] | python | valid | 40 |
JoseAntFer/pyny3d | pyny3d/geoms.py | https://github.com/JoseAntFer/pyny3d/blob/fb81684935a24f7e50c975cb4383c81a63ab56df/pyny3d/geoms.py#L818-L828 | def get_seed(self):
"""
Collects the required information to generate a data estructure
that can be used to recreate exactly the same geometry object
via *\*\*kwargs*.
:returns: Object's sufficient info to initialize it.
:rtype: dict
"""
... | [
"def",
"get_seed",
"(",
"self",
")",
":",
"return",
"{",
"'polygons'",
":",
"[",
"poly",
".",
"points",
"for",
"poly",
"in",
"self",
"]",
",",
"'holes'",
":",
"[",
"hole",
".",
"points",
"for",
"hole",
"in",
"self",
".",
"holes",
"]",
"}"
] | Collects the required information to generate a data estructure
that can be used to recreate exactly the same geometry object
via *\*\*kwargs*.
:returns: Object's sufficient info to initialize it.
:rtype: dict | [
"Collects",
"the",
"required",
"information",
"to",
"generate",
"a",
"data",
"estructure",
"that",
"can",
"be",
"used",
"to",
"recreate",
"exactly",
"the",
"same",
"geometry",
"object",
"via",
"*",
"\\",
"*",
"\\",
"*",
"kwargs",
"*",
".",
":",
"returns",
... | python | train | 38.727273 |
uw-it-aca/uw-restclients-sws | uw_sws/registration.py | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/registration.py#L141-L163 | def get_credits_by_section_and_regid(section, regid):
"""
Returns a uw_sws.models.Registration object
for the section and regid passed in.
"""
deprecation("Use get_credits_by_reg_url")
# note trailing comma in URL, it's required for the optional dup_code param
url = "{}{},{},{},{},{},{},.jso... | [
"def",
"get_credits_by_section_and_regid",
"(",
"section",
",",
"regid",
")",
":",
"deprecation",
"(",
"\"Use get_credits_by_reg_url\"",
")",
"# note trailing comma in URL, it's required for the optional dup_code param",
"url",
"=",
"\"{}{},{},{},{},{},{},.json\"",
".",
"format",
... | Returns a uw_sws.models.Registration object
for the section and regid passed in. | [
"Returns",
"a",
"uw_sws",
".",
"models",
".",
"Registration",
"object",
"for",
"the",
"section",
"and",
"regid",
"passed",
"in",
"."
] | python | train | 29 |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/refconverters/common.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/refconverters/common.py#L11-L16 | def get_library_citation():
'''Return a descriptive string and reference data for what users of the library should cite'''
all_ref_data = api.get_reference_data()
lib_refs_data = {k: all_ref_data[k] for k in _lib_refs}
return (_lib_refs_desc, lib_refs_data) | [
"def",
"get_library_citation",
"(",
")",
":",
"all_ref_data",
"=",
"api",
".",
"get_reference_data",
"(",
")",
"lib_refs_data",
"=",
"{",
"k",
":",
"all_ref_data",
"[",
"k",
"]",
"for",
"k",
"in",
"_lib_refs",
"}",
"return",
"(",
"_lib_refs_desc",
",",
"li... | Return a descriptive string and reference data for what users of the library should cite | [
"Return",
"a",
"descriptive",
"string",
"and",
"reference",
"data",
"for",
"what",
"users",
"of",
"the",
"library",
"should",
"cite"
] | python | train | 44.833333 |
pdkit/pdkit | pdkit/utils.py | https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/utils.py#L81-L94 | def load_segmented_data(filename):
"""
Helper function to load segmented gait time series data.
:param filename: The full path of the file that contais our data. This should be a comma separated value (csv file).
:type filename: str
:return: The gait time series segmented data, wit... | [
"def",
"load_segmented_data",
"(",
"filename",
")",
":",
"data",
"=",
"pd",
".",
"read_csv",
"(",
"filename",
",",
"index_col",
"=",
"0",
")",
"data",
".",
"index",
"=",
"data",
".",
"index",
".",
"astype",
"(",
"np",
".",
"datetime64",
")",
"return",
... | Helper function to load segmented gait time series data.
:param filename: The full path of the file that contais our data. This should be a comma separated value (csv file).
:type filename: str
:return: The gait time series segmented data, with a x, y, z, mag_acc_sum and segmented columns.
... | [
"Helper",
"function",
"to",
"load",
"segmented",
"gait",
"time",
"series",
"data",
"."
] | python | train | 36.571429 |
zhanglab/psamm | psamm/datasource/native.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/datasource/native.py#L244-L287 | def parse_compartments(self):
"""Parse compartment information from model.
Return tuple of: 1) iterator of
:class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs
defining the compartment boundaries of the model.
"""
compartments = OrderedDict()
bounda... | [
"def",
"parse_compartments",
"(",
"self",
")",
":",
"compartments",
"=",
"OrderedDict",
"(",
")",
"boundaries",
"=",
"set",
"(",
")",
"if",
"'compartments'",
"in",
"self",
".",
"_model",
":",
"boundary_map",
"=",
"{",
"}",
"for",
"compartment_def",
"in",
"... | Parse compartment information from model.
Return tuple of: 1) iterator of
:class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs
defining the compartment boundaries of the model. | [
"Parse",
"compartment",
"information",
"from",
"model",
"."
] | python | train | 41.886364 |
pygobject/pgi | pgi/overrides/Gtk.py | https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/Gtk.py#L1263-L1289 | def get(self, treeiter, *columns):
"""
:param treeiter: the :obj:`Gtk.TreeIter`
:type treeiter: :obj:`Gtk.TreeIter`
:param \\*columns: a list of column indices to fetch
:type columns: (:obj:`int`)
Returns a tuple of all values specified by their indices in `columns`
... | [
"def",
"get",
"(",
"self",
",",
"treeiter",
",",
"*",
"columns",
")",
":",
"n_columns",
"=",
"self",
".",
"get_n_columns",
"(",
")",
"values",
"=",
"[",
"]",
"for",
"col",
"in",
"columns",
":",
"if",
"not",
"isinstance",
"(",
"col",
",",
"int",
")"... | :param treeiter: the :obj:`Gtk.TreeIter`
:type treeiter: :obj:`Gtk.TreeIter`
:param \\*columns: a list of column indices to fetch
:type columns: (:obj:`int`)
Returns a tuple of all values specified by their indices in `columns`
in the order the indices are contained in `columns... | [
":",
"param",
"treeiter",
":",
"the",
":",
"obj",
":",
"Gtk",
".",
"TreeIter",
":",
"type",
"treeiter",
":",
":",
"obj",
":",
"Gtk",
".",
"TreeIter"
] | python | train | 29.962963 |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L4767-L4775 | def libvlc_media_list_player_new(p_instance):
'''Create new media_list_player.
@param p_instance: libvlc instance.
@return: media list player instance or NULL on error.
'''
f = _Cfunctions.get('libvlc_media_list_player_new', None) or \
_Cfunction('libvlc_media_list_player_new', ((1,),), clas... | [
"def",
"libvlc_media_list_player_new",
"(",
"p_instance",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_list_player_new'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_list_player_new'",
",",
"(",
"(",
"1",
",",
")",
",",
")",
... | Create new media_list_player.
@param p_instance: libvlc instance.
@return: media list player instance or NULL on error. | [
"Create",
"new",
"media_list_player",
"."
] | python | train | 45.555556 |
wbond/oscrypto | oscrypto/_osx/tls.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L531-L1004 | def _handshake(self):
"""
Perform an initial TLS handshake
"""
session_context = None
ssl_policy_ref = None
crl_search_ref = None
crl_policy_ref = None
ocsp_search_ref = None
ocsp_policy_ref = None
policy_array_ref = None
try:
... | [
"def",
"_handshake",
"(",
"self",
")",
":",
"session_context",
"=",
"None",
"ssl_policy_ref",
"=",
"None",
"crl_search_ref",
"=",
"None",
"crl_policy_ref",
"=",
"None",
"ocsp_search_ref",
"=",
"None",
"ocsp_policy_ref",
"=",
"None",
"policy_array_ref",
"=",
"None"... | Perform an initial TLS handshake | [
"Perform",
"an",
"initial",
"TLS",
"handshake"
] | python | valid | 43.601266 |
iblancasa/GitHubCity | src/githubcity/ghregion.py | https://github.com/iblancasa/GitHubCity/blob/c5299c6859dbefbd869e2ac6ff2faff2a39cf32f/src/githubcity/ghregion.py#L49-L60 | def addCity(self, fileName):
"""Add a JSON file and read the users.
:param fileName: path to the JSON file. This file has to have a list of
users, called users.
:type fileName: str.
"""
with open(fileName) as data_file:
data = load(data_file)
for u in... | [
"def",
"addCity",
"(",
"self",
",",
"fileName",
")",
":",
"with",
"open",
"(",
"fileName",
")",
"as",
"data_file",
":",
"data",
"=",
"load",
"(",
"data_file",
")",
"for",
"u",
"in",
"data",
"[",
"\"users\"",
"]",
":",
"if",
"not",
"any",
"(",
"d",
... | Add a JSON file and read the users.
:param fileName: path to the JSON file. This file has to have a list of
users, called users.
:type fileName: str. | [
"Add",
"a",
"JSON",
"file",
"and",
"read",
"the",
"users",
"."
] | python | train | 36.083333 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAData/data_resample.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_resample.py#L347-L408 | def QA_data_min_resample(min_data, type_='5min'):
"""分钟线采样成大周期
分钟线采样成子级别的分钟线
time+ OHLC==> resample
Arguments:
min {[type]} -- [description]
raw_type {[type]} -- [description]
new_type {[type]} -- [description]
"""
try:
min_data = min_data.reset_index().set_i... | [
"def",
"QA_data_min_resample",
"(",
"min_data",
",",
"type_",
"=",
"'5min'",
")",
":",
"try",
":",
"min_data",
"=",
"min_data",
".",
"reset_index",
"(",
")",
".",
"set_index",
"(",
"'datetime'",
",",
"drop",
"=",
"False",
")",
"except",
":",
"min_data",
... | 分钟线采样成大周期
分钟线采样成子级别的分钟线
time+ OHLC==> resample
Arguments:
min {[type]} -- [description]
raw_type {[type]} -- [description]
new_type {[type]} -- [description] | [
"分钟线采样成大周期"
] | python | train | 24.564516 |
ns1/ns1-python | ns1/zones.py | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/zones.py#L82-L100 | def update(self, callback=None, errback=None, **kwargs):
"""
Update zone configuration. Pass a list of keywords and their values to
update. For the list of keywords available for zone configuration, see
:attr:`ns1.rest.zones.Zones.INT_FIELDS` and
:attr:`ns1.rest.zones.Zones.PASST... | [
"def",
"update",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"data",
":",
"raise",
"ZoneException",
"(",
"'zone not loaded'",
")",
"def",
"success",
"(",
"result",... | Update zone configuration. Pass a list of keywords and their values to
update. For the list of keywords available for zone configuration, see
:attr:`ns1.rest.zones.Zones.INT_FIELDS` and
:attr:`ns1.rest.zones.Zones.PASSTHRU_FIELDS` | [
"Update",
"zone",
"configuration",
".",
"Pass",
"a",
"list",
"of",
"keywords",
"and",
"their",
"values",
"to",
"update",
".",
"For",
"the",
"list",
"of",
"keywords",
"available",
"for",
"zone",
"configuration",
"see",
":",
"attr",
":",
"ns1",
".",
"rest",
... | python | train | 36.947368 |
kathyxchen/crosstalk-correction | crosstalk_correction/crosstalk_correction.py | https://github.com/kathyxchen/crosstalk-correction/blob/eac11d54b39ea7ec301b54f8e498adce91713223/crosstalk_correction/crosstalk_correction.py#L239-L251 | def _update_pathway_definitions(crosstalk_corrected_index_map,
gene_row_names,
pathway_column_names):
"""Helper function to convert the mapping of int
(pathway id -> list of gene ids) to the corresponding pathway
names and gene identifiers.
... | [
"def",
"_update_pathway_definitions",
"(",
"crosstalk_corrected_index_map",
",",
"gene_row_names",
",",
"pathway_column_names",
")",
":",
"corrected_pathway_definitions",
"=",
"{",
"}",
"for",
"pathway_index",
",",
"gene_indices",
"in",
"crosstalk_corrected_index_map",
".",
... | Helper function to convert the mapping of int
(pathway id -> list of gene ids) to the corresponding pathway
names and gene identifiers. | [
"Helper",
"function",
"to",
"convert",
"the",
"mapping",
"of",
"int",
"(",
"pathway",
"id",
"-",
">",
"list",
"of",
"gene",
"ids",
")",
"to",
"the",
"corresponding",
"pathway",
"names",
"and",
"gene",
"identifiers",
"."
] | python | train | 50.461538 |
googleapis/google-auth-library-python | google/oauth2/service_account.py | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/oauth2/service_account.py#L155-L174 | def _from_signer_and_info(cls, signer, info, **kwargs):
"""Creates a Credentials instance from a signer and service account
info.
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
info (Mapping[str, str]): The service account info.
kwargs... | [
"def",
"_from_signer_and_info",
"(",
"cls",
",",
"signer",
",",
"info",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
"(",
"signer",
",",
"service_account_email",
"=",
"info",
"[",
"'client_email'",
"]",
",",
"token_uri",
"=",
"info",
"[",
"'token_ur... | Creates a Credentials instance from a signer and service account
info.
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
info (Mapping[str, str]): The service account info.
kwargs: Additional arguments to pass to the constructor.
Returns... | [
"Creates",
"a",
"Credentials",
"instance",
"from",
"a",
"signer",
"and",
"service",
"account",
"info",
"."
] | python | train | 36.45 |
drhagen/parsita | parsita/state.py | https://github.com/drhagen/parsita/blob/d97414a05541f48231381f607d1d2e6b50781d39/parsita/state.py#L186-L205 | def recursion_error(self, repeated_parser: str):
"""Generate an error to indicate that infinite recursion was encountered.
A parser can supply a representation of itself to this method and the
reader will supply the context, including the location where the
parser stalled.
Args... | [
"def",
"recursion_error",
"(",
"self",
",",
"repeated_parser",
":",
"str",
")",
":",
"if",
"self",
".",
"finished",
":",
"return",
"super",
"(",
")",
".",
"recursion_error",
"(",
"repeated_parser",
")",
"else",
":",
"line_index",
",",
"character_index",
",",... | Generate an error to indicate that infinite recursion was encountered.
A parser can supply a representation of itself to this method and the
reader will supply the context, including the location where the
parser stalled.
Args:
repeated_parser: A representation of the repea... | [
"Generate",
"an",
"error",
"to",
"indicate",
"that",
"infinite",
"recursion",
"was",
"encountered",
"."
] | python | test | 42.2 |
zomux/deepy | deepy/trainers/base.py | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/trainers/base.py#L90-L96 | def skip(self, n_batches, n_epochs=0):
"""
Skip N batches in the training.
"""
logging.info("skip %d epochs and %d batches" % (n_epochs, n_batches))
self._skip_batches = n_batches
self._skip_epochs = n_epochs | [
"def",
"skip",
"(",
"self",
",",
"n_batches",
",",
"n_epochs",
"=",
"0",
")",
":",
"logging",
".",
"info",
"(",
"\"skip %d epochs and %d batches\"",
"%",
"(",
"n_epochs",
",",
"n_batches",
")",
")",
"self",
".",
"_skip_batches",
"=",
"n_batches",
"self",
"... | Skip N batches in the training. | [
"Skip",
"N",
"batches",
"in",
"the",
"training",
"."
] | python | test | 35.714286 |
kmedian/korr | korr/find_unrelated.py | https://github.com/kmedian/korr/blob/4eb86fc14b1fc1b69204069b7753d115b327c937/korr/find_unrelated.py#L5-L28 | def find_unrelated(x, plim=0.1, axis=0):
"""Find indicies of insignificant un-/correlated variables
Example:
--------
i, j = find_unrelated(x, plim, rlim)
"""
# transpose if axis<>0
if axis is not 0:
x = x.T
# read dimensions and allocate variables
_, c = x.shape
p... | [
"def",
"find_unrelated",
"(",
"x",
",",
"plim",
"=",
"0.1",
",",
"axis",
"=",
"0",
")",
":",
"# transpose if axis<>0",
"if",
"axis",
"is",
"not",
"0",
":",
"x",
"=",
"x",
".",
"T",
"# read dimensions and allocate variables",
"_",
",",
"c",
"=",
"x",
".... | Find indicies of insignificant un-/correlated variables
Example:
--------
i, j = find_unrelated(x, plim, rlim) | [
"Find",
"indicies",
"of",
"insignificant",
"un",
"-",
"/",
"correlated",
"variables"
] | python | train | 23.416667 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv4.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv4.py#L166-L257 | def read_ipv4(self, length):
"""Read Internet Protocol version 4 (IPv4).
Structure of IPv4 header [RFC 791]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+... | [
"def",
"read_ipv4",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"len",
"(",
"self",
")",
"_vihl",
"=",
"self",
".",
"_read_fileng",
"(",
"1",
")",
".",
"hex",
"(",
")",
"_dscp",
"=",
"self",
".",
"_read... | Read Internet Protocol version 4 (IPv4).
Structure of IPv4 header [RFC 791]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
... | [
"Read",
"Internet",
"Protocol",
"version",
"4",
"(",
"IPv4",
")",
"."
] | python | train | 47.206522 |
sptonkin/fuzzyhashlib | fuzzyhashlib/__init__.py | https://github.com/sptonkin/fuzzyhashlib/blob/61999dcfb0893358a330f51d88e4fa494a91bce2/fuzzyhashlib/__init__.py#L86-L91 | def hexdigest(self):
"""Return the digest value as a string of hexadecimal digits."""
if self._pre_computed_hash is None:
return libssdeep_wrapper.fuzzy_digest(self._state, 0)
else:
return self._pre_computed_hash | [
"def",
"hexdigest",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pre_computed_hash",
"is",
"None",
":",
"return",
"libssdeep_wrapper",
".",
"fuzzy_digest",
"(",
"self",
".",
"_state",
",",
"0",
")",
"else",
":",
"return",
"self",
".",
"_pre_computed_hash"
] | Return the digest value as a string of hexadecimal digits. | [
"Return",
"the",
"digest",
"value",
"as",
"a",
"string",
"of",
"hexadecimal",
"digits",
"."
] | python | train | 42.5 |
MisterWil/abodepy | abodepy/devices/binary_sensor.py | https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/devices/binary_sensor.py#L11-L20 | def is_on(self):
"""
Get sensor state.
Assume offline or open (worst case).
"""
if self._type == 'Occupancy':
return self.status not in CONST.STATUS_ONLINE
return self.status not in (CONST.STATUS_OFF, CONST.STATUS_OFFLINE,
C... | [
"def",
"is_on",
"(",
"self",
")",
":",
"if",
"self",
".",
"_type",
"==",
"'Occupancy'",
":",
"return",
"self",
".",
"status",
"not",
"in",
"CONST",
".",
"STATUS_ONLINE",
"return",
"self",
".",
"status",
"not",
"in",
"(",
"CONST",
".",
"STATUS_OFF",
","... | Get sensor state.
Assume offline or open (worst case). | [
"Get",
"sensor",
"state",
"."
] | python | train | 33 |
bcbio/bcbio-nextgen | bcbio/ngsalign/alignprep.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L402-L439 | def _bgzip_from_cram(cram_file, dirs, data):
"""Create bgzipped fastq files from an input CRAM file in regions of interest.
Returns a list with a single file, for single end CRAM files, or two
files for paired end input.
"""
import pybedtools
region_file = (tz.get_in(["config", "algorithm", "va... | [
"def",
"_bgzip_from_cram",
"(",
"cram_file",
",",
"dirs",
",",
"data",
")",
":",
"import",
"pybedtools",
"region_file",
"=",
"(",
"tz",
".",
"get_in",
"(",
"[",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"variant_regions\"",
"]",
",",
"data",
")",
"if",
"t... | Create bgzipped fastq files from an input CRAM file in regions of interest.
Returns a list with a single file, for single end CRAM files, or two
files for paired end input. | [
"Create",
"bgzipped",
"fastq",
"files",
"from",
"an",
"input",
"CRAM",
"file",
"in",
"regions",
"of",
"interest",
"."
] | python | train | 48.815789 |
DataONEorg/d1_python | client_cli/src/d1_cli/impl/operation_formatter.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_cli/src/d1_cli/impl/operation_formatter.py#L94-L121 | def _format_value(self, operation, key, indent):
"""A value that exists in the operation but has value None is displayed.
A value that does not exist in the operation is left out entirely. The value
name in the operation must match the value name in the template, but the
location does n... | [
"def",
"_format_value",
"(",
"self",
",",
"operation",
",",
"key",
",",
"indent",
")",
":",
"v",
"=",
"self",
".",
"_find_value",
"(",
"operation",
",",
"key",
")",
"if",
"v",
"==",
"\"NOT_FOUND\"",
":",
"return",
"[",
"]",
"if",
"not",
"isinstance",
... | A value that exists in the operation but has value None is displayed.
A value that does not exist in the operation is left out entirely. The value
name in the operation must match the value name in the template, but the
location does not have to match. | [
"A",
"value",
"that",
"exists",
"in",
"the",
"operation",
"but",
"has",
"value",
"None",
"is",
"displayed",
"."
] | python | train | 33.25 |
litl/rauth | rauth/session.py | https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/session.py#L470-L515 | def sign(url, app_id, app_secret, hash_meth='sha1', **params):
'''
A signature method which generates the necessary Ofly parameters.
:param app_id: The oFlyAppId, i.e. "application ID".
:type app_id: str
:param app_secret: The oFlyAppSecret, i.e. "shared secret".
:type a... | [
"def",
"sign",
"(",
"url",
",",
"app_id",
",",
"app_secret",
",",
"hash_meth",
"=",
"'sha1'",
",",
"*",
"*",
"params",
")",
":",
"hash_meth_str",
"=",
"hash_meth",
"if",
"hash_meth",
"==",
"'sha1'",
":",
"hash_meth",
"=",
"sha1",
"elif",
"hash_meth",
"==... | A signature method which generates the necessary Ofly parameters.
:param app_id: The oFlyAppId, i.e. "application ID".
:type app_id: str
:param app_secret: The oFlyAppSecret, i.e. "shared secret".
:type app_secret: str
:param hash_meth: The hash method to use for signing, defaul... | [
"A",
"signature",
"method",
"which",
"generates",
"the",
"necessary",
"Ofly",
"parameters",
"."
] | python | train | 36.478261 |
ivelum/graphql-py | graphql/parser.py | https://github.com/ivelum/graphql-py/blob/72baf16d838e82349ee5e8d8f8971ce11cfcedf9/graphql/parser.py#L372-L378 | def p_directive(self, p):
"""
directive : AT name arguments
| AT name
"""
arguments = p[3] if len(p) == 4 else None
p[0] = Directive(name=p[2], arguments=arguments) | [
"def",
"p_directive",
"(",
"self",
",",
"p",
")",
":",
"arguments",
"=",
"p",
"[",
"3",
"]",
"if",
"len",
"(",
"p",
")",
"==",
"4",
"else",
"None",
"p",
"[",
"0",
"]",
"=",
"Directive",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"arguments",
... | directive : AT name arguments
| AT name | [
"directive",
":",
"AT",
"name",
"arguments",
"|",
"AT",
"name"
] | python | train | 30.857143 |
PMEAL/OpenPNM | openpnm/models/geometry/throat_vector.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/models/geometry/throat_vector.py#L10-L34 | def pore_to_pore(target):
r"""
Calculates throat vector as straight path between connected pores.
Parameters
----------
geometry : OpenPNM Geometry object
The object containing the geometrical properties of the throats
Notes
-----
There is an important impicit assumption here: ... | [
"def",
"pore_to_pore",
"(",
"target",
")",
":",
"network",
"=",
"target",
".",
"project",
".",
"network",
"throats",
"=",
"network",
".",
"throats",
"(",
"target",
".",
"name",
")",
"conns",
"=",
"network",
"[",
"'throat.conns'",
"]",
"P1",
"=",
"conns",... | r"""
Calculates throat vector as straight path between connected pores.
Parameters
----------
geometry : OpenPNM Geometry object
The object containing the geometrical properties of the throats
Notes
-----
There is an important impicit assumption here: the positive direction is
... | [
"r",
"Calculates",
"throat",
"vector",
"as",
"straight",
"path",
"between",
"connected",
"pores",
"."
] | python | train | 32.96 |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_store.py | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_store.py#L19-L26 | def get_ops(self, key):
''' Returns ops from the key if found otherwise raises a KeyError.
'''
ops = self._store.get(key)
if ops is None:
raise KeyError(
'cannot get operations for {}'.format(key))
return ops | [
"def",
"get_ops",
"(",
"self",
",",
"key",
")",
":",
"ops",
"=",
"self",
".",
"_store",
".",
"get",
"(",
"key",
")",
"if",
"ops",
"is",
"None",
":",
"raise",
"KeyError",
"(",
"'cannot get operations for {}'",
".",
"format",
"(",
"key",
")",
")",
"ret... | Returns ops from the key if found otherwise raises a KeyError. | [
"Returns",
"ops",
"from",
"the",
"key",
"if",
"found",
"otherwise",
"raises",
"a",
"KeyError",
"."
] | python | train | 33.625 |
saltstack/salt | salt/modules/solaris_user.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L63-L71 | def _build_gecos(gecos_dict):
'''
Accepts a dictionary entry containing GECOS field names and their values,
and returns a full GECOS comment string, to be used with usermod.
'''
return '{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''),
gecos_dict.get('roomnu... | [
"def",
"_build_gecos",
"(",
"gecos_dict",
")",
":",
"return",
"'{0},{1},{2},{3}'",
".",
"format",
"(",
"gecos_dict",
".",
"get",
"(",
"'fullname'",
",",
"''",
")",
",",
"gecos_dict",
".",
"get",
"(",
"'roomnumber'",
",",
"''",
")",
",",
"gecos_dict",
".",
... | Accepts a dictionary entry containing GECOS field names and their values,
and returns a full GECOS comment string, to be used with usermod. | [
"Accepts",
"a",
"dictionary",
"entry",
"containing",
"GECOS",
"field",
"names",
"and",
"their",
"values",
"and",
"returns",
"a",
"full",
"GECOS",
"comment",
"string",
"to",
"be",
"used",
"with",
"usermod",
"."
] | python | train | 51.222222 |
alvarogzp/telegram-bot-framework | bot/action/standard/info/formatter/chat.py | https://github.com/alvarogzp/telegram-bot-framework/blob/7b597a415c1901901c677976cb13100fc3083107/bot/action/standard/info/formatter/chat.py#L20-L29 | def format(self, full_info: bool = False):
"""
:param full_info: If True, adds more info about the chat. Please, note that this additional info requires
to make up to THREE synchronous api calls.
"""
chat = self.api_object
if full_info:
self.__format_full(... | [
"def",
"format",
"(",
"self",
",",
"full_info",
":",
"bool",
"=",
"False",
")",
":",
"chat",
"=",
"self",
".",
"api_object",
"if",
"full_info",
":",
"self",
".",
"__format_full",
"(",
"chat",
")",
"else",
":",
"self",
".",
"__format_simple",
"(",
"chat... | :param full_info: If True, adds more info about the chat. Please, note that this additional info requires
to make up to THREE synchronous api calls. | [
":",
"param",
"full_info",
":",
"If",
"True",
"adds",
"more",
"info",
"about",
"the",
"chat",
".",
"Please",
"note",
"that",
"this",
"additional",
"info",
"requires",
"to",
"make",
"up",
"to",
"THREE",
"synchronous",
"api",
"calls",
"."
] | python | train | 36.9 |
nderkach/airbnb-python | airbnb/api.py | https://github.com/nderkach/airbnb-python/blob/0b3ed69518e41383eca93ae11b24247f3cc69a27/airbnb/api.py#L186-L201 | def get_calendar(self, listing_id, starting_month=datetime.datetime.now().month, starting_year=datetime.datetime.now().year, calendar_months=12):
"""
Get availability calendar for a given listing
"""
params = {
'year': str(starting_year),
'listing_id': str(listing... | [
"def",
"get_calendar",
"(",
"self",
",",
"listing_id",
",",
"starting_month",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"month",
",",
"starting_year",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"year",
",",
"calendar_... | Get availability calendar for a given listing | [
"Get",
"availability",
"calendar",
"for",
"a",
"given",
"listing"
] | python | train | 36 |
eventbrite/eventbrite-sdk-python | eventbrite/access_methods.py | https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/access_methods.py#L883-L891 | def get_user_bookmarks(self, id, **data):
"""
GET /users/:id/bookmarks/
Gets all the user's saved events.
In order to update the saved events list, the user must unsave or save each event.
A user is authorized to only see his/her saved events.
"""
return ... | [
"def",
"get_user_bookmarks",
"(",
"self",
",",
"id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"/users/{0}/bookmarks/\"",
".",
"format",
"(",
"id",
")",
",",
"data",
"=",
"data",
")"
] | GET /users/:id/bookmarks/
Gets all the user's saved events.
In order to update the saved events list, the user must unsave or save each event.
A user is authorized to only see his/her saved events. | [
"GET",
"/",
"users",
"/",
":",
"id",
"/",
"bookmarks",
"/",
"Gets",
"all",
"the",
"user",
"s",
"saved",
"events",
".",
"In",
"order",
"to",
"update",
"the",
"saved",
"events",
"list",
"the",
"user",
"must",
"unsave",
"or",
"save",
"each",
"event",
".... | python | train | 40.777778 |
Shoobx/xmldiff | xmldiff/_diff_match_patch_py3.py | https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1348-L1362 | def match_alphabet(self, pattern):
"""Initialise the alphabet for the Bitap algorithm.
Args:
pattern: The text to encode.
Returns:
Hash of character locations.
"""
s = {}
for char in pattern:
s[char] = 0
for i in range(len(pattern)):
s[pattern[i]] |= 1 << (len(patte... | [
"def",
"match_alphabet",
"(",
"self",
",",
"pattern",
")",
":",
"s",
"=",
"{",
"}",
"for",
"char",
"in",
"pattern",
":",
"s",
"[",
"char",
"]",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"pattern",
")",
")",
":",
"s",
"[",
"pattern",... | Initialise the alphabet for the Bitap algorithm.
Args:
pattern: The text to encode.
Returns:
Hash of character locations. | [
"Initialise",
"the",
"alphabet",
"for",
"the",
"Bitap",
"algorithm",
"."
] | python | train | 22.066667 |
saltstack/salt | salt/modules/nspawn.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L1059-L1078 | def start(name):
'''
Start the named container
CLI Example:
.. code-block:: bash
salt myminion nspawn.start <name>
'''
if _sd_version() >= 219:
ret = _machinectl('start {0}'.format(name))
else:
cmd = 'systemctl start systemd-nspawn@{0}'.format(name)
ret = _... | [
"def",
"start",
"(",
"name",
")",
":",
"if",
"_sd_version",
"(",
")",
">=",
"219",
":",
"ret",
"=",
"_machinectl",
"(",
"'start {0}'",
".",
"format",
"(",
"name",
")",
")",
"else",
":",
"cmd",
"=",
"'systemctl start systemd-nspawn@{0}'",
".",
"format",
"... | Start the named container
CLI Example:
.. code-block:: bash
salt myminion nspawn.start <name> | [
"Start",
"the",
"named",
"container"
] | python | train | 24.3 |
MartinThoma/hwrt | hwrt/datasets/inkml.py | https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/datasets/inkml.py#L70-L155 | def read(filepath):
"""
Read a single InkML file
Parameters
----------
filepath : string
path to the (readable) InkML file
Returns
-------
HandwrittenData :
The parsed InkML file as a HandwrittenData object
"""
import xml.etree.ElementTree
root = xml.etree.E... | [
"def",
"read",
"(",
"filepath",
")",
":",
"import",
"xml",
".",
"etree",
".",
"ElementTree",
"root",
"=",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"parse",
"(",
"filepath",
")",
".",
"getroot",
"(",
")",
"# Get the raw data",
"recording",
"=",
"[",
... | Read a single InkML file
Parameters
----------
filepath : string
path to the (readable) InkML file
Returns
-------
HandwrittenData :
The parsed InkML file as a HandwrittenData object | [
"Read",
"a",
"single",
"InkML",
"file"
] | python | train | 39.686047 |
libtcod/python-tcod | tcod/tileset.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tileset.py#L120-L134 | def load_truetype_font(
path: str, tile_width: int, tile_height: int
) -> Tileset:
"""Return a new Tileset from a `.ttf` or `.otf` file.
Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead.
You can send this Tileset to :any:`set_default`.
This function is provisional. The API m... | [
"def",
"load_truetype_font",
"(",
"path",
":",
"str",
",",
"tile_width",
":",
"int",
",",
"tile_height",
":",
"int",
")",
"->",
"Tileset",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"RuntimeError",
"(",
"\"File ... | Return a new Tileset from a `.ttf` or `.otf` file.
Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead.
You can send this Tileset to :any:`set_default`.
This function is provisional. The API may change. | [
"Return",
"a",
"new",
"Tileset",
"from",
"a",
".",
"ttf",
"or",
".",
"otf",
"file",
"."
] | python | train | 36.466667 |
crackinglandia/pype32 | pype32/pype32.py | https://github.com/crackinglandia/pype32/blob/192fd14dfc0dd36d953739a81c17fbaf5e3d6076/pype32/pype32.py#L872-L880 | def isNXEnabled(self):
"""
Determines if the current L{PE} instance has the NXCOMPAT (Compatible with Data Execution Prevention) flag enabled.
@see: U{http://msdn.microsoft.com/en-us/library/ms235442.aspx}
@rtype: bool
@return: Returns C{True} if the current L{PE} instance has t... | [
"def",
"isNXEnabled",
"(",
"self",
")",
":",
"return",
"self",
".",
"ntHeaders",
".",
"optionalHeader",
".",
"dllCharacteristics",
".",
"value",
"&",
"consts",
".",
"IMAGE_DLL_CHARACTERISTICS_NX_COMPAT",
"==",
"consts",
".",
"IMAGE_DLL_CHARACTERISTICS_NX_COMPAT"
] | Determines if the current L{PE} instance has the NXCOMPAT (Compatible with Data Execution Prevention) flag enabled.
@see: U{http://msdn.microsoft.com/en-us/library/ms235442.aspx}
@rtype: bool
@return: Returns C{True} if the current L{PE} instance has the NXCOMPAT flag enabled. Otherwise, return... | [
"Determines",
"if",
"the",
"current",
"L",
"{",
"PE",
"}",
"instance",
"has",
"the",
"NXCOMPAT",
"(",
"Compatible",
"with",
"Data",
"Execution",
"Prevention",
")",
"flag",
"enabled",
".",
"@see",
":",
"U",
"{",
"http",
":",
"//",
"msdn",
".",
"microsoft"... | python | train | 59.888889 |
GNS3/gns3-server | gns3server/utils/__init__.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/__init__.py#L52-L90 | def parse_version(version):
"""
Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0
Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple
:returns: Version string as comparable tuple
"""
r... | [
"def",
"parse_version",
"(",
"version",
")",
":",
"release_type_found",
"=",
"False",
"version_infos",
"=",
"re",
".",
"split",
"(",
"'(\\.|[a-z]+)'",
",",
"version",
")",
"version",
"=",
"[",
"]",
"for",
"info",
"in",
"version_infos",
":",
"if",
"info",
"... | Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0
Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple
:returns: Version string as comparable tuple | [
"Return",
"a",
"comparable",
"tuple",
"from",
"a",
"version",
"string",
".",
"We",
"try",
"to",
"force",
"tuple",
"to",
"semver",
"with",
"version",
"like",
"1",
".",
"2",
".",
"0"
] | python | train | 35.435897 |
caktus/django-treenav | treenav/admin.py | https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/admin.py#L103-L109 | def rebuild_tree(self, request):
'''
Rebuilds the tree and clears the cache.
'''
self.model.objects.rebuild()
self.message_user(request, _('Menu Tree Rebuilt.'))
return self.clean_cache(request) | [
"def",
"rebuild_tree",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"model",
".",
"objects",
".",
"rebuild",
"(",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"'Menu Tree Rebuilt.'",
")",
")",
"return",
"self",
".",
"clean_cach... | Rebuilds the tree and clears the cache. | [
"Rebuilds",
"the",
"tree",
"and",
"clears",
"the",
"cache",
"."
] | python | train | 33.714286 |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_macaroon.py | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L310-L320 | def copy(self):
''' Returns a copy of the macaroon. Note that the the new
macaroon's namespace still points to the same underlying Namespace -
copying the macaroon does not make a copy of the namespace.
:return a Macaroon
'''
m1 = Macaroon(None, None, version=self._versio... | [
"def",
"copy",
"(",
"self",
")",
":",
"m1",
"=",
"Macaroon",
"(",
"None",
",",
"None",
",",
"version",
"=",
"self",
".",
"_version",
",",
"namespace",
"=",
"self",
".",
"_namespace",
")",
"m1",
".",
"_macaroon",
"=",
"self",
".",
"_macaroon",
".",
... | Returns a copy of the macaroon. Note that the the new
macaroon's namespace still points to the same underlying Namespace -
copying the macaroon does not make a copy of the namespace.
:return a Macaroon | [
"Returns",
"a",
"copy",
"of",
"the",
"macaroon",
".",
"Note",
"that",
"the",
"the",
"new",
"macaroon",
"s",
"namespace",
"still",
"points",
"to",
"the",
"same",
"underlying",
"Namespace",
"-",
"copying",
"the",
"macaroon",
"does",
"not",
"make",
"a",
"copy... | python | train | 43.181818 |
juicer/juicer | juicer/utils/__init__.py | https://github.com/juicer/juicer/blob/0c9f0fd59e293d45df6b46e81f675d33221c600d/juicer/utils/__init__.py#L436-L449 | def save_url_as(url, save_as):
"""
Download the file `url` and save it to the local disk as
`save_as`.
"""
remote = requests.get(url, verify=False)
if not remote.status_code == Constants.PULP_GET_OK:
raise JuicerPulpError("A %s error occurred trying to get %s" %
... | [
"def",
"save_url_as",
"(",
"url",
",",
"save_as",
")",
":",
"remote",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"verify",
"=",
"False",
")",
"if",
"not",
"remote",
".",
"status_code",
"==",
"Constants",
".",
"PULP_GET_OK",
":",
"raise",
"JuicerPulpEr... | Download the file `url` and save it to the local disk as
`save_as`. | [
"Download",
"the",
"file",
"url",
"and",
"save",
"it",
"to",
"the",
"local",
"disk",
"as",
"save_as",
"."
] | python | train | 29.928571 |
miguelgrinberg/Flask-Migrate | flask_migrate/__init__.py | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L226-L233 | def edit(directory=None, revision='current'):
"""Edit current revision."""
if alembic_version >= (0, 8, 0):
config = current_app.extensions['migrate'].migrate.get_config(
directory)
command.edit(config, revision)
else:
raise RuntimeError('Alembic 0.8.0 or greater is requi... | [
"def",
"edit",
"(",
"directory",
"=",
"None",
",",
"revision",
"=",
"'current'",
")",
":",
"if",
"alembic_version",
">=",
"(",
"0",
",",
"8",
",",
"0",
")",
":",
"config",
"=",
"current_app",
".",
"extensions",
"[",
"'migrate'",
"]",
".",
"migrate",
... | Edit current revision. | [
"Edit",
"current",
"revision",
"."
] | python | train | 39.75 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QASetting/cache.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/cache.py#L68-L84 | def _create(self, cache_file):
"""Create the tables needed to store the information."""
conn = sqlite3.connect(cache_file)
cur = conn.cursor()
cur.execute("PRAGMA foreign_keys = ON")
cur.execute('''
CREATE TABLE jobs(
hash TEXT NOT NULL UNIQUE PRIMARY ... | [
"def",
"_create",
"(",
"self",
",",
"cache_file",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"cache_file",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"\"PRAGMA foreign_keys = ON\"",
")",
"cur",
".",
"execute... | Create the tables needed to store the information. | [
"Create",
"the",
"tables",
"needed",
"to",
"store",
"the",
"information",
"."
] | python | train | 38 |
Stranger6667/pyoffers | pyoffers/utils.py | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/utils.py#L49-L65 | def prepend_model(self, value, model):
"""
Prepends model name if it is not already prepended.
For example model is "Offer":
key -> Offer.key
-key -> -Offer.key
Offer.key -> Offer.key
-Offer.key -> -Offer.key
"""
if '.' not in valu... | [
"def",
"prepend_model",
"(",
"self",
",",
"value",
",",
"model",
")",
":",
"if",
"'.'",
"not",
"in",
"value",
":",
"direction",
"=",
"''",
"if",
"value",
".",
"startswith",
"(",
"'-'",
")",
":",
"value",
"=",
"value",
"[",
"1",
":",
"]",
"direction... | Prepends model name if it is not already prepended.
For example model is "Offer":
key -> Offer.key
-key -> -Offer.key
Offer.key -> Offer.key
-Offer.key -> -Offer.key | [
"Prepends",
"model",
"name",
"if",
"it",
"is",
"not",
"already",
"prepended",
".",
"For",
"example",
"model",
"is",
"Offer",
":"
] | python | train | 30.352941 |
tanghaibao/jcvi | jcvi/assembly/hic.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L1130-L1146 | def separate_tour_and_o(row):
"""
The tour line typically contains contig list like:
tig00044568+ tig00045748- tig00071055- tig00015093- tig00030900-
This function separates the names from the orientations.
"""
tour = []
tour_o = []
for contig in row.split():
if contig[-1] in ('... | [
"def",
"separate_tour_and_o",
"(",
"row",
")",
":",
"tour",
"=",
"[",
"]",
"tour_o",
"=",
"[",
"]",
"for",
"contig",
"in",
"row",
".",
"split",
"(",
")",
":",
"if",
"contig",
"[",
"-",
"1",
"]",
"in",
"(",
"'+'",
",",
"'-'",
",",
"'?'",
")",
... | The tour line typically contains contig list like:
tig00044568+ tig00045748- tig00071055- tig00015093- tig00030900-
This function separates the names from the orientations. | [
"The",
"tour",
"line",
"typically",
"contains",
"contig",
"list",
"like",
":",
"tig00044568",
"+",
"tig00045748",
"-",
"tig00071055",
"-",
"tig00015093",
"-",
"tig00030900",
"-"
] | python | train | 29.882353 |
DataBiosphere/toil | src/toil/realtimeLogger.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/realtimeLogger.py#L183-L214 | def getLogger(cls):
"""
Get the logger that logs real-time to the leader.
Note that if the returned logger is used on the leader, you will see the message twice,
since it still goes to the normal log handlers, too.
"""
# Only do the setup once, so we don't add a ... | [
"def",
"getLogger",
"(",
"cls",
")",
":",
"# Only do the setup once, so we don't add a handler every time we log. Use a lock to do",
"# so safely even if we're being called in different threads. Use double-checked locking",
"# to reduce the overhead introduced by the lock.",
"if",
"cls",
".",
... | Get the logger that logs real-time to the leader.
Note that if the returned logger is used on the leader, you will see the message twice,
since it still goes to the normal log handlers, too. | [
"Get",
"the",
"logger",
"that",
"logs",
"real",
"-",
"time",
"to",
"the",
"leader",
".",
"Note",
"that",
"if",
"the",
"returned",
"logger",
"is",
"used",
"on",
"the",
"leader",
"you",
"will",
"see",
"the",
"message",
"twice",
"since",
"it",
"still",
"g... | python | train | 50.34375 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L181-L196 | def _read(self):
""" Read a USB HID feature report from the YubiKey. """
request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_IN
value = _REPORT_TYPE_FEATURE << 8 # apparently required for YubiKey 1.3.2, but not 2.2.x
recv = self._usb_handle.controlMsg(request_type,
... | [
"def",
"_read",
"(",
"self",
")",
":",
"request_type",
"=",
"_USB_TYPE_CLASS",
"|",
"_USB_RECIP_INTERFACE",
"|",
"_USB_ENDPOINT_IN",
"value",
"=",
"_REPORT_TYPE_FEATURE",
"<<",
"8",
"# apparently required for YubiKey 1.3.2, but not 2.2.x",
"recv",
"=",
"self",
".",
"_us... | Read a USB HID feature report from the YubiKey. | [
"Read",
"a",
"USB",
"HID",
"feature",
"report",
"from",
"the",
"YubiKey",
"."
] | python | train | 60.375 |
glitchassassin/lackey | lackey/RegionMatching.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1083-L1090 | def setRaster(self, rows, columns):
""" Sets the raster for the region, allowing sections to be indexed by row/column """
rows = int(rows)
columns = int(columns)
if rows <= 0 or columns <= 0:
return self
self._raster = (rows, columns)
return self.getCell(0, 0) | [
"def",
"setRaster",
"(",
"self",
",",
"rows",
",",
"columns",
")",
":",
"rows",
"=",
"int",
"(",
"rows",
")",
"columns",
"=",
"int",
"(",
"columns",
")",
"if",
"rows",
"<=",
"0",
"or",
"columns",
"<=",
"0",
":",
"return",
"self",
"self",
".",
"_r... | Sets the raster for the region, allowing sections to be indexed by row/column | [
"Sets",
"the",
"raster",
"for",
"the",
"region",
"allowing",
"sections",
"to",
"be",
"indexed",
"by",
"row",
"/",
"column"
] | python | train | 39.125 |
log2timeline/dfdatetime | dfdatetime/interface.py | https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L704-L723 | def _GetNumberOfDaysInCentury(self, year):
"""Retrieves the number of days in a century.
Args:
year (int): year in the century e.g. 1970.
Returns:
int: number of (remaining) days in the century.
Raises:
ValueError: if the year value is out of bounds.
"""
if year < 0:
r... | [
"def",
"_GetNumberOfDaysInCentury",
"(",
"self",
",",
"year",
")",
":",
"if",
"year",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Year value out of bounds.'",
")",
"year",
",",
"_",
"=",
"divmod",
"(",
"year",
",",
"100",
")",
"if",
"self",
".",
"_IsLea... | Retrieves the number of days in a century.
Args:
year (int): year in the century e.g. 1970.
Returns:
int: number of (remaining) days in the century.
Raises:
ValueError: if the year value is out of bounds. | [
"Retrieves",
"the",
"number",
"of",
"days",
"in",
"a",
"century",
"."
] | python | train | 22.3 |
yakupadakli/python-unsplash | unsplash/collection.py | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L195-L210 | def remove_photo(self, collection_id, photo_id):
"""
Remove a photo from one of the logged-in user’s collections.
Requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param photo_id [string]: The photo’s ID. Required.
:re... | [
"def",
"remove_photo",
"(",
"self",
",",
"collection_id",
",",
"photo_id",
")",
":",
"url",
"=",
"\"/collections/%s/remove\"",
"%",
"collection_id",
"data",
"=",
"{",
"\"collection_id\"",
":",
"collection_id",
",",
"\"photo_id\"",
":",
"photo_id",
"}",
"result",
... | Remove a photo from one of the logged-in user’s collections.
Requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param photo_id [string]: The photo’s ID. Required.
:return: [Tuple]: The Unsplash Collection and Photo | [
"Remove",
"a",
"photo",
"from",
"one",
"of",
"the",
"logged",
"-",
"in",
"user’s",
"collections",
".",
"Requires",
"the",
"write_collections",
"scope",
"."
] | python | train | 42.375 |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L11150-L11165 | def get_screen_settings(self, screen_id):
"""Returns the recording settings for a particular screen.
in screen_id of type int
Screen ID to retrieve recording screen settings for.
return record_screen_settings of type :class:`IRecordingScreenSettings`
Recording screen se... | [
"def",
"get_screen_settings",
"(",
"self",
",",
"screen_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"screen_id",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"screen_id can only be an instance of type baseinteger\"",
")",
"record_screen_settings",
"=",
... | Returns the recording settings for a particular screen.
in screen_id of type int
Screen ID to retrieve recording screen settings for.
return record_screen_settings of type :class:`IRecordingScreenSettings`
Recording screen settings for the requested screen. | [
"Returns",
"the",
"recording",
"settings",
"for",
"a",
"particular",
"screen",
"."
] | python | train | 44.375 |
cdeboever3/cdpybio | cdpybio/star.py | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L137-L200 | def _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff=20):
"""Filter junctions from many sj_out files and make panel.
Parameters
----------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
total_jxn_cov_cutoff : int
If the unique read coverage of a ju... | [
"def",
"_make_sj_out_panel",
"(",
"sj_outD",
",",
"total_jxn_cov_cutoff",
"=",
"20",
")",
":",
"# num_jxns = dict()",
"# # set of all junctions",
"# jxnS = reduce(lambda x,y: set(x) | set(y),",
"# [ sj_outD[k].index for k in sj_outD.keys() ])",
"# jxn_keepS = set()",
"# j... | Filter junctions from many sj_out files and make panel.
Parameters
----------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
total_jxn_cov_cutoff : int
If the unique read coverage of a junction summed over all samples is not
greater than or equ... | [
"Filter",
"junctions",
"from",
"many",
"sj_out",
"files",
"and",
"make",
"panel",
"."
] | python | train | 37.828125 |
AustralianSynchrotron/lightflow | lightflow/workers.py | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/workers.py#L60-L93 | def list_workers(config, *, filter_by_queues=None):
""" Return a list of all available workers.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
filter_by_queues (list): Restrict the returned workers to workers that listen to
... | [
"def",
"list_workers",
"(",
"config",
",",
"*",
",",
"filter_by_queues",
"=",
"None",
")",
":",
"celery_app",
"=",
"create_app",
"(",
"config",
")",
"worker_stats",
"=",
"celery_app",
".",
"control",
".",
"inspect",
"(",
")",
".",
"stats",
"(",
")",
"que... | Return a list of all available workers.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
filter_by_queues (list): Restrict the returned workers to workers that listen to
at least one of the queue names in this list.
Ret... | [
"Return",
"a",
"list",
"of",
"all",
"available",
"workers",
"."
] | python | train | 32.176471 |
awslabs/sockeye | sockeye/transformer.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/transformer.py#L322-L336 | def get_autoregressive_bias(max_length: int, dtype: str = C.DTYPE_FP32) -> mx.sym.Symbol:
"""
Returns bias/mask to ensure position i can only attend to positions <i.
:param max_length: Sequence length.
:param dtype: dtype of bias
:return: Bias symbol of shape (1, max_length, max_length).
"""
... | [
"def",
"get_autoregressive_bias",
"(",
"max_length",
":",
"int",
",",
"dtype",
":",
"str",
"=",
"C",
".",
"DTYPE_FP32",
")",
"->",
"mx",
".",
"sym",
".",
"Symbol",
":",
"length_array",
"=",
"mx",
".",
"sym",
".",
"arange",
"(",
"max_length",
",",
"dtyp... | Returns bias/mask to ensure position i can only attend to positions <i.
:param max_length: Sequence length.
:param dtype: dtype of bias
:return: Bias symbol of shape (1, max_length, max_length). | [
"Returns",
"bias",
"/",
"mask",
"to",
"ensure",
"position",
"i",
"can",
"only",
"attend",
"to",
"positions",
"<i",
"."
] | python | train | 50 |
gboeing/osmnx | osmnx/core.py | https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/core.py#L1681-L1794 | def graph_from_polygon(polygon, network_type='all_private', simplify=True,
retain_all=False, truncate_by_edge=False, name='unnamed',
timeout=180, memory=None,
max_query_area_size=50*1000*50*1000,
clean_periphery=True, infrastruc... | [
"def",
"graph_from_polygon",
"(",
"polygon",
",",
"network_type",
"=",
"'all_private'",
",",
"simplify",
"=",
"True",
",",
"retain_all",
"=",
"False",
",",
"truncate_by_edge",
"=",
"False",
",",
"name",
"=",
"'unnamed'",
",",
"timeout",
"=",
"180",
",",
"mem... | Create a networkx graph from OSM data within the spatial boundaries of the
passed-in shapely polygon.
Parameters
----------
polygon : shapely Polygon or MultiPolygon
the shape to get network data within. coordinates should be in units of
latitude-longitude degrees.
network_type : st... | [
"Create",
"a",
"networkx",
"graph",
"from",
"OSM",
"data",
"within",
"the",
"spatial",
"boundaries",
"of",
"the",
"passed",
"-",
"in",
"shapely",
"polygon",
"."
] | python | train | 51.201754 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L858-L878 | def __interpret_slices(self, slices):
"""
Convert python slice objects into a more useful and computable form:
- requested_bbox: A bounding box representing the volume requested
- steps: the requested stride over x,y,z
- channel_slice: A python slice object over the channel dimension
Returned ... | [
"def",
"__interpret_slices",
"(",
"self",
",",
"slices",
")",
":",
"maxsize",
"=",
"list",
"(",
"self",
".",
"bounds",
".",
"maxpt",
")",
"+",
"[",
"self",
".",
"num_channels",
"]",
"minsize",
"=",
"list",
"(",
"self",
".",
"bounds",
".",
"minpt",
")... | Convert python slice objects into a more useful and computable form:
- requested_bbox: A bounding box representing the volume requested
- steps: the requested stride over x,y,z
- channel_slice: A python slice object over the channel dimension
Returned as a tuple: (requested_bbox, steps, channel_slice) | [
"Convert",
"python",
"slice",
"objects",
"into",
"a",
"more",
"useful",
"and",
"computable",
"form",
":"
] | python | train | 37.142857 |
wummel/linkchecker | linkcheck/checker/urlbase.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/urlbase.py#L737-L802 | def to_wire_dict (self):
"""Return a simplified transport object for logging and caching.
The transport object must contain these attributes:
- url_data.valid: bool
Indicates if URL is valid
- url_data.result: unicode
Result string
- url_data.warnings: list o... | [
"def",
"to_wire_dict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"valid",
"=",
"self",
".",
"valid",
",",
"extern",
"=",
"self",
".",
"extern",
"[",
"0",
"]",
",",
"result",
"=",
"self",
".",
"result",
",",
"warnings",
"=",
"self",
".",
"warnin... | Return a simplified transport object for logging and caching.
The transport object must contain these attributes:
- url_data.valid: bool
Indicates if URL is valid
- url_data.result: unicode
Result string
- url_data.warnings: list of tuples (tag, warning message)
... | [
"Return",
"a",
"simplified",
"transport",
"object",
"for",
"logging",
"and",
"caching",
"."
] | python | train | 38.075758 |
spyder-ide/spyder | spyder/plugins/help/utils/sphinxify.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L94-L146 | def generate_context(name='', argspec='', note='', math=False, collapse=False,
img_path='', css_path=CSS_PATH):
"""
Generate the html_context dictionary for our Sphinx conf file.
This is a set of variables to be passed to the Jinja template engine and
that are used to control h... | [
"def",
"generate_context",
"(",
"name",
"=",
"''",
",",
"argspec",
"=",
"''",
",",
"note",
"=",
"''",
",",
"math",
"=",
"False",
",",
"collapse",
"=",
"False",
",",
"img_path",
"=",
"''",
",",
"css_path",
"=",
"CSS_PATH",
")",
":",
"if",
"img_path",
... | Generate the html_context dictionary for our Sphinx conf file.
This is a set of variables to be passed to the Jinja template engine and
that are used to control how the webpage is rendered in connection with
Sphinx
Parameters
----------
name : str
Object's name.
note : str
... | [
"Generate",
"the",
"html_context",
"dictionary",
"for",
"our",
"Sphinx",
"conf",
"file",
".",
"This",
"is",
"a",
"set",
"of",
"variables",
"to",
"be",
"passed",
"to",
"the",
"Jinja",
"template",
"engine",
"and",
"that",
"are",
"used",
"to",
"control",
"how... | python | train | 28.679245 |
twisted/axiom | axiom/listversions.py | https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/listversions.py#L78-L83 | def asVersion(self):
"""
Convert the version data in this item to a
L{twisted.python.versions.Version}.
"""
return versions.Version(self.package, self.major, self.minor, self.micro) | [
"def",
"asVersion",
"(",
"self",
")",
":",
"return",
"versions",
".",
"Version",
"(",
"self",
".",
"package",
",",
"self",
".",
"major",
",",
"self",
".",
"minor",
",",
"self",
".",
"micro",
")"
] | Convert the version data in this item to a
L{twisted.python.versions.Version}. | [
"Convert",
"the",
"version",
"data",
"in",
"this",
"item",
"to",
"a",
"L",
"{",
"twisted",
".",
"python",
".",
"versions",
".",
"Version",
"}",
"."
] | python | train | 36 |
gtaylor/python-route53 | route53/connection.py | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L34-L51 | def _send_request(self, path, data, method):
"""
Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:... | [
"def",
"_send_request",
"(",
"self",
",",
"path",
",",
"data",
",",
"method",
")",
":",
"response_body",
"=",
"self",
".",
"_transport",
".",
"send_request",
"(",
"path",
",",
"data",
",",
"method",
")",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"r... | Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:`endpoint`.
:param data: The params to send along with th... | [
"Uses",
"the",
"HTTP",
"transport",
"to",
"query",
"the",
"Route53",
"API",
".",
"Runs",
"the",
"response",
"through",
"lxml",
"s",
"parser",
"before",
"we",
"hand",
"it",
"off",
"for",
"further",
"picking",
"apart",
"by",
"our",
"call",
"-",
"specific",
... | python | test | 43.444444 |
geronimp/graftM | graftm/sequence_searcher.py | https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/sequence_searcher.py#L823-L960 | def search_and_extract_orfs_matching_protein_database(self,
unpack,
search_method,
maximum_range,
thread... | [
"def",
"search_and_extract_orfs_matching_protein_database",
"(",
"self",
",",
"unpack",
",",
"search_method",
",",
"maximum_range",
",",
"threads",
",",
"evalue",
",",
"min_orf_length",
",",
"restrict_read_length",
",",
"diamond_database",
",",
"output_search_file",
",",
... | As per aa_db_search() except slightly lower level. Search an
input read set (unpack) and then extract the proteins that hit together
with their containing nucleotide sequences.
Parameters
----------
output_search_file: str
path to hmmsearch output table or diamond ba... | [
"As",
"per",
"aa_db_search",
"()",
"except",
"slightly",
"lower",
"level",
".",
"Search",
"an",
"input",
"read",
"set",
"(",
"unpack",
")",
"and",
"then",
"extract",
"the",
"proteins",
"that",
"hit",
"together",
"with",
"their",
"containing",
"nucleotide",
"... | python | train | 45.173913 |
lago-project/lago | lago/sdk.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/sdk.py#L14-L35 | def add_stream_logger(level=logging.DEBUG, name=None):
"""
Add a stream logger. This can be used for printing all SDK calls to stdout
while working in an interactive session. Note this is a logger for the
entire module, which will apply to all environments started in the same
session. If you need a ... | [
"def",
"add_stream_logger",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"name",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"setLevel",
"(",
"level",
")",
"handler",
"=",
"logging",
".",
"Str... | Add a stream logger. This can be used for printing all SDK calls to stdout
while working in an interactive session. Note this is a logger for the
entire module, which will apply to all environments started in the same
session. If you need a specific logger pass a ``logfile`` to
:func:`~sdk.init`
Ar... | [
"Add",
"a",
"stream",
"logger",
".",
"This",
"can",
"be",
"used",
"for",
"printing",
"all",
"SDK",
"calls",
"to",
"stdout",
"while",
"working",
"in",
"an",
"interactive",
"session",
".",
"Note",
"this",
"is",
"a",
"logger",
"for",
"the",
"entire",
"modul... | python | train | 33.181818 |
OrangeTux/einder | einder/client.py | https://github.com/OrangeTux/einder/blob/deb2c5f79a69b684257fe939659c3bd751556fd5/einder/client.py#L38-L78 | def authorize(self):
""" Use the magic of a unicorn and summon the set-top box to listen
to us.
/
,.. /
,' ';
,,.__ _,' /'; .
:',' ~~~~ '. '~
:' ( ) )::,
'. '. .=----=..-~ .;'... | [
"def",
"authorize",
"(",
"self",
")",
":",
"# Read the version of the set-top box and write it back. Why? I've no",
"# idea.",
"version",
"=",
"self",
".",
"con",
".",
"makefile",
"(",
")",
".",
"readline",
"(",
")",
"self",
".",
"con",
".",
"send",
"(",
"versio... | Use the magic of a unicorn and summon the set-top box to listen
to us.
/
,.. /
,' ';
,,.__ _,' /'; .
:',' ~~~~ '. '~
:' ( ) )::,
'. '. .=----=..-~ .;'
' ;' :: ':. '"
... | [
"Use",
"the",
"magic",
"of",
"a",
"unicorn",
"and",
"summon",
"the",
"set",
"-",
"top",
"box",
"to",
"listen",
"to",
"us",
"."
] | python | train | 33.536585 |
Crunch-io/crunch-cube | src/cr/cube/util.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/util.py#L39-L46 | def intersperse_hs_in_std_res(slice_, hs_dims, res):
"""Perform the insertions of place-holding rows and cols for insertions."""
for dim, inds in enumerate(slice_.inserted_hs_indices()):
if dim not in hs_dims:
continue
for i in inds:
res = np.insert(res, i, np.nan, axis=(... | [
"def",
"intersperse_hs_in_std_res",
"(",
"slice_",
",",
"hs_dims",
",",
"res",
")",
":",
"for",
"dim",
",",
"inds",
"in",
"enumerate",
"(",
"slice_",
".",
"inserted_hs_indices",
"(",
")",
")",
":",
"if",
"dim",
"not",
"in",
"hs_dims",
":",
"continue",
"f... | Perform the insertions of place-holding rows and cols for insertions. | [
"Perform",
"the",
"insertions",
"of",
"place",
"-",
"holding",
"rows",
"and",
"cols",
"for",
"insertions",
"."
] | python | train | 43.375 |
fedora-infra/fedmsg | fedmsg/crypto/__init__.py | https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/crypto/__init__.py#L166-L192 | def init(**config):
""" Initialize the crypto backend.
The backend can be one of two plugins:
- 'x509' - Uses x509 certificates.
- 'gpg' - Uses GnuPG keys.
"""
global _implementation
global _validate_implementations
if config.get('crypto_backend') == 'gpg':
_implementa... | [
"def",
"init",
"(",
"*",
"*",
"config",
")",
":",
"global",
"_implementation",
"global",
"_validate_implementations",
"if",
"config",
".",
"get",
"(",
"'crypto_backend'",
")",
"==",
"'gpg'",
":",
"_implementation",
"=",
"gpg",
"else",
":",
"_implementation",
"... | Initialize the crypto backend.
The backend can be one of two plugins:
- 'x509' - Uses x509 certificates.
- 'gpg' - Uses GnuPG keys. | [
"Initialize",
"the",
"crypto",
"backend",
"."
] | python | train | 28.740741 |
wummel/linkchecker | third_party/dnspython/dns/resolver.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/resolver.py#L462-L470 | def _config_win32_nameservers(self, nameservers):
"""Configure a NameServer registry entry."""
# we call str() on nameservers to convert it from unicode to ascii
nameservers = str(nameservers)
split_char = self._determine_split_char(nameservers)
ns_list = nameservers.split(split_... | [
"def",
"_config_win32_nameservers",
"(",
"self",
",",
"nameservers",
")",
":",
"# we call str() on nameservers to convert it from unicode to ascii",
"nameservers",
"=",
"str",
"(",
"nameservers",
")",
"split_char",
"=",
"self",
".",
"_determine_split_char",
"(",
"nameserver... | Configure a NameServer registry entry. | [
"Configure",
"a",
"NameServer",
"registry",
"entry",
"."
] | python | train | 47.888889 |
saltstack/salt | salt/modules/btrfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L627-L675 | def properties(obj, type=None, set=None):
'''
List properties for given btrfs object. The object can be path of BTRFS device,
mount point, or any directories/files inside the BTRFS filesystem.
General options:
* **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice].
* **for... | [
"def",
"properties",
"(",
"obj",
",",
"type",
"=",
"None",
",",
"set",
"=",
"None",
")",
":",
"if",
"type",
"and",
"type",
"not",
"in",
"[",
"'s'",
",",
"'subvol'",
",",
"'f'",
",",
"'filesystem'",
",",
"'i'",
",",
"'inode'",
",",
"'d'",
",",
"'d... | List properties for given btrfs object. The object can be path of BTRFS device,
mount point, or any directories/files inside the BTRFS filesystem.
General options:
* **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice].
* **force**: Force overwrite existing filesystem on the disk
... | [
"List",
"properties",
"for",
"given",
"btrfs",
"object",
".",
"The",
"object",
"can",
"be",
"path",
"of",
"BTRFS",
"device",
"mount",
"point",
"or",
"any",
"directories",
"/",
"files",
"inside",
"the",
"BTRFS",
"filesystem",
"."
] | python | train | 34.77551 |
sorgerlab/indra | indra/assemblers/pybel/assembler.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pybel/assembler.py#L463-L518 | def _get_agent_grounding(agent):
"""Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later)."""
def _get_id(_agent, key):
_id = _agent.db_refs.get(key)
if isinstance(_id, list):
_id = _id[0]
return _id
hgnc_id = _get_id(agent, 'HGNC')
... | [
"def",
"_get_agent_grounding",
"(",
"agent",
")",
":",
"def",
"_get_id",
"(",
"_agent",
",",
"key",
")",
":",
"_id",
"=",
"_agent",
".",
"db_refs",
".",
"get",
"(",
"key",
")",
"if",
"isinstance",
"(",
"_id",
",",
"list",
")",
":",
"_id",
"=",
"_id... | Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later). | [
"Convert",
"an",
"agent",
"to",
"the",
"corresponding",
"PyBEL",
"DSL",
"object",
"(",
"to",
"be",
"filled",
"with",
"variants",
"later",
")",
"."
] | python | train | 26.607143 |
bwohlberg/sporco | sporco/cnvrep.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/cnvrep.py#L987-L1013 | def _Pcn_crp(x, dsz, Nv, dimN=2, dimC=1):
"""
Projection onto dictionary update constraint set: support
projection and normalisation. The result is cropped to the
support of the largest filter in the dictionary.
Parameters
----------
x : array_like
Input array
dsz : tuple
... | [
"def",
"_Pcn_crp",
"(",
"x",
",",
"dsz",
",",
"Nv",
",",
"dimN",
"=",
"2",
",",
"dimC",
"=",
"1",
")",
":",
"return",
"normalise",
"(",
"bcrop",
"(",
"x",
",",
"dsz",
",",
"dimN",
")",
",",
"dimN",
"+",
"dimC",
")"
] | Projection onto dictionary update constraint set: support
projection and normalisation. The result is cropped to the
support of the largest filter in the dictionary.
Parameters
----------
x : array_like
Input array
dsz : tuple
Filter support size(s), specified using the same forma... | [
"Projection",
"onto",
"dictionary",
"update",
"constraint",
"set",
":",
"support",
"projection",
"and",
"normalisation",
".",
"The",
"result",
"is",
"cropped",
"to",
"the",
"support",
"of",
"the",
"largest",
"filter",
"in",
"the",
"dictionary",
"."
] | python | train | 27.925926 |
boppreh/keyboard | keyboard/__init__.py | https://github.com/boppreh/keyboard/blob/dbb73dfff484f733d5fed8dbc53301af5b6c7f50/keyboard/__init__.py#L1029-L1041 | def record(until='escape', suppress=False, trigger_on_release=False):
"""
Records all keyboard events from all keyboards until the user presses the
given hotkey. Then returns the list of events recorded, of type
`keyboard.KeyboardEvent`. Pairs well with
`play(events)`.
Note: this is a blocking ... | [
"def",
"record",
"(",
"until",
"=",
"'escape'",
",",
"suppress",
"=",
"False",
",",
"trigger_on_release",
"=",
"False",
")",
":",
"start_recording",
"(",
")",
"wait",
"(",
"until",
",",
"suppress",
"=",
"suppress",
",",
"trigger_on_release",
"=",
"trigger_on... | Records all keyboard events from all keyboards until the user presses the
given hotkey. Then returns the list of events recorded, of type
`keyboard.KeyboardEvent`. Pairs well with
`play(events)`.
Note: this is a blocking function.
Note: for more details on the keyboard hook and events see `hook`. | [
"Records",
"all",
"keyboard",
"events",
"from",
"all",
"keyboards",
"until",
"the",
"user",
"presses",
"the",
"given",
"hotkey",
".",
"Then",
"returns",
"the",
"list",
"of",
"events",
"recorded",
"of",
"type",
"keyboard",
".",
"KeyboardEvent",
".",
"Pairs",
... | python | train | 40 |
mithro/python-datetime-tz | datetime_tz/__init__.py | https://github.com/mithro/python-datetime-tz/blob/3c682d003f8b28e39f0c096773e471aeb68e6bbb/datetime_tz/__init__.py#L799-L810 | def days(start, end=None):
"""Iterate over the days between the given datetime_tzs.
Args:
start: datetime_tz to start from.
end: (Optional) Date to end at, if not given the iterator will never
terminate.
Returns:
An iterator which generates datetime_tz objects a day apart.
... | [
"def",
"days",
"(",
"start",
",",
"end",
"=",
"None",
")",
":",
"return",
"iterate",
".",
"between",
"(",
"start",
",",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"1",
")",
",",
"end",
")"
] | Iterate over the days between the given datetime_tzs.
Args:
start: datetime_tz to start from.
end: (Optional) Date to end at, if not given the iterator will never
terminate.
Returns:
An iterator which generates datetime_tz objects a day apart. | [
"Iterate",
"over",
"the",
"days",
"between",
"the",
"given",
"datetime_tzs",
"."
] | python | train | 31.666667 |
toumorokoshi/sprinter | sprinter/environment.py | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L210-L226 | def deactivate(self):
""" deactivate the environment """
try:
self.phase = PHASE.DEACTIVATE
self.logger.info("Deactivating environment %s..." % self.namespace)
self.directory.rewrite_config = False
self.instantiate_features()
self._specialize()... | [
"def",
"deactivate",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"phase",
"=",
"PHASE",
".",
"DEACTIVATE",
"self",
".",
"logger",
".",
"info",
"(",
"\"Deactivating environment %s...\"",
"%",
"self",
".",
"namespace",
")",
"self",
".",
"directory",
".",... | deactivate the environment | [
"deactivate",
"the",
"environment"
] | python | train | 40.823529 |
caseyjlaw/rtpipe | rtpipe/parsesdm.py | https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/parsesdm.py#L598-L607 | def getsdm(*args, **kwargs):
""" Wrap sdmpy.SDM to get around schema change error """
try:
sdm = sdmpy.SDM(*args, **kwargs)
except XMLSyntaxError:
kwargs['use_xsd'] = False
sdm = sdmpy.SDM(*args, **kwargs)
return sdm | [
"def",
"getsdm",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"sdm",
"=",
"sdmpy",
".",
"SDM",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"XMLSyntaxError",
":",
"kwargs",
"[",
"'use_xsd'",
"]",
"=",
"False",
"sd... | Wrap sdmpy.SDM to get around schema change error | [
"Wrap",
"sdmpy",
".",
"SDM",
"to",
"get",
"around",
"schema",
"change",
"error"
] | python | train | 24.9 |
HarveyHunt/i3situation | i3situation/core/config.py | https://github.com/HarveyHunt/i3situation/blob/3160a21006fcc6961f240988874e228a5ec6f18e/i3situation/core/config.py#L50-L68 | def reload(self):
"""
Reload the configuration from the file. This is in its own function
so that it can be called at any time by another class.
"""
self._conf = configparser.ConfigParser()
# Preserve the case of sections and keys.
self._conf.optionxform = str
... | [
"def",
"reload",
"(",
"self",
")",
":",
"self",
".",
"_conf",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"# Preserve the case of sections and keys.",
"self",
".",
"_conf",
".",
"optionxform",
"=",
"str",
"self",
".",
"_conf",
".",
"read",
"(",
"self... | Reload the configuration from the file. This is in its own function
so that it can be called at any time by another class. | [
"Reload",
"the",
"configuration",
"from",
"the",
"file",
".",
"This",
"is",
"in",
"its",
"own",
"function",
"so",
"that",
"it",
"can",
"be",
"called",
"at",
"any",
"time",
"by",
"another",
"class",
"."
] | python | train | 45.315789 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavutil.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavutil.py#L394-L400 | def param_fetch_one(self, name):
'''initiate fetch of one parameter'''
try:
idx = int(name)
self.mav.param_request_read_send(self.target_system, self.target_component, "", idx)
except Exception:
self.mav.param_request_read_send(self.target_system, self.target_... | [
"def",
"param_fetch_one",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"idx",
"=",
"int",
"(",
"name",
")",
"self",
".",
"mav",
".",
"param_request_read_send",
"(",
"self",
".",
"target_system",
",",
"self",
".",
"target_component",
",",
"\"\"",
",",
... | initiate fetch of one parameter | [
"initiate",
"fetch",
"of",
"one",
"parameter"
] | python | train | 47.714286 |
sernst/cauldron | cauldron/runner/python_file.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/python_file.py#L45-L72 | def get_file_contents(source_path: str) -> str:
"""
Loads the contents of the source into a string for execution using multiple
loading methods to handle cross-platform encoding edge cases. If none of
the load methods work, a string is returned that contains an error function
response that will be d... | [
"def",
"get_file_contents",
"(",
"source_path",
":",
"str",
")",
"->",
"str",
":",
"open_funcs",
"=",
"[",
"functools",
".",
"partial",
"(",
"codecs",
".",
"open",
",",
"source_path",
",",
"encoding",
"=",
"'utf-8'",
")",
",",
"functools",
".",
"partial",
... | Loads the contents of the source into a string for execution using multiple
loading methods to handle cross-platform encoding edge cases. If none of
the load methods work, a string is returned that contains an error function
response that will be displayed when the step is run alert the user to the
erro... | [
"Loads",
"the",
"contents",
"of",
"the",
"source",
"into",
"a",
"string",
"for",
"execution",
"using",
"multiple",
"loading",
"methods",
"to",
"handle",
"cross",
"-",
"platform",
"encoding",
"edge",
"cases",
".",
"If",
"none",
"of",
"the",
"load",
"methods",... | python | train | 29.964286 |
blockstack/blockstack-core | blockstack/lib/nameset/db.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L1742-L1756 | def namedb_get_account_tokens(cur, address):
"""
Get an account's tokens
Returns the list of tokens on success
Returns None if not found
"""
sql = 'SELECT DISTINCT type FROM accounts WHERE address = ?;'
args = (address,)
rows = namedb_query_execute(cur, sql, args)
ret = []
for r... | [
"def",
"namedb_get_account_tokens",
"(",
"cur",
",",
"address",
")",
":",
"sql",
"=",
"'SELECT DISTINCT type FROM accounts WHERE address = ?;'",
"args",
"=",
"(",
"address",
",",
")",
"rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
... | Get an account's tokens
Returns the list of tokens on success
Returns None if not found | [
"Get",
"an",
"account",
"s",
"tokens",
"Returns",
"the",
"list",
"of",
"tokens",
"on",
"success",
"Returns",
"None",
"if",
"not",
"found"
] | python | train | 24.333333 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/__init__.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/__init__.py#L270-L286 | def _backtrace(elt, dom):
'''Return a "backtrace" from the given element to the DOM root,
in XPath syntax.
'''
s = ''
while elt != dom:
name, parent = elt.nodeName, elt.parentNode
if parent is None: break
matches = [ c for c in _child_elements(parent)
... | [
"def",
"_backtrace",
"(",
"elt",
",",
"dom",
")",
":",
"s",
"=",
"''",
"while",
"elt",
"!=",
"dom",
":",
"name",
",",
"parent",
"=",
"elt",
".",
"nodeName",
",",
"elt",
".",
"parentNode",
"if",
"parent",
"is",
"None",
":",
"break",
"matches",
"=",
... | Return a "backtrace" from the given element to the DOM root,
in XPath syntax. | [
"Return",
"a",
"backtrace",
"from",
"the",
"given",
"element",
"to",
"the",
"DOM",
"root",
"in",
"XPath",
"syntax",
"."
] | python | train | 30.588235 |
Turbo87/aerofiles | aerofiles/igc/writer.py | https://github.com/Turbo87/aerofiles/blob/d8b7b04a1fcea5c98f89500de1164619a4ec7ef4/aerofiles/igc/writer.py#L808-L862 | def write_k_record(self, *args):
"""
Write a K record::
writer.write_k_record_extensions([
('FXA', 3), ('SIU', 2), ('ENL', 3),
])
writer.write_k_record(datetime.time(2, 3, 4), ['023', 13, 2])
# -> J030810FXA1112SIU1315ENL
# -... | [
"def",
"write_k_record",
"(",
"self",
",",
"*",
"args",
")",
":",
"num_args",
"=",
"len",
"(",
"args",
")",
"if",
"num_args",
"not",
"in",
"(",
"1",
",",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid number of parameters received'",
")",
"if",
"nu... | Write a K record::
writer.write_k_record_extensions([
('FXA', 3), ('SIU', 2), ('ENL', 3),
])
writer.write_k_record(datetime.time(2, 3, 4), ['023', 13, 2])
# -> J030810FXA1112SIU1315ENL
# -> K02030402313002
:param time: UTC time of t... | [
"Write",
"a",
"K",
"record",
"::"
] | python | train | 30.563636 |
calmjs/calmjs | src/calmjs/indexer.py | https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/indexer.py#L284-L301 | def mapper(module, entry_point,
modpath='pkg_resources', globber='root', modname='es6',
fext=JS_EXT, registry=_utils):
"""
General mapper
Loads components from the micro registry.
"""
modname_f = modname if callable(modname) else _utils['modname'][modname]
return {
... | [
"def",
"mapper",
"(",
"module",
",",
"entry_point",
",",
"modpath",
"=",
"'pkg_resources'",
",",
"globber",
"=",
"'root'",
",",
"modname",
"=",
"'es6'",
",",
"fext",
"=",
"JS_EXT",
",",
"registry",
"=",
"_utils",
")",
":",
"modname_f",
"=",
"modname",
"i... | General mapper
Loads components from the micro registry. | [
"General",
"mapper"
] | python | train | 30.444444 |
payplug/payplug-python | payplug/__init__.py | https://github.com/payplug/payplug-python/blob/42dec9d6bff420dd0c26e51a84dd000adff04331/payplug/__init__.py#L12-L29 | def set_secret_key(token):
"""
Initializes a Authentication and sets it as the new default global authentication.
It also performs some checks before saving the authentication.
:Example
>>> # Expected format for secret key:
>>> import payplug
>>> payplug.set_secret_key('sk_test_somerandomc... | [
"def",
"set_secret_key",
"(",
"token",
")",
":",
"if",
"not",
"isinstance",
"(",
"token",
",",
"string_types",
")",
":",
"raise",
"exceptions",
".",
"ConfigurationError",
"(",
"'Expected string value for token.'",
")",
"config",
".",
"secret_key",
"=",
"token"
] | Initializes a Authentication and sets it as the new default global authentication.
It also performs some checks before saving the authentication.
:Example
>>> # Expected format for secret key:
>>> import payplug
>>> payplug.set_secret_key('sk_test_somerandomcharacters')
:param token: your sec... | [
"Initializes",
"a",
"Authentication",
"and",
"sets",
"it",
"as",
"the",
"new",
"default",
"global",
"authentication",
".",
"It",
"also",
"performs",
"some",
"checks",
"before",
"saving",
"the",
"authentication",
"."
] | python | train | 30.888889 |
petl-developers/petl | petl/util/counting.py | https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/util/counting.py#L28-L52 | def valuecount(table, field, value, missing=None):
"""
Count the number of occurrences of `value` under the given field. Returns
the absolute count and relative frequency as a pair. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar'],
... ['a', 1],
... ... | [
"def",
"valuecount",
"(",
"table",
",",
"field",
",",
"value",
",",
"missing",
"=",
"None",
")",
":",
"total",
"=",
"0",
"vs",
"=",
"0",
"for",
"v",
"in",
"values",
"(",
"table",
",",
"field",
",",
"missing",
"=",
"missing",
")",
":",
"total",
"+... | Count the number of occurrences of `value` under the given field. Returns
the absolute count and relative frequency as a pair. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['b', 7]]
>>> etl.valu... | [
"Count",
"the",
"number",
"of",
"occurrences",
"of",
"value",
"under",
"the",
"given",
"field",
".",
"Returns",
"the",
"absolute",
"count",
"and",
"relative",
"frequency",
"as",
"a",
"pair",
".",
"E",
".",
"g",
".",
"::"
] | python | train | 29 |
deepmind/sonnet | sonnet/python/modules/spatial_transformer.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/spatial_transformer.py#L495-L500 | def _calc_mask(self):
"""Computes a boolean mask from the user defined constraints."""
mask = []
for row in self._constraints:
mask.append(tuple(x is None for x in row))
return tuple(mask) | [
"def",
"_calc_mask",
"(",
"self",
")",
":",
"mask",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
".",
"_constraints",
":",
"mask",
".",
"append",
"(",
"tuple",
"(",
"x",
"is",
"None",
"for",
"x",
"in",
"row",
")",
")",
"return",
"tuple",
"(",
"mask... | Computes a boolean mask from the user defined constraints. | [
"Computes",
"a",
"boolean",
"mask",
"from",
"the",
"user",
"defined",
"constraints",
"."
] | python | train | 34.166667 |
pandas-dev/pandas | pandas/io/formats/style.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/formats/style.py#L934-L989 | def _background_gradient(s, cmap='PuBu', low=0, high=0,
text_color_threshold=0.408):
"""
Color background in a range according to the data.
"""
if (not isinstance(text_color_threshold, (float, int)) or
not 0 <= text_color_threshold <= 1):
... | [
"def",
"_background_gradient",
"(",
"s",
",",
"cmap",
"=",
"'PuBu'",
",",
"low",
"=",
"0",
",",
"high",
"=",
"0",
",",
"text_color_threshold",
"=",
"0.408",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"text_color_threshold",
",",
"(",
"float",
",",
... | Color background in a range according to the data. | [
"Color",
"background",
"in",
"a",
"range",
"according",
"to",
"the",
"data",
"."
] | python | train | 38.642857 |
miyakogi/wdom | wdom/event.py | https://github.com/miyakogi/wdom/blob/a21bcd23e94baceee71161829f6897bee3fd39c1/wdom/event.py#L401-L414 | def js_query(self, query: str) -> Awaitable:
"""Send query to related DOM on browser.
:param str query: single string which indicates query type.
"""
if self.connected:
self.js_exec(query, self.__reqid)
fut = Future() # type: Future[str]
self.__tasks... | [
"def",
"js_query",
"(",
"self",
",",
"query",
":",
"str",
")",
"->",
"Awaitable",
":",
"if",
"self",
".",
"connected",
":",
"self",
".",
"js_exec",
"(",
"query",
",",
"self",
".",
"__reqid",
")",
"fut",
"=",
"Future",
"(",
")",
"# type: Future[str]",
... | Send query to related DOM on browser.
:param str query: single string which indicates query type. | [
"Send",
"query",
"to",
"related",
"DOM",
"on",
"browser",
"."
] | python | train | 33.357143 |
PyCQA/pylint | pylint/utils/utils.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/utils/utils.py#L335-L355 | def _ini_format(stream, options):
"""format options using the INI format"""
for optname, optdict, value in options:
value = _format_option_value(optdict, value)
help_opt = optdict.get("help")
if help_opt:
help_opt = normalize_text(help_opt, line_len=79, indent="# ")
... | [
"def",
"_ini_format",
"(",
"stream",
",",
"options",
")",
":",
"for",
"optname",
",",
"optdict",
",",
"value",
"in",
"options",
":",
"value",
"=",
"_format_option_value",
"(",
"optdict",
",",
"value",
")",
"help_opt",
"=",
"optdict",
".",
"get",
"(",
"\"... | format options using the INI format | [
"format",
"options",
"using",
"the",
"INI",
"format"
] | python | test | 42.428571 |
aws/sagemaker-python-sdk | src/sagemaker/vpc_utils.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/vpc_utils.py#L67-L108 | def sanitize(vpc_config):
"""
Checks that an instance of VpcConfig has the expected keys and values, removes unexpected keys,
and raises ValueErrors if any expectations are violated
Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
Returns:
A val... | [
"def",
"sanitize",
"(",
"vpc_config",
")",
":",
"if",
"vpc_config",
"is",
"None",
":",
"return",
"vpc_config",
"elif",
"type",
"(",
"vpc_config",
")",
"is",
"not",
"dict",
":",
"raise",
"ValueError",
"(",
"'vpc_config is not a dict: {}'",
".",
"format",
"(",
... | Checks that an instance of VpcConfig has the expected keys and values, removes unexpected keys,
and raises ValueErrors if any expectations are violated
Args:
vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'
Returns:
A valid VpcConfig dict containing only 'Sub... | [
"Checks",
"that",
"an",
"instance",
"of",
"VpcConfig",
"has",
"the",
"expected",
"keys",
"and",
"values",
"removes",
"unexpected",
"keys",
"and",
"raises",
"ValueErrors",
"if",
"any",
"expectations",
"are",
"violated"
] | python | train | 44.97619 |
chrislit/abydos | abydos/phonetic/_soundex.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_soundex.py#L63-L187 | def encode(
self, word, max_length=4, var='American', reverse=False, zero_pad=True
):
"""Return the Soundex code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4... | [
"def",
"encode",
"(",
"self",
",",
"word",
",",
"max_length",
"=",
"4",
",",
"var",
"=",
"'American'",
",",
"reverse",
"=",
"False",
",",
"zero_pad",
"=",
"True",
")",
":",
"# Require a max_length of at least 4 and not more than 64",
"if",
"max_length",
"!=",
... | Return the Soundex code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4)
var : str
The variant of the algorithm to employ (defaults to ``American``):
... | [
"Return",
"the",
"Soundex",
"code",
"for",
"a",
"word",
"."
] | python | valid | 33.072 |
nicholasbishop/trask | trask/phase2.py | https://github.com/nicholasbishop/trask/blob/a97688425f70b539c7710b498627da9a6e39afd8/trask/phase2.py#L36-L44 | def make_keys_safe(dct):
"""Modify the keys in |dct| to be valid attribute names."""
result = {}
for key, val in dct.items():
key = key.replace('-', '_')
if key in keyword.kwlist:
key = key + '_'
result[key] = val
return result | [
"def",
"make_keys_safe",
"(",
"dct",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"dct",
".",
"items",
"(",
")",
":",
"key",
"=",
"key",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"if",
"key",
"in",
"keyword",
".",
"kwli... | Modify the keys in |dct| to be valid attribute names. | [
"Modify",
"the",
"keys",
"in",
"|dct|",
"to",
"be",
"valid",
"attribute",
"names",
"."
] | python | train | 30.111111 |
pandas-dev/pandas | pandas/core/sorting.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sorting.py#L19-L99 | def get_group_index(labels, shape, sort, xnull):
"""
For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations, *as long as* this space fits within int64 bounds;
otherwise, though group indices ide... | [
"def",
"get_group_index",
"(",
"labels",
",",
"shape",
",",
"sort",
",",
"xnull",
")",
":",
"def",
"_int64_cut_off",
"(",
"shape",
")",
":",
"acc",
"=",
"1",
"for",
"i",
",",
"mul",
"in",
"enumerate",
"(",
"shape",
")",
":",
"acc",
"*=",
"int",
"("... | For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations, *as long as* this space fits within int64 bounds;
otherwise, though group indices identify unique combinations of
labels, they cannot be decon... | [
"For",
"the",
"particular",
"label_list",
"gets",
"the",
"offsets",
"into",
"the",
"hypothetical",
"list",
"representing",
"the",
"totally",
"ordered",
"cartesian",
"product",
"of",
"all",
"possible",
"label",
"combinations",
"*",
"as",
"long",
"as",
"*",
"this"... | python | train | 34.888889 |
senaite/senaite.lims | src/senaite/lims/browser/spotlight/jsonapi.py | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/spotlight/jsonapi.py#L94-L106 | def get_search_index_for(catalog):
"""Returns the search index to query
"""
searchable_text_index = "SearchableText"
listing_searchable_text_index = "listing_searchable_text"
if catalog == CATALOG_ANALYSIS_REQUEST_LISTING:
tool = api.get_tool(catalog)
indexes = tool.indexes()
... | [
"def",
"get_search_index_for",
"(",
"catalog",
")",
":",
"searchable_text_index",
"=",
"\"SearchableText\"",
"listing_searchable_text_index",
"=",
"\"listing_searchable_text\"",
"if",
"catalog",
"==",
"CATALOG_ANALYSIS_REQUEST_LISTING",
":",
"tool",
"=",
"api",
".",
"get_to... | Returns the search index to query | [
"Returns",
"the",
"search",
"index",
"to",
"query"
] | python | train | 33.615385 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.