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 |
|---|---|---|---|---|---|---|---|---|---|
jobovy/galpy | galpy/df/diskdf.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/diskdf.py#L240-L286 | def _call_marginalizevlos(self,o,**kwargs):
"""Call the DF, marginalizing over line-of-sight velocity"""
#Get d, l, vperp
l= o.ll(obs=[1.,0.,0.],ro=1.)*_DEGTORAD
vperp= o.vll(ro=1.,vo=1.,obs=[1.,0.,0.,0.,0.,0.])
R= o.R(use_physical=False)
phi= o.phi(use_physical=False)
... | [
"def",
"_call_marginalizevlos",
"(",
"self",
",",
"o",
",",
"*",
"*",
"kwargs",
")",
":",
"#Get d, l, vperp",
"l",
"=",
"o",
".",
"ll",
"(",
"obs",
"=",
"[",
"1.",
",",
"0.",
",",
"0.",
"]",
",",
"ro",
"=",
"1.",
")",
"*",
"_DEGTORAD",
"vperp",
... | Call the DF, marginalizing over line-of-sight velocity | [
"Call",
"the",
"DF",
"marginalizing",
"over",
"line",
"-",
"of",
"-",
"sight",
"velocity"
] | python | train | 53.638298 |
tensorflow/tensorboard | tensorboard/plugins/beholder/visualizer.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/beholder/visualizer.py#L225-L238 | def _sections_to_variance_sections(self, sections_over_time):
'''Computes the variance of corresponding sections over time.
Returns:
a list of np arrays.
'''
variance_sections = []
for i in range(len(sections_over_time[0])):
time_sections = [sections[i] for sections in sections_over_ti... | [
"def",
"_sections_to_variance_sections",
"(",
"self",
",",
"sections_over_time",
")",
":",
"variance_sections",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sections_over_time",
"[",
"0",
"]",
")",
")",
":",
"time_sections",
"=",
"[",
"section... | Computes the variance of corresponding sections over time.
Returns:
a list of np arrays. | [
"Computes",
"the",
"variance",
"of",
"corresponding",
"sections",
"over",
"time",
"."
] | python | train | 30.571429 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winutils.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winutils.py#L48-L64 | def get_system_path():
"""Return the path that Windows will search for dlls."""
_bpath = []
if is_win:
try:
import win32api
except ImportError:
logger.warn("Cannot determine your Windows or System directories")
logger.warn("Please add them to your PATH if ... | [
"def",
"get_system_path",
"(",
")",
":",
"_bpath",
"=",
"[",
"]",
"if",
"is_win",
":",
"try",
":",
"import",
"win32api",
"except",
"ImportError",
":",
"logger",
".",
"warn",
"(",
"\"Cannot determine your Windows or System directories\"",
")",
"logger",
".",
"war... | Return the path that Windows will search for dlls. | [
"Return",
"the",
"path",
"that",
"Windows",
"will",
"search",
"for",
"dlls",
"."
] | python | train | 42.705882 |
tuxpiper/cloudcast | cloudcast/__init__.py | https://github.com/tuxpiper/cloudcast/blob/06ca62045c483e9c3e7ee960ba70d90ea6a13776/cloudcast/__init__.py#L101-L123 | def find_stack_elements(self, module, module_name="", _visited_modules=None):
"""
This function goes through the given container and returns the stack elements. Each stack
element is represented by a tuple:
( container_name, element_name, stack_element)
The tuples are returne... | [
"def",
"find_stack_elements",
"(",
"self",
",",
"module",
",",
"module_name",
"=",
"\"\"",
",",
"_visited_modules",
"=",
"None",
")",
":",
"from",
"types",
"import",
"ModuleType",
"if",
"_visited_modules",
"is",
"None",
":",
"_visited_modules",
"=",
"[",
"]",
... | This function goes through the given container and returns the stack elements. Each stack
element is represented by a tuple:
( container_name, element_name, stack_element)
The tuples are returned in an array | [
"This",
"function",
"goes",
"through",
"the",
"given",
"container",
"and",
"returns",
"the",
"stack",
"elements",
".",
"Each",
"stack",
"element",
"is",
"represented",
"by",
"a",
"tuple",
":",
"(",
"container_name",
"element_name",
"stack_element",
")",
"The",
... | python | train | 45.217391 |
LuqueDaniel/pybooru | pybooru/pybooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/pybooru.py#L79-L93 | def site_name(self, site_name):
"""Function that sets and checks the site name and set url.
Parameters:
site_name (str): The site name in 'SITE_LIST', default sites.
Raises:
PybooruError: When 'site_name' isn't valid.
"""
if site_name in SITE_LIST:
... | [
"def",
"site_name",
"(",
"self",
",",
"site_name",
")",
":",
"if",
"site_name",
"in",
"SITE_LIST",
":",
"self",
".",
"__site_name",
"=",
"site_name",
"self",
".",
"__site_url",
"=",
"SITE_LIST",
"[",
"site_name",
"]",
"[",
"'url'",
"]",
"else",
":",
"rai... | Function that sets and checks the site name and set url.
Parameters:
site_name (str): The site name in 'SITE_LIST', default sites.
Raises:
PybooruError: When 'site_name' isn't valid. | [
"Function",
"that",
"sets",
"and",
"checks",
"the",
"site",
"name",
"and",
"set",
"url",
"."
] | python | train | 34.866667 |
pzs741/TEDT | TEDT/candidate_corpus.py | https://github.com/pzs741/TEDT/blob/6b6663227b755005fe1a1e3e807a05bdb521e066/TEDT/candidate_corpus.py#L174-L250 | def get_corpus(self):
"""获取语料库
Return:
corpus -- 语料库,str类型
"""
# 正向判定
corpus = []
cd = 0
tag = None
for i in range(0, self.init_corpus[0][0]):
init_unit = self.unit_raw[self.init_corpus[0][0] - i]
cdm = CDM(i... | [
"def",
"get_corpus",
"(",
"self",
")",
":",
"# 正向判定",
"corpus",
"=",
"[",
"]",
"cd",
"=",
"0",
"tag",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"init_corpus",
"[",
"0",
"]",
"[",
"0",
"]",
")",
":",
"init_unit",
"=",
... | 获取语料库
Return:
corpus -- 语料库,str类型 | [
"获取语料库"
] | python | train | 28.701299 |
autokey/autokey | lib/autokey/scripting.py | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L593-L619 | def list_menu(self, options, title="Choose a value", message="Choose a value", default=None, **kwargs):
"""
Show a single-selection list menu
Usage: C{dialog.list_menu(options, title="Choose a value", message="Choose a value", default=None, **kwargs)}
@param options: li... | [
"def",
"list_menu",
"(",
"self",
",",
"options",
",",
"title",
"=",
"\"Choose a value\"",
",",
"message",
"=",
"\"Choose a value\"",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"[",
"]",
"for",
"option",
"in",
"options... | Show a single-selection list menu
Usage: C{dialog.list_menu(options, title="Choose a value", message="Choose a value", default=None, **kwargs)}
@param options: list of options (strings) for the dialog
@param title: window title for the dialog
@param message: message dis... | [
"Show",
"a",
"single",
"-",
"selection",
"list",
"menu",
"Usage",
":",
"C",
"{",
"dialog",
".",
"list_menu",
"(",
"options",
"title",
"=",
"Choose",
"a",
"value",
"message",
"=",
"Choose",
"a",
"value",
"default",
"=",
"None",
"**",
"kwargs",
")",
"}"
... | python | train | 38.333333 |
klen/zeta-library | zetalibrary/scss/__init__.py | https://github.com/klen/zeta-library/blob/b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd/zetalibrary/scss/__init__.py#L1570-L1624 | def parse_extends(self):
"""
For each part, create the inheritance parts from the ' extends '
"""
# To be able to manage multiple extends, you need to
# destroy the actual node and create many nodes that have
# mono extend. The first one gets all the css rules
for... | [
"def",
"parse_extends",
"(",
"self",
")",
":",
"# To be able to manage multiple extends, you need to",
"# destroy the actual node and create many nodes that have",
"# mono extend. The first one gets all the css rules",
"for",
"_selectors",
",",
"rules",
"in",
"self",
".",
"parts",
... | For each part, create the inheritance parts from the ' extends ' | [
"For",
"each",
"part",
"create",
"the",
"inheritance",
"parts",
"from",
"the",
"extends"
] | python | train | 45.345455 |
KnowledgeLinks/rdfframework | rdfframework/sparql/querygenerator.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/sparql/querygenerator.py#L122-L127 | def add_sparql_line_nums(sparql):
"""
Returns a sparql query with line numbers prepended
"""
lines = sparql.split("\n")
return "\n".join(["%s %s" % (i + 1, line) for i, line in enumerate(lines)]) | [
"def",
"add_sparql_line_nums",
"(",
"sparql",
")",
":",
"lines",
"=",
"sparql",
".",
"split",
"(",
"\"\\n\"",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"\"%s %s\"",
"%",
"(",
"i",
"+",
"1",
",",
"line",
")",
"for",
"i",
",",
"line",
"in",
"e... | Returns a sparql query with line numbers prepended | [
"Returns",
"a",
"sparql",
"query",
"with",
"line",
"numbers",
"prepended"
] | python | train | 35 |
StagPython/StagPy | stagpy/_step.py | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/_step.py#L241-L261 | def _get_raw_data(self, name):
"""Find file holding data and return its content."""
# try legacy first, then hdf5
filestem = ''
for filestem, list_fvar in self._files.items():
if name in list_fvar:
break
fieldfile = self.step.sdat.filename(filestem, se... | [
"def",
"_get_raw_data",
"(",
"self",
",",
"name",
")",
":",
"# try legacy first, then hdf5",
"filestem",
"=",
"''",
"for",
"filestem",
",",
"list_fvar",
"in",
"self",
".",
"_files",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"list_fvar",
":",
"break"... | Find file holding data and return its content. | [
"Find",
"file",
"holding",
"data",
"and",
"return",
"its",
"content",
"."
] | python | train | 45.380952 |
synw/dataswim | dataswim/data/__init__.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/__init__.py#L173-L181 | def dateparser(self, dformat='%d/%m/%Y'):
"""
Returns a date parser for pandas
"""
def dateparse(dates):
return [pd.datetime.strptime(d, dformat) for d in dates]
return dateparse | [
"def",
"dateparser",
"(",
"self",
",",
"dformat",
"=",
"'%d/%m/%Y'",
")",
":",
"def",
"dateparse",
"(",
"dates",
")",
":",
"return",
"[",
"pd",
".",
"datetime",
".",
"strptime",
"(",
"d",
",",
"dformat",
")",
"for",
"d",
"in",
"dates",
"]",
"return",... | Returns a date parser for pandas | [
"Returns",
"a",
"date",
"parser",
"for",
"pandas"
] | python | train | 24.888889 |
odrling/peony-twitter | peony/oauth_dance.py | https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/oauth_dance.py#L152-L169 | def parse_token(response):
"""
parse the responses containing the tokens
Parameters
----------
response : str
The response containing the tokens
Returns
-------
dict
The parsed tokens
"""
items = response.split("&")
items = [item.split("=") for item in items... | [
"def",
"parse_token",
"(",
"response",
")",
":",
"items",
"=",
"response",
".",
"split",
"(",
"\"&\"",
")",
"items",
"=",
"[",
"item",
".",
"split",
"(",
"\"=\"",
")",
"for",
"item",
"in",
"items",
"]",
"return",
"{",
"key",
":",
"value",
"for",
"k... | parse the responses containing the tokens
Parameters
----------
response : str
The response containing the tokens
Returns
-------
dict
The parsed tokens | [
"parse",
"the",
"responses",
"containing",
"the",
"tokens"
] | python | valid | 19.611111 |
msiemens/PyGitUp | PyGitUp/gitup.py | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L216-L309 | def rebase_all_branches(self):
""" Rebase all branches, if possible. """
col_width = max(len(b.name) for b in self.branches) + 1
if self.repo.head.is_detached:
raise GitError("You're not currently on a branch. I'm exiting"
" in case you're in the middl... | [
"def",
"rebase_all_branches",
"(",
"self",
")",
":",
"col_width",
"=",
"max",
"(",
"len",
"(",
"b",
".",
"name",
")",
"for",
"b",
"in",
"self",
".",
"branches",
")",
"+",
"1",
"if",
"self",
".",
"repo",
".",
"head",
".",
"is_detached",
":",
"raise"... | Rebase all branches, if possible. | [
"Rebase",
"all",
"branches",
"if",
"possible",
"."
] | python | train | 42.223404 |
infothrill/python-dyndnsc | dyndnsc/common/subject.py | https://github.com/infothrill/python-dyndnsc/blob/2196d48aa6098da9835a7611fbdb0b5f0fbf51e4/dyndnsc/common/subject.py#L17-L29 | def register_observer(self, observer, events=None):
"""Register a listener function.
:param observer: external listener function
:param events: tuple or list of relevant events (default=None)
"""
if events is not None and not isinstance(events, (tuple, list)):
events... | [
"def",
"register_observer",
"(",
"self",
",",
"observer",
",",
"events",
"=",
"None",
")",
":",
"if",
"events",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"events",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"events",
"=",
"(",
"events... | Register a listener function.
:param observer: external listener function
:param events: tuple or list of relevant events (default=None) | [
"Register",
"a",
"listener",
"function",
"."
] | python | train | 41.230769 |
eaton-lab/toytree | toytree/Toytree.py | https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/Toytree.py#L420-L430 | def ladderize(self, direction=0):
"""
Ladderize tree (order descendants) so that top child has fewer
descendants than the bottom child in a left to right tree plot.
To reverse this pattern use direction=1.
"""
nself = deepcopy(self)
nself.treenode.ladderize(dire... | [
"def",
"ladderize",
"(",
"self",
",",
"direction",
"=",
"0",
")",
":",
"nself",
"=",
"deepcopy",
"(",
"self",
")",
"nself",
".",
"treenode",
".",
"ladderize",
"(",
"direction",
"=",
"direction",
")",
"nself",
".",
"_fixed_order",
"=",
"None",
"nself",
... | Ladderize tree (order descendants) so that top child has fewer
descendants than the bottom child in a left to right tree plot.
To reverse this pattern use direction=1. | [
"Ladderize",
"tree",
"(",
"order",
"descendants",
")",
"so",
"that",
"top",
"child",
"has",
"fewer",
"descendants",
"than",
"the",
"bottom",
"child",
"in",
"a",
"left",
"to",
"right",
"tree",
"plot",
".",
"To",
"reverse",
"this",
"pattern",
"use",
"directi... | python | train | 37.454545 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py#L364-L374 | def OSPFNeighborState_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
OSPFNeighborState = ET.SubElement(config, "OSPFNeighborState", xmlns="http://brocade.com/ns/brocade-notification-stream")
originator_switch_inf... | [
"def",
"OSPFNeighborState_originator_switch_info_switchIpV4Address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"OSPFNeighborState",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"OSPFNeighbor... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 55.909091 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L93-L124 | def oauth_manager(self, oauth_manager):
"""Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager
"""
@self.app.before_request
def before_request():
endpoint = request.endpoint
resource = self.app.view_functions[endpoint].vi... | [
"def",
"oauth_manager",
"(",
"self",
",",
"oauth_manager",
")",
":",
"@",
"self",
".",
"app",
".",
"before_request",
"def",
"before_request",
"(",
")",
":",
"endpoint",
"=",
"request",
".",
"endpoint",
"resource",
"=",
"self",
".",
"app",
".",
"view_functi... | Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager | [
"Use",
"the",
"oauth",
"manager",
"to",
"enable",
"oauth",
"for",
"API"
] | python | train | 34.34375 |
libtcod/python-tcod | tcod/libtcodpy.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L2330-L2341 | def heightmap_clamp(hm: np.ndarray, mi: float, ma: float) -> None:
"""Clamp all values on this heightmap between ``mi`` and ``ma``
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
mi (float): The lower bound to clamp to.
ma (float): The upper bound to clamp t... | [
"def",
"heightmap_clamp",
"(",
"hm",
":",
"np",
".",
"ndarray",
",",
"mi",
":",
"float",
",",
"ma",
":",
"float",
")",
"->",
"None",
":",
"hm",
".",
"clip",
"(",
"mi",
",",
"ma",
")"
] | Clamp all values on this heightmap between ``mi`` and ``ma``
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
mi (float): The lower bound to clamp to.
ma (float): The upper bound to clamp to.
.. deprecated:: 2.0
Do ``hm.clip(mi, ma)`` instead. | [
"Clamp",
"all",
"values",
"on",
"this",
"heightmap",
"between",
"mi",
"and",
"ma"
] | python | train | 33.666667 |
klen/muffin-redis | muffin_redis.py | https://github.com/klen/muffin-redis/blob/b0cb8c1ba1511d501c2084def156710e75aaf781/muffin_redis.py#L243-L262 | async def _unsubscribe(self, channels, is_mask):
"""Unsubscribe from given channel."""
vanished = []
if channels:
for channel in channels:
key = channel, is_mask
self._channels.remove(key)
self._plugin._subscriptions[key].remove(self._q... | [
"async",
"def",
"_unsubscribe",
"(",
"self",
",",
"channels",
",",
"is_mask",
")",
":",
"vanished",
"=",
"[",
"]",
"if",
"channels",
":",
"for",
"channel",
"in",
"channels",
":",
"key",
"=",
"channel",
",",
"is_mask",
"self",
".",
"_channels",
".",
"re... | Unsubscribe from given channel. | [
"Unsubscribe",
"from",
"given",
"channel",
"."
] | python | train | 46.9 |
saltstack/salt | salt/modules/github.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1870-L1959 | def _query(profile,
action=None,
command=None,
args=None,
method='GET',
header_dict=None,
data=None,
url='https://api.github.com/',
per_page=None):
'''
Make a web call to the GitHub API and deal with paginated results.
'... | [
"def",
"_query",
"(",
"profile",
",",
"action",
"=",
"None",
",",
"command",
"=",
"None",
",",
"args",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"header_dict",
"=",
"None",
",",
"data",
"=",
"None",
",",
"url",
"=",
"'https://api.github.com/'",
",... | Make a web call to the GitHub API and deal with paginated results. | [
"Make",
"a",
"web",
"call",
"to",
"the",
"GitHub",
"API",
"and",
"deal",
"with",
"paginated",
"results",
"."
] | python | train | 32.855556 |
wright-group/WrightTools | WrightTools/data/_spcm.py | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_spcm.py#L28-L145 | def from_spcm(filepath, name=None, *, delimiter=",", parent=None, verbose=True) -> Data:
"""Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``).
If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object.
See the `spcm`__ software hompage fo... | [
"def",
"from_spcm",
"(",
"filepath",
",",
"name",
"=",
"None",
",",
"*",
",",
"delimiter",
"=",
"\",\"",
",",
"parent",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
"->",
"Data",
":",
"filestr",
"=",
"os",
".",
"fspath",
"(",
"filepath",
")",
"fi... | Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``).
If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object.
See the `spcm`__ software hompage for more info.
__ http://www.becker-hickl.com/software/spcm.htm
Parameters
---------... | [
"Create",
"a",
"Data",
"object",
"from",
"a",
"Becker",
"&",
"Hickl",
"spcm",
"file",
"(",
"ASCII",
"-",
"exported",
".",
"asc",
")",
"."
] | python | train | 35.991525 |
royi1000/py-libhdate | hdate/date.py | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/date.py#L91-L95 | def hdate(self):
"""Return the hebrew date."""
if self._last_updated == "hdate":
return self._hdate
return conv.jdn_to_hdate(self._jdn) | [
"def",
"hdate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last_updated",
"==",
"\"hdate\"",
":",
"return",
"self",
".",
"_hdate",
"return",
"conv",
".",
"jdn_to_hdate",
"(",
"self",
".",
"_jdn",
")"
] | Return the hebrew date. | [
"Return",
"the",
"hebrew",
"date",
"."
] | python | train | 33.4 |
CalebBell/fluids | fluids/optional/pychebfun.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L435-L443 | def basis(self, n):
"""
Chebyshev basis functions T_n.
"""
if n == 0:
return self(np.array([1.]))
vals = np.ones(n+1)
vals[1::2] = -1
return self(vals) | [
"def",
"basis",
"(",
"self",
",",
"n",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"self",
"(",
"np",
".",
"array",
"(",
"[",
"1.",
"]",
")",
")",
"vals",
"=",
"np",
".",
"ones",
"(",
"n",
"+",
"1",
")",
"vals",
"[",
"1",
":",
":",
"... | Chebyshev basis functions T_n. | [
"Chebyshev",
"basis",
"functions",
"T_n",
"."
] | python | train | 23.444444 |
nion-software/nionswift | nion/swift/model/DisplayItem.py | https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/model/DisplayItem.py#L980-L998 | def snapshot(self):
"""Return a new library item which is a copy of this one with any dynamic behavior made static."""
display_item = self.__class__()
display_item.display_type = self.display_type
# metadata
display_item._set_persistent_property_value("title", self._get_persisten... | [
"def",
"snapshot",
"(",
"self",
")",
":",
"display_item",
"=",
"self",
".",
"__class__",
"(",
")",
"display_item",
".",
"display_type",
"=",
"self",
".",
"display_type",
"# metadata",
"display_item",
".",
"_set_persistent_property_value",
"(",
"\"title\"",
",",
... | Return a new library item which is a copy of this one with any dynamic behavior made static. | [
"Return",
"a",
"new",
"library",
"item",
"which",
"is",
"a",
"copy",
"of",
"this",
"one",
"with",
"any",
"dynamic",
"behavior",
"made",
"static",
"."
] | python | train | 78.157895 |
mseclab/PyJFuzz | pyjfuzz/core/pjf_mutators.py | https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_mutators.py#L148-L157 | def fuzz(self, obj):
"""
Perform the fuzzing
"""
buf = list(obj)
FuzzFactor = random.randrange(1, len(buf))
numwrites=random.randrange(math.ceil((float(len(buf)) / FuzzFactor)))+1
for j in range(numwrites):
self.random_action(buf)
return self.s... | [
"def",
"fuzz",
"(",
"self",
",",
"obj",
")",
":",
"buf",
"=",
"list",
"(",
"obj",
")",
"FuzzFactor",
"=",
"random",
".",
"randrange",
"(",
"1",
",",
"len",
"(",
"buf",
")",
")",
"numwrites",
"=",
"random",
".",
"randrange",
"(",
"math",
".",
"cei... | Perform the fuzzing | [
"Perform",
"the",
"fuzzing"
] | python | test | 32.7 |
numba/llvmlite | llvmlite/ir/builder.py | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L205-L210 | def position_at_end(self, block):
"""
Position at the end of the basic *block*.
"""
self._block = block
self._anchor = len(block.instructions) | [
"def",
"position_at_end",
"(",
"self",
",",
"block",
")",
":",
"self",
".",
"_block",
"=",
"block",
"self",
".",
"_anchor",
"=",
"len",
"(",
"block",
".",
"instructions",
")"
] | Position at the end of the basic *block*. | [
"Position",
"at",
"the",
"end",
"of",
"the",
"basic",
"*",
"block",
"*",
"."
] | python | train | 29.5 |
MillionIntegrals/vel | vel/rl/buffers/prioritized_circular_replay_buffer.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/prioritized_circular_replay_buffer.py#L46-L75 | def _get_transitions(self, probs, indexes, tree_idxs, batch_info, forward_steps=1, discount_factor=1.0):
""" Return batch of frames for given indexes """
if forward_steps > 1:
transition_arrays = self.backend.get_transitions_forward_steps(indexes, forward_steps, discount_factor)
else... | [
"def",
"_get_transitions",
"(",
"self",
",",
"probs",
",",
"indexes",
",",
"tree_idxs",
",",
"batch_info",
",",
"forward_steps",
"=",
"1",
",",
"discount_factor",
"=",
"1.0",
")",
":",
"if",
"forward_steps",
">",
"1",
":",
"transition_arrays",
"=",
"self",
... | Return batch of frames for given indexes | [
"Return",
"batch",
"of",
"frames",
"for",
"given",
"indexes"
] | python | train | 42.4 |
datajoint/datajoint-python | datajoint/utils.py | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/utils.py#L73-L83 | def safe_write(filename, blob):
"""
A two-step write.
:param filename: full path
:param blob: binary data
:return: None
"""
temp_file = filename + '.saving'
with open(temp_file, 'bw') as f:
f.write(blob)
os.rename(temp_file, filename) | [
"def",
"safe_write",
"(",
"filename",
",",
"blob",
")",
":",
"temp_file",
"=",
"filename",
"+",
"'.saving'",
"with",
"open",
"(",
"temp_file",
",",
"'bw'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"blob",
")",
"os",
".",
"rename",
"(",
"temp_file... | A two-step write.
:param filename: full path
:param blob: binary data
:return: None | [
"A",
"two",
"-",
"step",
"write",
".",
":",
"param",
"filename",
":",
"full",
"path",
":",
"param",
"blob",
":",
"binary",
"data",
":",
"return",
":",
"None"
] | python | train | 24.363636 |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L346-L385 | def get_FEC(molecule_list, temperature, pressure, electronic_energy='Default'):
"""Returns the Gibbs free energy corrections to be added to raw reaction energies.
Parameters
----------
molecule_list : list of strings
temperature : numeric
temperature in K
pressure : numeric
press... | [
"def",
"get_FEC",
"(",
"molecule_list",
",",
"temperature",
",",
"pressure",
",",
"electronic_energy",
"=",
"'Default'",
")",
":",
"if",
"not",
"temperature",
"or",
"not",
"pressure",
":",
"return",
"(",
"0",
")",
"else",
":",
"molecule_list",
"=",
"[",
"m... | Returns the Gibbs free energy corrections to be added to raw reaction energies.
Parameters
----------
molecule_list : list of strings
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
Returns
-------
G_H, G_OH : Gibbs free energy of proton and hy... | [
"Returns",
"the",
"Gibbs",
"free",
"energy",
"corrections",
"to",
"be",
"added",
"to",
"raw",
"reaction",
"energies",
"."
] | python | train | 34.975 |
snowblink14/smatch | amr.py | https://github.com/snowblink14/smatch/blob/ad7e6553a3d52e469b2eef69d7716c87a67eedac/amr.py#L166-L190 | def get_amr_line(input_f):
"""
Read the file containing AMRs. AMRs are separated by a blank line.
Each call of get_amr_line() returns the next available AMR (in one-line form).
Note: this function does not verify if the AMR is valid
"""
cur_amr = []
has_content =... | [
"def",
"get_amr_line",
"(",
"input_f",
")",
":",
"cur_amr",
"=",
"[",
"]",
"has_content",
"=",
"False",
"for",
"line",
"in",
"input_f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"==",
"\"\"",
":",
"if",
"not",
"has_content",
":"... | Read the file containing AMRs. AMRs are separated by a blank line.
Each call of get_amr_line() returns the next available AMR (in one-line form).
Note: this function does not verify if the AMR is valid | [
"Read",
"the",
"file",
"containing",
"AMRs",
".",
"AMRs",
"are",
"separated",
"by",
"a",
"blank",
"line",
".",
"Each",
"call",
"of",
"get_amr_line",
"()",
"returns",
"the",
"next",
"available",
"AMR",
"(",
"in",
"one",
"-",
"line",
"form",
")",
".",
"N... | python | train | 35 |
stevearc/dql | dql/expressions/visitor.py | https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/visitor.py#L39-L45 | def _maybe_replace_path(self, match):
""" Regex replacement method that will sub paths when needed """
path = match.group(0)
if self._should_replace(path):
return self._replace_path(path)
else:
return path | [
"def",
"_maybe_replace_path",
"(",
"self",
",",
"match",
")",
":",
"path",
"=",
"match",
".",
"group",
"(",
"0",
")",
"if",
"self",
".",
"_should_replace",
"(",
"path",
")",
":",
"return",
"self",
".",
"_replace_path",
"(",
"path",
")",
"else",
":",
... | Regex replacement method that will sub paths when needed | [
"Regex",
"replacement",
"method",
"that",
"will",
"sub",
"paths",
"when",
"needed"
] | python | train | 36.428571 |
rosenbrockc/fortpy | fortpy/interop/ftypes.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/interop/ftypes.py#L798-L808 | def _ctypes_out(parameter):
"""Returns a parameter variable declaration for an output variable for the specified
parameter.
"""
if (parameter.dimension is not None and ":" in parameter.dimension
and "out" in parameter.direction and ("allocatable" in parameter.modifiers or
... | [
"def",
"_ctypes_out",
"(",
"parameter",
")",
":",
"if",
"(",
"parameter",
".",
"dimension",
"is",
"not",
"None",
"and",
"\":\"",
"in",
"parameter",
".",
"dimension",
"and",
"\"out\"",
"in",
"parameter",
".",
"direction",
"and",
"(",
"\"allocatable\"",
"in",
... | Returns a parameter variable declaration for an output variable for the specified
parameter. | [
"Returns",
"a",
"parameter",
"variable",
"declaration",
"for",
"an",
"output",
"variable",
"for",
"the",
"specified",
"parameter",
"."
] | python | train | 60.454545 |
bids-standard/pybids | bids/variables/kollekshuns.py | https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/variables/kollekshuns.py#L164-L181 | def _index_entities(self):
''' Sets current instance's entities based on the existing index.
Note: Only entity key/value pairs common to all rows in all contained
Variables are returned. E.g., if a Collection contains Variables
extracted from runs 1, 2 and 3 from subject '01', t... | [
"def",
"_index_entities",
"(",
"self",
")",
":",
"all_ents",
"=",
"pd",
".",
"DataFrame",
".",
"from_records",
"(",
"[",
"v",
".",
"entities",
"for",
"v",
"in",
"self",
".",
"variables",
".",
"values",
"(",
")",
"]",
")",
"constant",
"=",
"all_ents",
... | Sets current instance's entities based on the existing index.
Note: Only entity key/value pairs common to all rows in all contained
Variables are returned. E.g., if a Collection contains Variables
extracted from runs 1, 2 and 3 from subject '01', the returned dict
will be {'... | [
"Sets",
"current",
"instance",
"s",
"entities",
"based",
"on",
"the",
"existing",
"index",
"."
] | python | train | 49 |
edoburu/django-any-urlfield | any_urlfield/models/fields.py | https://github.com/edoburu/django-any-urlfield/blob/8d7d36c8a1fc251930f6dbdcc8b5b5151d20e3ab/any_urlfield/models/fields.py#L137-L157 | def resolve_objects(cls, objects, skip_cached_urls=False):
"""
Make sure all AnyUrlValue objects from a set of objects is resolved in bulk.
This avoids making a query per item.
:param objects: A list or queryset of models.
:param skip_cached_urls: Whether to avoid prefetching da... | [
"def",
"resolve_objects",
"(",
"cls",
",",
"objects",
",",
"skip_cached_urls",
"=",
"False",
")",
":",
"# Allow the queryset or list to consist of multiple models.",
"# This supports querysets from django-polymorphic too.",
"queryset",
"=",
"list",
"(",
"objects",
")",
"any_u... | Make sure all AnyUrlValue objects from a set of objects is resolved in bulk.
This avoids making a query per item.
:param objects: A list or queryset of models.
:param skip_cached_urls: Whether to avoid prefetching data that has it's URL cached. | [
"Make",
"sure",
"all",
"AnyUrlValue",
"objects",
"from",
"a",
"set",
"of",
"objects",
"is",
"resolved",
"in",
"bulk",
".",
"This",
"avoids",
"making",
"a",
"query",
"per",
"item",
"."
] | python | train | 44 |
trailofbits/manticore | manticore/core/state.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/state.py#L362-L380 | def solve_buffer(self, addr, nbytes, constrain=False):
"""
Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to
concretize it
:param int address: Address of buffer to concretize
:param int nbytes: Size of buffer to concretize
:param bool cons... | [
"def",
"solve_buffer",
"(",
"self",
",",
"addr",
",",
"nbytes",
",",
"constrain",
"=",
"False",
")",
":",
"buffer",
"=",
"self",
".",
"cpu",
".",
"read_bytes",
"(",
"addr",
",",
"nbytes",
")",
"result",
"=",
"[",
"]",
"with",
"self",
".",
"_constrain... | Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to
concretize it
:param int address: Address of buffer to concretize
:param int nbytes: Size of buffer to concretize
:param bool constrain: If True, constrain the buffer to the concretized value
:retu... | [
"Reads",
"nbytes",
"of",
"symbolic",
"data",
"from",
"a",
"buffer",
"in",
"memory",
"at",
"addr",
"and",
"attempts",
"to",
"concretize",
"it"
] | python | valid | 41.736842 |
UCL-INGI/INGInious | inginious/agent/__init__.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L188-L199 | async def send_ssh_job_info(self, job_id: BackendJobId, host: str, port: int, key: str):
"""
Send info about the SSH debug connection to the backend/client. Must be called *at most once* for each job.
:exception JobNotRunningException: is raised when the job is not running anymore (send_job_resu... | [
"async",
"def",
"send_ssh_job_info",
"(",
"self",
",",
"job_id",
":",
"BackendJobId",
",",
"host",
":",
"str",
",",
"port",
":",
"int",
",",
"key",
":",
"str",
")",
":",
"if",
"job_id",
"not",
"in",
"self",
".",
"__running_job",
":",
"raise",
"JobNotRu... | Send info about the SSH debug connection to the backend/client. Must be called *at most once* for each job.
:exception JobNotRunningException: is raised when the job is not running anymore (send_job_result already called)
:exception TooManyCallsException: is raised when this function has been called mor... | [
"Send",
"info",
"about",
"the",
"SSH",
"debug",
"connection",
"to",
"the",
"backend",
"/",
"client",
".",
"Must",
"be",
"called",
"*",
"at",
"most",
"once",
"*",
"for",
"each",
"job",
".",
":",
"exception",
"JobNotRunningException",
":",
"is",
"raised",
... | python | train | 64.583333 |
RedHatInsights/insights-core | insights/client/dmsetupWrap.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/dmsetupWrap.py#L13-L23 | def getMajorMinor(deviceName, dmsetupLs):
"""
Given output of dmsetup ls this will return
themajor:minor (block name) of the device deviceName
"""
startingIndex = string.rindex(dmsetupLs, deviceName) + len(deviceName)
endingIndex = string.index(dmsetupLs[startingIndex:], "\n") + startingIndex
... | [
"def",
"getMajorMinor",
"(",
"deviceName",
",",
"dmsetupLs",
")",
":",
"startingIndex",
"=",
"string",
".",
"rindex",
"(",
"dmsetupLs",
",",
"deviceName",
")",
"+",
"len",
"(",
"deviceName",
")",
"endingIndex",
"=",
"string",
".",
"index",
"(",
"dmsetupLs",
... | Given output of dmsetup ls this will return
themajor:minor (block name) of the device deviceName | [
"Given",
"output",
"of",
"dmsetup",
"ls",
"this",
"will",
"return",
"themajor",
":",
"minor",
"(",
"block",
"name",
")",
"of",
"the",
"device",
"deviceName"
] | python | train | 38.454545 |
jssimporter/python-jss | jss/casper.py | https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/casper.py#L68-L76 | def update(self):
"""Request an updated set of data from casper.jxml."""
response = self.jss.session.post(self.url, data=self.auth)
response_xml = ElementTree.fromstring(response.text.encode("utf_8"))
# Remove previous data, if any, and then add in response's XML.
self.clear()
... | [
"def",
"update",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"jss",
".",
"session",
".",
"post",
"(",
"self",
".",
"url",
",",
"data",
"=",
"self",
".",
"auth",
")",
"response_xml",
"=",
"ElementTree",
".",
"fromstring",
"(",
"response",
"."... | Request an updated set of data from casper.jxml. | [
"Request",
"an",
"updated",
"set",
"of",
"data",
"from",
"casper",
".",
"jxml",
"."
] | python | train | 43.333333 |
PyCQA/astroid | astroid/node_classes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L1839-L1850 | def postinit(self, targets=None, value=None, type_annotation=None):
"""Do some setup after initialisation.
:param targets: What is being assigned to.
:type targets: list(NodeNG) or None
:param value: The value being assigned to the variables.
:type: NodeNG or None
"""
... | [
"def",
"postinit",
"(",
"self",
",",
"targets",
"=",
"None",
",",
"value",
"=",
"None",
",",
"type_annotation",
"=",
"None",
")",
":",
"self",
".",
"targets",
"=",
"targets",
"self",
".",
"value",
"=",
"value",
"self",
".",
"type_annotation",
"=",
"typ... | Do some setup after initialisation.
:param targets: What is being assigned to.
:type targets: list(NodeNG) or None
:param value: The value being assigned to the variables.
:type: NodeNG or None | [
"Do",
"some",
"setup",
"after",
"initialisation",
"."
] | python | train | 34.333333 |
rocky/python-uncompyle6 | uncompyle6/scanners/scanner2.py | https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/scanners/scanner2.py#L1172-L1209 | def rem_or(self, start, end, instr, target=None, include_beyond_target=False):
"""
Find all <instr> in the block from start to end.
<instr> is any python bytecode instruction or a list of opcodes
If <instr> is an opcode with a target (like a jump), a target
destination can be spe... | [
"def",
"rem_or",
"(",
"self",
",",
"start",
",",
"end",
",",
"instr",
",",
"target",
"=",
"None",
",",
"include_beyond_target",
"=",
"False",
")",
":",
"assert",
"(",
"start",
">=",
"0",
"and",
"end",
"<=",
"len",
"(",
"self",
".",
"code",
")",
"an... | Find all <instr> in the block from start to end.
<instr> is any python bytecode instruction or a list of opcodes
If <instr> is an opcode with a target (like a jump), a target
destination can be specified which must match precisely.
Return a list with indexes to them or [] if none found. | [
"Find",
"all",
"<instr",
">",
"in",
"the",
"block",
"from",
"start",
"to",
"end",
".",
"<instr",
">",
"is",
"any",
"python",
"bytecode",
"instruction",
"or",
"a",
"list",
"of",
"opcodes",
"If",
"<instr",
">",
"is",
"an",
"opcode",
"with",
"a",
"target"... | python | train | 35.815789 |
trailofbits/manticore | manticore/ethereum/abi.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L24-L40 | def _type_size(ty):
""" Calculate `static` type size """
if ty[0] in ('int', 'uint', 'bytesM', 'function'):
return 32
elif ty[0] in ('tuple'):
result = 0
for ty_i in ty[1]:
result += ABI._type_size(ty_i)
return result
elif t... | [
"def",
"_type_size",
"(",
"ty",
")",
":",
"if",
"ty",
"[",
"0",
"]",
"in",
"(",
"'int'",
",",
"'uint'",
",",
"'bytesM'",
",",
"'function'",
")",
":",
"return",
"32",
"elif",
"ty",
"[",
"0",
"]",
"in",
"(",
"'tuple'",
")",
":",
"result",
"=",
"0... | Calculate `static` type size | [
"Calculate",
"static",
"type",
"size"
] | python | valid | 32 |
project-ncl/pnc-cli | pnc_cli/environments.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/environments.py#L18-L24 | def get_environment(id=None, name=None):
"""
Get a specific Environment by name or ID
"""
data = get_environment_raw(id, name)
if data:
return utils.format_json(data) | [
"def",
"get_environment",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"data",
"=",
"get_environment_raw",
"(",
"id",
",",
"name",
")",
"if",
"data",
":",
"return",
"utils",
".",
"format_json",
"(",
"data",
")"
] | Get a specific Environment by name or ID | [
"Get",
"a",
"specific",
"Environment",
"by",
"name",
"or",
"ID"
] | python | train | 26.857143 |
trailofbits/protofuzz | protofuzz/pbimport.py | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L80-L101 | def _compile_proto(full_path, dest):
'Helper to compile protobuf files'
proto_path = os.path.dirname(full_path)
protoc_args = [find_protoc(),
'--python_out={}'.format(dest),
'--proto_path={}'.format(proto_path),
full_path]
proc = subprocess... | [
"def",
"_compile_proto",
"(",
"full_path",
",",
"dest",
")",
":",
"proto_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"full_path",
")",
"protoc_args",
"=",
"[",
"find_protoc",
"(",
")",
",",
"'--python_out={}'",
".",
"format",
"(",
"dest",
")",
",... | Helper to compile protobuf files | [
"Helper",
"to",
"compile",
"protobuf",
"files"
] | python | train | 36.545455 |
rigetti/quantumflow | quantumflow/ops.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L148-L151 | def permute(self, qubits: Qubits) -> 'Gate':
"""Permute the order of the qubits"""
vec = self.vec.permute(qubits)
return Gate(vec.tensor, qubits=vec.qubits) | [
"def",
"permute",
"(",
"self",
",",
"qubits",
":",
"Qubits",
")",
"->",
"'Gate'",
":",
"vec",
"=",
"self",
".",
"vec",
".",
"permute",
"(",
"qubits",
")",
"return",
"Gate",
"(",
"vec",
".",
"tensor",
",",
"qubits",
"=",
"vec",
".",
"qubits",
")"
] | Permute the order of the qubits | [
"Permute",
"the",
"order",
"of",
"the",
"qubits"
] | python | train | 44.25 |
projectshift/shift-boiler | boiler/user/user_service.py | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L598-L602 | def remove_role_from_user(self, user, role):
""" Removes role from user """
user.remove_role(role)
self.save(user)
events.user_lost_role_event.send(user, role=role) | [
"def",
"remove_role_from_user",
"(",
"self",
",",
"user",
",",
"role",
")",
":",
"user",
".",
"remove_role",
"(",
"role",
")",
"self",
".",
"save",
"(",
"user",
")",
"events",
".",
"user_lost_role_event",
".",
"send",
"(",
"user",
",",
"role",
"=",
"ro... | Removes role from user | [
"Removes",
"role",
"from",
"user"
] | python | train | 38.4 |
sixty-north/added-value | source/added_value/tabulator.py | https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/tabulator.py#L225-L335 | def tabulate(
obj,
v_level_indexes=None,
h_level_indexes=None,
v_level_visibility=None,
h_level_visibility=None,
v_level_sort_keys=None,
h_level_sort_keys=None,
v_level_titles=None,
h_level_titles=None,
empty="",
):
"""Render a nested data structure into a two-dimensional tab... | [
"def",
"tabulate",
"(",
"obj",
",",
"v_level_indexes",
"=",
"None",
",",
"h_level_indexes",
"=",
"None",
",",
"v_level_visibility",
"=",
"None",
",",
"h_level_visibility",
"=",
"None",
",",
"v_level_sort_keys",
"=",
"None",
",",
"h_level_sort_keys",
"=",
"None",... | Render a nested data structure into a two-dimensional table.
Args:
obj: The indexable data structure to be rendered, which can
either be a non-string sequence or a mapping containing other
sequences and mappings nested to arbitrarily many levels,
with all the leaf items ... | [
"Render",
"a",
"nested",
"data",
"structure",
"into",
"a",
"two",
"-",
"dimensional",
"table",
"."
] | python | train | 42.981982 |
tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L304-L364 | def compute_mpnn_qkv(node_states,
total_key_depth,
total_value_depth,
num_transforms):
"""Computes query, key and value for edge matrices.
Let B be the number of batches.
Let N be the number of nodes in the graph.
Let D be the size of the node hidd... | [
"def",
"compute_mpnn_qkv",
"(",
"node_states",
",",
"total_key_depth",
",",
"total_value_depth",
",",
"num_transforms",
")",
":",
"# node_states is initially a tensor with shape [B, N, D]. The call to dense",
"# creates a D x K kernel that serves as a fully-connected layer.",
"#",
"# F... | Computes query, key and value for edge matrices.
Let B be the number of batches.
Let N be the number of nodes in the graph.
Let D be the size of the node hidden states.
Let K be the size of the attention keys/queries (total_key_depth).
Let V be the size of the attention values (total_value_depth).
Let T be... | [
"Computes",
"query",
"key",
"and",
"value",
"for",
"edge",
"matrices",
"."
] | python | train | 47.606557 |
SeabornGames/Meta | seaborn_meta/calling_function.py | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L163-L202 | def function_info(function_index=1, function_name=None, line_number=None):
"""
This will return the class_name and function_name of the
function traced back two functions.
:param function_index: int of how many frames back the program
should look (2 will give the parent of t... | [
"def",
"function_info",
"(",
"function_index",
"=",
"1",
",",
"function_name",
"=",
"None",
",",
"line_number",
"=",
"None",
")",
":",
"frm",
"=",
"func_frame",
"(",
"function_index",
"+",
"1",
",",
"function_name",
")",
"file_",
"=",
"os",
".",
"path",
... | This will return the class_name and function_name of the
function traced back two functions.
:param function_index: int of how many frames back the program
should look (2 will give the parent of the caller)
:param function_name: str of what function to look for (should
... | [
"This",
"will",
"return",
"the",
"class_name",
"and",
"function_name",
"of",
"the",
"function",
"traced",
"back",
"two",
"functions",
"."
] | python | train | 45.1 |
edibledinos/pwnypack | pwnypack/shellcode/x86/mutable_data.py | https://github.com/edibledinos/pwnypack/blob/e0a5a8e6ef3f4f1f7e1b91ee379711f4a49cb0e6/pwnypack/shellcode/x86/mutable_data.py#L41-L99 | def nasm_null_safe_mutable_data_finalizer(env, code, data):
"""
Simple data allocation strategy that expects the code to be in a writable
segment. We just append the data to the end of the code.
"""
if data or env.buffers:
# Determine length of nullify + shellcode and adjust data pointer
... | [
"def",
"nasm_null_safe_mutable_data_finalizer",
"(",
"env",
",",
"code",
",",
"data",
")",
":",
"if",
"data",
"or",
"env",
".",
"buffers",
":",
"# Determine length of nullify + shellcode and adjust data pointer",
"xor_offsets",
"=",
"[",
"]",
"masked_data",
"=",
"Orde... | Simple data allocation strategy that expects the code to be in a writable
segment. We just append the data to the end of the code. | [
"Simple",
"data",
"allocation",
"strategy",
"that",
"expects",
"the",
"code",
"to",
"be",
"in",
"a",
"writable",
"segment",
".",
"We",
"just",
"append",
"the",
"data",
"to",
"the",
"end",
"of",
"the",
"code",
"."
] | python | train | 36.135593 |
workforce-data-initiative/skills-utils | skills_utils/time.py | https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/time.py#L26-L35 | def datetime_to_year_quarter(dt):
"""
Args:
dt: a datetime
Returns:
tuple of the datetime's year and quarter
"""
year = dt.year
quarter = int(math.ceil(float(dt.month)/3))
return (year, quarter) | [
"def",
"datetime_to_year_quarter",
"(",
"dt",
")",
":",
"year",
"=",
"dt",
".",
"year",
"quarter",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
"dt",
".",
"month",
")",
"/",
"3",
")",
")",
"return",
"(",
"year",
",",
"quarter",
")"
] | Args:
dt: a datetime
Returns:
tuple of the datetime's year and quarter | [
"Args",
":",
"dt",
":",
"a",
"datetime",
"Returns",
":",
"tuple",
"of",
"the",
"datetime",
"s",
"year",
"and",
"quarter"
] | python | train | 22.9 |
annoviko/pyclustering | pyclustering/nnet/cnn.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/nnet/cnn.py#L116-L133 | def __allocate_neuron_patterns(self, start_iteration, stop_iteration):
"""!
@brief Allocates observation transposed matrix of neurons that is limited by specified periods of simulation.
@details Matrix where state of each neuron is denoted by zero/one in line with Heaviside function on each i... | [
"def",
"__allocate_neuron_patterns",
"(",
"self",
",",
"start_iteration",
",",
"stop_iteration",
")",
":",
"pattern_matrix",
"=",
"[",
"]",
"for",
"index_neuron",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"output",
"[",
"0",
"]",
")",
")",
":",
"pattern... | !
@brief Allocates observation transposed matrix of neurons that is limited by specified periods of simulation.
@details Matrix where state of each neuron is denoted by zero/one in line with Heaviside function on each iteration.
@return (list) Transposed observation matrix that is l... | [
"!"
] | python | valid | 46.888889 |
kstaniek/condoor | condoor/connection.py | https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L371-L374 | def resume_session_logging(self):
"""Resume session logging."""
self._chain.ctrl.set_session_log(self.session_fd)
self.log("Session logging resumed") | [
"def",
"resume_session_logging",
"(",
"self",
")",
":",
"self",
".",
"_chain",
".",
"ctrl",
".",
"set_session_log",
"(",
"self",
".",
"session_fd",
")",
"self",
".",
"log",
"(",
"\"Session logging resumed\"",
")"
] | Resume session logging. | [
"Resume",
"session",
"logging",
"."
] | python | train | 42.5 |
twilio/twilio-python | twilio/rest/preview/wireless/sim/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/preview/wireless/sim/__init__.py#L108-L145 | def page(self, status=values.unset, iccid=values.unset, rate_plan=values.unset,
e_id=values.unset, sim_registration_code=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of SimInstance records from... | [
"def",
"page",
"(",
"self",
",",
"status",
"=",
"values",
".",
"unset",
",",
"iccid",
"=",
"values",
".",
"unset",
",",
"rate_plan",
"=",
"values",
".",
"unset",
",",
"e_id",
"=",
"values",
".",
"unset",
",",
"sim_registration_code",
"=",
"values",
"."... | Retrieve a single page of SimInstance records from the API.
Request is executed immediately
:param unicode status: The status
:param unicode iccid: The iccid
:param unicode rate_plan: The rate_plan
:param unicode e_id: The e_id
:param unicode sim_registration_code: The s... | [
"Retrieve",
"a",
"single",
"page",
"of",
"SimInstance",
"records",
"from",
"the",
"API",
".",
"Request",
"is",
"executed",
"immediately"
] | python | train | 36.947368 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/error.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/error.py#L262-L279 | def render_traceback(self, excid=None):
"""render one or all of my tracebacks to a list of lines"""
lines = []
if excid is None:
for (en,ev,etb,ei) in self.elist:
lines.append(self._get_engine_str(ei))
lines.extend((etb or 'No traceback available').spl... | [
"def",
"render_traceback",
"(",
"self",
",",
"excid",
"=",
"None",
")",
":",
"lines",
"=",
"[",
"]",
"if",
"excid",
"is",
"None",
":",
"for",
"(",
"en",
",",
"ev",
",",
"etb",
",",
"ei",
")",
"in",
"self",
".",
"elist",
":",
"lines",
".",
"appe... | render one or all of my tracebacks to a list of lines | [
"render",
"one",
"or",
"all",
"of",
"my",
"tracebacks",
"to",
"a",
"list",
"of",
"lines"
] | python | test | 39.444444 |
awslabs/serverless-application-model | samtranslator/intrinsics/actions.py | https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/actions.py#L172-L194 | def resolve_parameter_refs(self, input_dict, parameters):
"""
Substitute references found within the string of `Fn::Sub` intrinsic function
:param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be
`Fn::Sub`. Ex: {"Fn::Sub": ...}
... | [
"def",
"resolve_parameter_refs",
"(",
"self",
",",
"input_dict",
",",
"parameters",
")",
":",
"def",
"do_replacement",
"(",
"full_ref",
",",
"prop_name",
")",
":",
"\"\"\"\n Replace parameter references with actual value. Return value of this method is directly replace... | Substitute references found within the string of `Fn::Sub` intrinsic function
:param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be
`Fn::Sub`. Ex: {"Fn::Sub": ...}
:param parameters: Dictionary of parameter values for substitution
... | [
"Substitute",
"references",
"found",
"within",
"the",
"string",
"of",
"Fn",
"::",
"Sub",
"intrinsic",
"function"
] | python | train | 41.26087 |
oisinmulvihill/stomper | lib/stomper/utils.py | https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/utils.py#L11-L22 | def log_init(level):
"""Set up a logger that catches all channels and logs it to stdout.
This is used to set up logging when testing.
"""
log = logging.getLogger()
hdlr = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
hdlr.se... | [
"def",
"log_init",
"(",
"level",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
")",
"hdlr",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s %(name)s %(levelname)s %(message)s'",
")",
"... | Set up a logger that catches all channels and logs it to stdout.
This is used to set up logging when testing. | [
"Set",
"up",
"a",
"logger",
"that",
"catches",
"all",
"channels",
"and",
"logs",
"it",
"to",
"stdout",
".",
"This",
"is",
"used",
"to",
"set",
"up",
"logging",
"when",
"testing",
"."
] | python | train | 31.583333 |
edx/edx-enterprise | enterprise/api/v1/serializers.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L567-L616 | def create(self, validated_data):
"""
Perform the enrollment for existing enterprise customer users, or create the pending objects for new users.
"""
enterprise_customer = self.context.get('enterprise_customer')
lms_user = validated_data.get('lms_user_id')
tpa_user = vali... | [
"def",
"create",
"(",
"self",
",",
"validated_data",
")",
":",
"enterprise_customer",
"=",
"self",
".",
"context",
".",
"get",
"(",
"'enterprise_customer'",
")",
"lms_user",
"=",
"validated_data",
".",
"get",
"(",
"'lms_user_id'",
")",
"tpa_user",
"=",
"valida... | Perform the enrollment for existing enterprise customer users, or create the pending objects for new users. | [
"Perform",
"the",
"enrollment",
"for",
"existing",
"enterprise",
"customer",
"users",
"or",
"create",
"the",
"pending",
"objects",
"for",
"new",
"users",
"."
] | python | valid | 42.84 |
bradmontgomery/django-redis-metrics | redis_metrics/models.py | https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L372-L384 | def get_metric(self, slug):
"""Get the current values for a metric.
Returns a dictionary with metric values accumulated for the seconds,
minutes, hours, day, week, month, and year.
"""
results = OrderedDict()
granularities = self._granularities()
keys = self._bu... | [
"def",
"get_metric",
"(",
"self",
",",
"slug",
")",
":",
"results",
"=",
"OrderedDict",
"(",
")",
"granularities",
"=",
"self",
".",
"_granularities",
"(",
")",
"keys",
"=",
"self",
".",
"_build_keys",
"(",
"slug",
")",
"for",
"granularity",
",",
"key",
... | Get the current values for a metric.
Returns a dictionary with metric values accumulated for the seconds,
minutes, hours, day, week, month, and year. | [
"Get",
"the",
"current",
"values",
"for",
"a",
"metric",
"."
] | python | train | 34.923077 |
jaegertracing/jaeger-client-python | jaeger_client/throttler.py | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/throttler.py#L89-L105 | def _init_polling(self):
"""
Bootstrap polling for throttler.
To avoid spiky traffic from throttler clients, we use a random delay
before the first poll.
"""
with self.lock:
if not self.running:
return
r = random.Random()
... | [
"def",
"_init_polling",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"r",
"=",
"random",
".",
"Random",
"(",
")",
"delay",
"=",
"r",
".",
"random",
"(",
")",
"*",
"self",
".",
"refre... | Bootstrap polling for throttler.
To avoid spiky traffic from throttler clients, we use a random delay
before the first poll. | [
"Bootstrap",
"polling",
"for",
"throttler",
"."
] | python | train | 32.764706 |
saltstack/salt | salt/grains/core.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L417-L440 | def _aix_cpudata():
'''
Return CPU information for AIX systems
'''
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which('prtconf')
if cmd:
data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
for dest, ... | [
"def",
"_aix_cpudata",
"(",
")",
":",
"# Provides:",
"# cpuarch",
"# num_cpus",
"# cpu_model",
"# cpu_flags",
"grains",
"=",
"{",
"}",
"cmd",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'prtconf'",
")",
"if",
"cmd",
":",
"data",
"="... | Return CPU information for AIX systems | [
"Return",
"CPU",
"information",
"for",
"AIX",
"systems"
] | python | train | 40.458333 |
architv/soccer-cli | soccer/writers.py | https://github.com/architv/soccer-cli/blob/472e9f492f7633a8e9739e228a6c31de454da88b/soccer/writers.py#L79-L91 | def team_scores(self, team_scores, time, show_datetime, use_12_hour_format):
"""Prints the teams scores in a pretty format"""
for score in team_scores["matches"]:
if score["status"] == "FINISHED":
click.secho("%s\t" % score["utcDate"].split('T')[0],
... | [
"def",
"team_scores",
"(",
"self",
",",
"team_scores",
",",
"time",
",",
"show_datetime",
",",
"use_12_hour_format",
")",
":",
"for",
"score",
"in",
"team_scores",
"[",
"\"matches\"",
"]",
":",
"if",
"score",
"[",
"\"status\"",
"]",
"==",
"\"FINISHED\"",
":"... | Prints the teams scores in a pretty format | [
"Prints",
"the",
"teams",
"scores",
"in",
"a",
"pretty",
"format"
] | python | train | 59.769231 |
nickpandolfi/Cyther | cyther/parser.py | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L135-L153 | def _parse_dependencies(string):
"""
This function actually parses the dependencies are sorts them into
the buildable and given dependencies
"""
contents = _get_contents_between(string, '(', ')')
unsorted_dependencies = contents.split(',')
_check_parameters(unsorted_dependencies, ('?',))
... | [
"def",
"_parse_dependencies",
"(",
"string",
")",
":",
"contents",
"=",
"_get_contents_between",
"(",
"string",
",",
"'('",
",",
"')'",
")",
"unsorted_dependencies",
"=",
"contents",
".",
"split",
"(",
"','",
")",
"_check_parameters",
"(",
"unsorted_dependencies",... | This function actually parses the dependencies are sorts them into
the buildable and given dependencies | [
"This",
"function",
"actually",
"parses",
"the",
"dependencies",
"are",
"sorts",
"them",
"into",
"the",
"buildable",
"and",
"given",
"dependencies"
] | python | train | 35.052632 |
maximtrp/scikit-posthocs | scikit_posthocs/_posthocs.py | https://github.com/maximtrp/scikit-posthocs/blob/5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d/scikit_posthocs/_posthocs.py#L1900-L1991 | def posthoc_mannwhitney(a, val_col=None, group_col=None, use_continuity=True, alternative='two-sided', p_adjust=None, sort=True):
'''Pairwise comparisons with Mann-Whitney rank test.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interfa... | [
"def",
"posthoc_mannwhitney",
"(",
"a",
",",
"val_col",
"=",
"None",
",",
"group_col",
"=",
"None",
",",
"use_continuity",
"=",
"True",
",",
"alternative",
"=",
"'two-sided'",
",",
"p_adjust",
"=",
"None",
",",
"sort",
"=",
"True",
")",
":",
"x",
",",
... | Pairwise comparisons with Mann-Whitney rank test.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interface or a pandas
DataFrame. Array must be two-dimensional.
val_col : str, optional
Name of a DataFrame column that cont... | [
"Pairwise",
"comparisons",
"with",
"Mann",
"-",
"Whitney",
"rank",
"test",
"."
] | python | train | 37.108696 |
bninja/pwho | pwho/__init__.py | https://github.com/bninja/pwho/blob/7ade559087e5fb687fa5af19fd0b48352525aeb2/pwho/__init__.py#L222-L264 | def parse_line(line):
"""
Parses a byte string like:
PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n
to a `ProxyInfo`.
"""
if not line.startswith(b'PROXY'):
raise exc.InvalidLine('Missing "PROXY" prefix', line)
if not line.endswith(CRLF):
raise exc.InvalidLine('Missing... | [
"def",
"parse_line",
"(",
"line",
")",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"b'PROXY'",
")",
":",
"raise",
"exc",
".",
"InvalidLine",
"(",
"'Missing \"PROXY\" prefix'",
",",
"line",
")",
"if",
"not",
"line",
".",
"endswith",
"(",
"CRLF",
")"... | Parses a byte string like:
PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n
to a `ProxyInfo`. | [
"Parses",
"a",
"byte",
"string",
"like",
":"
] | python | train | 33.069767 |
ioos/compliance-checker | compliance_checker/suite.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/suite.py#L247-L285 | def run(self, ds, skip_checks, *checker_names):
"""
Runs this CheckSuite on the dataset with all the passed Checker instances.
Returns a dictionary mapping checker names to a 2-tuple of their grouped scores and errors/exceptions while running checks.
"""
ret_val = {}
ch... | [
"def",
"run",
"(",
"self",
",",
"ds",
",",
"skip_checks",
",",
"*",
"checker_names",
")",
":",
"ret_val",
"=",
"{",
"}",
"checkers",
"=",
"self",
".",
"_get_valid_checkers",
"(",
"ds",
",",
"checker_names",
")",
"if",
"skip_checks",
"is",
"not",
"None",
... | Runs this CheckSuite on the dataset with all the passed Checker instances.
Returns a dictionary mapping checker names to a 2-tuple of their grouped scores and errors/exceptions while running checks. | [
"Runs",
"this",
"CheckSuite",
"on",
"the",
"dataset",
"with",
"all",
"the",
"passed",
"Checker",
"instances",
"."
] | python | train | 35.205128 |
apache/incubator-mxnet | example/ssd/symbol/symbol_builder.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/symbol/symbol_builder.py#L118-L182 | def get_symbol(network, num_classes, from_layers, num_filters, sizes, ratios,
strides, pads, normalizations=-1, steps=[], min_filter=128,
nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs):
"""Build network for testing SSD
Parameters
----------
network : str
... | [
"def",
"get_symbol",
"(",
"network",
",",
"num_classes",
",",
"from_layers",
",",
"num_filters",
",",
"sizes",
",",
"ratios",
",",
"strides",
",",
"pads",
",",
"normalizations",
"=",
"-",
"1",
",",
"steps",
"=",
"[",
"]",
",",
"min_filter",
"=",
"128",
... | Build network for testing SSD
Parameters
----------
network : str
base network symbol name
num_classes : int
number of object classes not including background
from_layers : list of str
feature extraction layers, use '' for add extra layers
For example:
from_l... | [
"Build",
"network",
"for",
"testing",
"SSD"
] | python | train | 42.353846 |
BernardFW/bernard | src/bernard/analytics/base.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/analytics/base.py#L65-L74 | def new_task(func):
"""
Runs the decorated function in a new task
"""
@wraps(func)
async def wrapper(self, *args, **kwargs):
loop = get_event_loop()
loop.create_task(func(self, *args, **kwargs))
return wrapper | [
"def",
"new_task",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"async",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"loop",
"=",
"get_event_loop",
"(",
")",
"loop",
".",
"create_task",
"(",
"func",... | Runs the decorated function in a new task | [
"Runs",
"the",
"decorated",
"function",
"in",
"a",
"new",
"task"
] | python | train | 24.1 |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L1055-L1070 | def send_invoice_email(self, invoice_id, email_dict):
"""
Sends an invoice by email
If you want to send your email to more than one persons do:
'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}}
:param invoice_id: the invoice id
:param email_dict: the... | [
"def",
"send_invoice_email",
"(",
"self",
",",
"invoice_id",
",",
"email_dict",
")",
":",
"return",
"self",
".",
"_create_post_request",
"(",
"resource",
"=",
"INVOICES",
",",
"billomat_id",
"=",
"invoice_id",
",",
"send_data",
"=",
"email_dict",
",",
"command",... | Sends an invoice by email
If you want to send your email to more than one persons do:
'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}}
:param invoice_id: the invoice id
:param email_dict: the email dict
:return dict | [
"Sends",
"an",
"invoice",
"by",
"email",
"If",
"you",
"want",
"to",
"send",
"your",
"email",
"to",
"more",
"than",
"one",
"persons",
"do",
":",
"recipients",
":",
"{",
"to",
":",
"[",
"bykof@me",
".",
"com",
"mbykovski@seibert",
"-",
"media",
".",
"net... | python | train | 33.0625 |
nimbusproject/dashi | dashi/bootstrap/__init__.py | https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/bootstrap/__init__.py#L171-L210 | def _parse_argv(argv=copy(sys.argv)):
"""return argv as a parsed dictionary, looks like the following:
app --option1 likethis --option2 likethat --flag
->
{'option1': 'likethis', 'option2': 'likethat', 'flag': True}
"""
cfg = DotDict()
cfg_files = []
argv = argv[1:] # Skip command n... | [
"def",
"_parse_argv",
"(",
"argv",
"=",
"copy",
"(",
"sys",
".",
"argv",
")",
")",
":",
"cfg",
"=",
"DotDict",
"(",
")",
"cfg_files",
"=",
"[",
"]",
"argv",
"=",
"argv",
"[",
"1",
":",
"]",
"# Skip command name",
"while",
"argv",
":",
"arg",
"=",
... | return argv as a parsed dictionary, looks like the following:
app --option1 likethis --option2 likethat --flag
->
{'option1': 'likethis', 'option2': 'likethat', 'flag': True} | [
"return",
"argv",
"as",
"a",
"parsed",
"dictionary",
"looks",
"like",
"the",
"following",
":"
] | python | train | 25.175 |
aewallin/allantools | allantools/noise.py | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/noise.py#L56-L67 | def brown(num_points=1024, b2=1.0, fs=1.0):
""" Brownian or random walk (diffusion) noise with 1/f^2 PSD
(not really a color... rather Brownian or random-walk)
N = number of samples
b2 = desired PSD is b2*f^-2
fs = sampling frequency
we integrate white-noise to get Brownian... | [
"def",
"brown",
"(",
"num_points",
"=",
"1024",
",",
"b2",
"=",
"1.0",
",",
"fs",
"=",
"1.0",
")",
":",
"return",
"(",
"1.0",
"/",
"float",
"(",
"fs",
")",
")",
"*",
"numpy",
".",
"cumsum",
"(",
"white",
"(",
"num_points",
",",
"b0",
"=",
"b2",... | Brownian or random walk (diffusion) noise with 1/f^2 PSD
(not really a color... rather Brownian or random-walk)
N = number of samples
b2 = desired PSD is b2*f^-2
fs = sampling frequency
we integrate white-noise to get Brownian noise. | [
"Brownian",
"or",
"random",
"walk",
"(",
"diffusion",
")",
"noise",
"with",
"1",
"/",
"f^2",
"PSD",
"(",
"not",
"really",
"a",
"color",
"...",
"rather",
"Brownian",
"or",
"random",
"-",
"walk",
")"
] | python | train | 35 |
cebel/pyuniprot | src/pyuniprot/manager/query.py | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/query.py#L963-L970 | def feature_types(self):
"""Distinct types (``type_``) in :class:`.models.Feature`
:return: all distinct feature types
:rtype: list[str]
"""
r = self.session.query(distinct(models.Feature.type_)).all()
return [x[0] for x in r] | [
"def",
"feature_types",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"session",
".",
"query",
"(",
"distinct",
"(",
"models",
".",
"Feature",
".",
"type_",
")",
")",
".",
"all",
"(",
")",
"return",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"r... | Distinct types (``type_``) in :class:`.models.Feature`
:return: all distinct feature types
:rtype: list[str] | [
"Distinct",
"types",
"(",
"type_",
")",
"in",
":",
"class",
":",
".",
"models",
".",
"Feature"
] | python | train | 33.5 |
rueckstiess/mtools | mtools/util/logevent.py | https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/util/logevent.py#L823-L837 | def to_dict(self, labels=None):
"""Convert LogEvent object to a dictionary."""
output = {}
if labels is None:
labels = ['line_str', 'split_tokens', 'datetime', 'operation',
'thread', 'namespace', 'nscanned', 'ntoreturn',
'nreturned', 'ninse... | [
"def",
"to_dict",
"(",
"self",
",",
"labels",
"=",
"None",
")",
":",
"output",
"=",
"{",
"}",
"if",
"labels",
"is",
"None",
":",
"labels",
"=",
"[",
"'line_str'",
",",
"'split_tokens'",
",",
"'datetime'",
",",
"'operation'",
",",
"'thread'",
",",
"'nam... | Convert LogEvent object to a dictionary. | [
"Convert",
"LogEvent",
"object",
"to",
"a",
"dictionary",
"."
] | python | train | 37.666667 |
DataBiosphere/toil | src/toil/utils/toilStats.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/utils/toilStats.py#L345-L356 | def get(tree, name):
""" Return a float value attribute NAME from TREE.
"""
if name in tree:
value = tree[name]
else:
return float("nan")
try:
a = float(value)
except ValueError:
a = float("nan")
return a | [
"def",
"get",
"(",
"tree",
",",
"name",
")",
":",
"if",
"name",
"in",
"tree",
":",
"value",
"=",
"tree",
"[",
"name",
"]",
"else",
":",
"return",
"float",
"(",
"\"nan\"",
")",
"try",
":",
"a",
"=",
"float",
"(",
"value",
")",
"except",
"ValueErro... | Return a float value attribute NAME from TREE. | [
"Return",
"a",
"float",
"value",
"attribute",
"NAME",
"from",
"TREE",
"."
] | python | train | 21.083333 |
tensorflow/tensor2tensor | tensor2tensor/envs/env_problem.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L656-L713 | def _generate_time_steps(self, trajectory_list):
"""A generator to yield single time-steps from a list of trajectories."""
for single_trajectory in trajectory_list:
assert isinstance(single_trajectory, trajectory.Trajectory)
# Skip writing trajectories that have only a single time-step -- this
... | [
"def",
"_generate_time_steps",
"(",
"self",
",",
"trajectory_list",
")",
":",
"for",
"single_trajectory",
"in",
"trajectory_list",
":",
"assert",
"isinstance",
"(",
"single_trajectory",
",",
"trajectory",
".",
"Trajectory",
")",
"# Skip writing trajectories that have only... | A generator to yield single time-steps from a list of trajectories. | [
"A",
"generator",
"to",
"yield",
"single",
"time",
"-",
"steps",
"from",
"a",
"list",
"of",
"trajectories",
"."
] | python | train | 37.5 |
watchforstock/evohome-client | evohomeclient2/zone.py | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/zone.py#L44-L63 | def set_schedule(self, zone_info):
"""Sets the schedule for this zone"""
# must only POST json, otherwise server API handler raises exceptions
try:
json.loads(zone_info)
except ValueError as error:
raise ValueError("zone_info must be valid JSON: ", error)
... | [
"def",
"set_schedule",
"(",
"self",
",",
"zone_info",
")",
":",
"# must only POST json, otherwise server API handler raises exceptions",
"try",
":",
"json",
".",
"loads",
"(",
"zone_info",
")",
"except",
"ValueError",
"as",
"error",
":",
"raise",
"ValueError",
"(",
... | Sets the schedule for this zone | [
"Sets",
"the",
"schedule",
"for",
"this",
"zone"
] | python | train | 37.15 |
saltstack/salt | salt/modules/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L851-L905 | def check_hash(path, file_hash):
'''
Check if a file matches the given hash string
Returns ``True`` if the hash matches, otherwise ``False``.
path
Path to a file local to the minion.
hash
The hash to check against the file specified in the ``path`` argument.
.. versioncha... | [
"def",
"check_hash",
"(",
"path",
",",
"file_hash",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"not",
"isinstance",
"(",
"file_hash",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"SaltInvocationError",
"("... | Check if a file matches the given hash string
Returns ``True`` if the hash matches, otherwise ``False``.
path
Path to a file local to the minion.
hash
The hash to check against the file specified in the ``path`` argument.
.. versionchanged:: 2016.11.4
For this and newer ... | [
"Check",
"if",
"a",
"file",
"matches",
"the",
"given",
"hash",
"string"
] | python | train | 32.836364 |
revelc/pyaccumulo | pyaccumulo/proxy/AccumuloProxy.py | https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L1231-L1240 | def getIteratorSetting(self, login, tableName, iteratorName, scope):
"""
Parameters:
- login
- tableName
- iteratorName
- scope
"""
self.send_getIteratorSetting(login, tableName, iteratorName, scope)
return self.recv_getIteratorSetting() | [
"def",
"getIteratorSetting",
"(",
"self",
",",
"login",
",",
"tableName",
",",
"iteratorName",
",",
"scope",
")",
":",
"self",
".",
"send_getIteratorSetting",
"(",
"login",
",",
"tableName",
",",
"iteratorName",
",",
"scope",
")",
"return",
"self",
".",
"rec... | Parameters:
- login
- tableName
- iteratorName
- scope | [
"Parameters",
":",
"-",
"login",
"-",
"tableName",
"-",
"iteratorName",
"-",
"scope"
] | python | train | 26.8 |
vaexio/vaex | packages/vaex-core/vaex/dataframe.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/dataframe.py#L625-L665 | def first(self, expression, order_expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None):
"""Return the first element of a binned `expression`, where the values each bin are sorted by `order_expression`.
Example:
>>> import vaex
... | [
"def",
"first",
"(",
"self",
",",
"expression",
",",
"order_expression",
",",
"binby",
"=",
"[",
"]",
",",
"limits",
"=",
"None",
",",
"shape",
"=",
"default_shape",
",",
"selection",
"=",
"False",
",",
"delay",
"=",
"False",
",",
"edges",
"=",
"False"... | Return the first element of a binned `expression`, where the values each bin are sorted by `order_expression`.
Example:
>>> import vaex
>>> df = vaex.example()
>>> df.first(df.x, df.y, shape=8)
>>> df.first(df.x, df.y, shape=8, binby=[df.y])
>>> df.first(df.x, df.y, sha... | [
"Return",
"the",
"first",
"element",
"of",
"a",
"binned",
"expression",
"where",
"the",
"values",
"each",
"bin",
"are",
"sorted",
"by",
"order_expression",
"."
] | python | test | 53.04878 |
lowandrew/OLCTools | spadespipeline/primer_finder_bbduk.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/primer_finder_bbduk.py#L166-L199 | def primers(self):
"""
Read in the primer file, and create a properly formatted output file that takes any degenerate bases
into account
"""
with open(self.formattedprimers, 'w') as formatted:
for record in SeqIO.parse(self.primerfile, 'fasta'):
# from... | [
"def",
"primers",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"formattedprimers",
",",
"'w'",
")",
"as",
"formatted",
":",
"for",
"record",
"in",
"SeqIO",
".",
"parse",
"(",
"self",
".",
"primerfile",
",",
"'fasta'",
")",
":",
"# from http... | Read in the primer file, and create a properly formatted output file that takes any degenerate bases
into account | [
"Read",
"in",
"the",
"primer",
"file",
"and",
"create",
"a",
"properly",
"formatted",
"output",
"file",
"that",
"takes",
"any",
"degenerate",
"bases",
"into",
"account"
] | python | train | 64.911765 |
saltstack/salt | salt/modules/djangomod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/djangomod.py#L283-L325 | def collectstatic(settings_module,
bin_env=None,
no_post_process=False,
ignore=None,
dry_run=False,
clear=False,
link=False,
no_default_ignore=False,
pythonpath=None,
... | [
"def",
"collectstatic",
"(",
"settings_module",
",",
"bin_env",
"=",
"None",
",",
"no_post_process",
"=",
"False",
",",
"ignore",
"=",
"None",
",",
"dry_run",
"=",
"False",
",",
"clear",
"=",
"False",
",",
"link",
"=",
"False",
",",
"no_default_ignore",
"=... | Collect static files from each of your applications into a single location
that can easily be served in production.
CLI Example:
.. code-block:: bash
salt '*' django.collectstatic <settings_module> | [
"Collect",
"static",
"files",
"from",
"each",
"of",
"your",
"applications",
"into",
"a",
"single",
"location",
"that",
"can",
"easily",
"be",
"served",
"in",
"production",
"."
] | python | train | 26.395349 |
ray-project/ray | python/ray/tune/trainable.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trainable.py#L275-L304 | def save_to_object(self):
"""Saves the current model state to a Python object. It also
saves to disk but does not return the checkpoint path.
Returns:
Object holding checkpoint data.
"""
tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir)
checkpoint... | [
"def",
"save_to_object",
"(",
"self",
")",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"\"save_to_object\"",
",",
"dir",
"=",
"self",
".",
"logdir",
")",
"checkpoint_prefix",
"=",
"self",
".",
"save",
"(",
"tmpdir",
")",
"data",
"=",
"{",
"}",
... | Saves the current model state to a Python object. It also
saves to disk but does not return the checkpoint path.
Returns:
Object holding checkpoint data. | [
"Saves",
"the",
"current",
"model",
"state",
"to",
"a",
"Python",
"object",
".",
"It",
"also",
"saves",
"to",
"disk",
"but",
"does",
"not",
"return",
"the",
"checkpoint",
"path",
"."
] | python | train | 34.333333 |
tensorflow/cleverhans | cleverhans/attacks/bapp.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L122-L159 | def generate_np(self, x, **kwargs):
"""
Generate adversarial images in a for loop.
:param y: An array of shape (n, nb_classes) for true labels.
:param y_target: An array of shape (n, nb_classes) for target labels.
Required for targeted attack.
:param image_target: An array of shape (n, **image ... | [
"def",
"generate_np",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"x_adv",
"=",
"[",
"]",
"if",
"'image_target'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'image_target'",
"]",
"is",
"not",
"None",
":",
"image_target",
"=",
"np",
".",
"co... | Generate adversarial images in a for loop.
:param y: An array of shape (n, nb_classes) for true labels.
:param y_target: An array of shape (n, nb_classes) for target labels.
Required for targeted attack.
:param image_target: An array of shape (n, **image shape) for initial
target images. Required f... | [
"Generate",
"adversarial",
"images",
"in",
"a",
"for",
"loop",
".",
":",
"param",
"y",
":",
"An",
"array",
"of",
"shape",
"(",
"n",
"nb_classes",
")",
"for",
"true",
"labels",
".",
":",
"param",
"y_target",
":",
"An",
"array",
"of",
"shape",
"(",
"n"... | python | train | 33.289474 |
concordusapps/alchemist | alchemist/db/operations/sql.py | https://github.com/concordusapps/alchemist/blob/822571366271b5dca0ac8bf41df988c6a3b61432/alchemist/db/operations/sql.py#L57-L73 | def init(**kwargs):
"""Initialize the specified names in the specified databases.
The general process is as follows:
- Ensure the database in question exists
- Ensure all tables exist in the database.
"""
# TODO: Iterate through all engines in name set.
database = kwargs.pop('database'... | [
"def",
"init",
"(",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Iterate through all engines in name set.",
"database",
"=",
"kwargs",
".",
"pop",
"(",
"'database'",
",",
"False",
")",
"if",
"database",
"and",
"not",
"database_exists",
"(",
"engine",
"[",
"'default'",... | Initialize the specified names in the specified databases.
The general process is as follows:
- Ensure the database in question exists
- Ensure all tables exist in the database. | [
"Initialize",
"the",
"specified",
"names",
"in",
"the",
"specified",
"databases",
"."
] | python | train | 38.411765 |
exa-analytics/exa | exa/util/nbvars.py | https://github.com/exa-analytics/exa/blob/40fb3c22b531d460dbc51e603de75b856cc28f0d/exa/util/nbvars.py#L39-L95 | def numbafy(fn, args, compiler="jit", **nbkws):
"""
Compile a string, sympy expression or symengine expression using numba.
Not all functions are supported by Python's numerical package (numpy). For
difficult cases, valid Python code (as string) may be more suitable than
symbolic expressions coming... | [
"def",
"numbafy",
"(",
"fn",
",",
"args",
",",
"compiler",
"=",
"\"jit\"",
",",
"*",
"*",
"nbkws",
")",
":",
"kwargs",
"=",
"{",
"}",
"# Numba kwargs to be updated by user",
"if",
"not",
"isinstance",
"(",
"args",
",",
"(",
"tuple",
",",
"list",
")",
"... | Compile a string, sympy expression or symengine expression using numba.
Not all functions are supported by Python's numerical package (numpy). For
difficult cases, valid Python code (as string) may be more suitable than
symbolic expressions coming from sympy, symengine, etc. When compiling
vectorized f... | [
"Compile",
"a",
"string",
"sympy",
"expression",
"or",
"symengine",
"expression",
"using",
"numba",
"."
] | python | train | 37.403509 |
dw/mitogen | mitogen/core.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/core.py#L2616-L2625 | def del_handler(self, handle):
"""
Remove the handle registered for `handle`
:raises KeyError:
The handle wasn't registered.
"""
_, _, _, respondent = self._handle_map.pop(handle)
if respondent:
self._handles_by_respondent[respondent].discard(hand... | [
"def",
"del_handler",
"(",
"self",
",",
"handle",
")",
":",
"_",
",",
"_",
",",
"_",
",",
"respondent",
"=",
"self",
".",
"_handle_map",
".",
"pop",
"(",
"handle",
")",
"if",
"respondent",
":",
"self",
".",
"_handles_by_respondent",
"[",
"respondent",
... | Remove the handle registered for `handle`
:raises KeyError:
The handle wasn't registered. | [
"Remove",
"the",
"handle",
"registered",
"for",
"handle"
] | python | train | 31.4 |
huge-success/sanic | sanic/server.py | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L230-L247 | def keep_alive_timeout_callback(self):
"""
Check if elapsed time since last response exceeds our configured
maximum keep alive timeout value and if so, close the transport
pipe and let the response writer handle the error.
:return: None
"""
time_elapsed = time() ... | [
"def",
"keep_alive_timeout_callback",
"(",
"self",
")",
":",
"time_elapsed",
"=",
"time",
"(",
")",
"-",
"self",
".",
"_last_response_time",
"if",
"time_elapsed",
"<",
"self",
".",
"keep_alive_timeout",
":",
"time_left",
"=",
"self",
".",
"keep_alive_timeout",
"... | Check if elapsed time since last response exceeds our configured
maximum keep alive timeout value and if so, close the transport
pipe and let the response writer handle the error.
:return: None | [
"Check",
"if",
"elapsed",
"time",
"since",
"last",
"response",
"exceeds",
"our",
"configured",
"maximum",
"keep",
"alive",
"timeout",
"value",
"and",
"if",
"so",
"close",
"the",
"transport",
"pipe",
"and",
"let",
"the",
"response",
"writer",
"handle",
"the",
... | python | train | 40.888889 |
allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/span_utils.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L20-L66 | def enumerate_spans(sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]:
"""
Given a sentence, return all token spans w... | [
"def",
"enumerate_spans",
"(",
"sentence",
":",
"List",
"[",
"T",
"]",
",",
"offset",
":",
"int",
"=",
"0",
",",
"max_span_width",
":",
"int",
"=",
"None",
",",
"min_span_width",
":",
"int",
"=",
"1",
",",
"filter_function",
":",
"Callable",
"[",
"[",
... | Given a sentence, return all token spans within the sentence. Spans are `inclusive`.
Additionally, you can provide a maximum and minimum span width, which will be used
to exclude spans outside of this range.
Finally, you can provide a function mapping ``List[T] -> bool``, which will
be applied to every... | [
"Given",
"a",
"sentence",
"return",
"all",
"token",
"spans",
"within",
"the",
"sentence",
".",
"Spans",
"are",
"inclusive",
".",
"Additionally",
"you",
"can",
"provide",
"a",
"maximum",
"and",
"minimum",
"span",
"width",
"which",
"will",
"be",
"used",
"to",
... | python | train | 52 |
pkgw/pwkit | pwkit/dulk_models.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/dulk_models.py#L358-L399 | def calc_synch_snu_ujy(b, ne, delta, sinth, width, elongation, dist, ghz, E0=1.):
"""Calculate a flux density from pure gyrosynchrotron emission.
This combines Dulk (1985) equations 40 and 41, which are fitting functions
assuming a power-law electron population, with standard radiative transfer
through... | [
"def",
"calc_synch_snu_ujy",
"(",
"b",
",",
"ne",
",",
"delta",
",",
"sinth",
",",
"width",
",",
"elongation",
",",
"dist",
",",
"ghz",
",",
"E0",
"=",
"1.",
")",
":",
"hz",
"=",
"ghz",
"*",
"1e9",
"eta",
"=",
"calc_synch_eta",
"(",
"b",
",",
"ne... | Calculate a flux density from pure gyrosynchrotron emission.
This combines Dulk (1985) equations 40 and 41, which are fitting functions
assuming a power-law electron population, with standard radiative transfer
through a uniform medium. Arguments are:
b
Magnetic field strength in Gauss
ne
... | [
"Calculate",
"a",
"flux",
"density",
"from",
"pure",
"gyrosynchrotron",
"emission",
"."
] | python | train | 41.571429 |
google/grr | grr/server/grr_response_server/flows/general/collectors.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flows/general/collectors.py#L1098-L1114 | def GetArtifactsForCollection(os_name, artifact_list):
"""Wrapper for the ArtifactArranger.
Extend the artifact list by dependencies and sort the artifacts to resolve the
dependencies.
Args:
os_name: String specifying the OS name.
artifact_list: List of requested artifact names.
Returns:
A list... | [
"def",
"GetArtifactsForCollection",
"(",
"os_name",
",",
"artifact_list",
")",
":",
"artifact_arranger",
"=",
"ArtifactArranger",
"(",
"os_name",
",",
"artifact_list",
")",
"artifact_names",
"=",
"artifact_arranger",
".",
"GetArtifactsInProperOrder",
"(",
")",
"return",... | Wrapper for the ArtifactArranger.
Extend the artifact list by dependencies and sort the artifacts to resolve the
dependencies.
Args:
os_name: String specifying the OS name.
artifact_list: List of requested artifact names.
Returns:
A list of artifacts such that if they are collected in the given o... | [
"Wrapper",
"for",
"the",
"ArtifactArranger",
"."
] | python | train | 33.235294 |
materialsproject/pymatgen | pymatgen/io/abinit/pseudos.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/pseudos.py#L632-L647 | def _int_from_str(string):
"""
Convert string into integer
Raise:
TypeError if string is not a valid integer
"""
float_num = float(string)
int_num = int(float_num)
if float_num == int_num:
return int_num
else:
# Needed to handle pseudos with fractional charge
... | [
"def",
"_int_from_str",
"(",
"string",
")",
":",
"float_num",
"=",
"float",
"(",
"string",
")",
"int_num",
"=",
"int",
"(",
"float_num",
")",
"if",
"float_num",
"==",
"int_num",
":",
"return",
"int_num",
"else",
":",
"# Needed to handle pseudos with fractional c... | Convert string into integer
Raise:
TypeError if string is not a valid integer | [
"Convert",
"string",
"into",
"integer"
] | python | train | 27.5 |
ascribe/pyspool | spool/spool.py | https://github.com/ascribe/pyspool/blob/f8b10df1e7d2ea7950dde433c1cb6d5225112f4f/spool/spool.py#L420-L449 | def refill(self, from_address, to_address, nfees, ntokens, password, min_confirmations=6, sync=False):
"""
Refill wallets with the necessary fuel to perform spool transactions
Args:
from_address (Tuple[str]): Federation wallet address. Fuels the wallets with tokens and fees. All tra... | [
"def",
"refill",
"(",
"self",
",",
"from_address",
",",
"to_address",
",",
"nfees",
",",
"ntokens",
",",
"password",
",",
"min_confirmations",
"=",
"6",
",",
"sync",
"=",
"False",
")",
":",
"path",
",",
"from_address",
"=",
"from_address",
"verb",
"=",
"... | Refill wallets with the necessary fuel to perform spool transactions
Args:
from_address (Tuple[str]): Federation wallet address. Fuels the wallets with tokens and fees. All transactions to wallets
holding a particular piece should come from the Federation wallet
to_addre... | [
"Refill",
"wallets",
"with",
"the",
"necessary",
"fuel",
"to",
"perform",
"spool",
"transactions"
] | python | train | 62.733333 |
glue-viz/echo | echo/core.py | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/core.py#L325-L331 | def iter_callback_properties(self):
"""
Iterator to loop over all callback properties.
"""
for name in dir(self):
if self.is_callback_property(name):
yield name, getattr(type(self), name) | [
"def",
"iter_callback_properties",
"(",
"self",
")",
":",
"for",
"name",
"in",
"dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_callback_property",
"(",
"name",
")",
":",
"yield",
"name",
",",
"getattr",
"(",
"type",
"(",
"self",
")",
",",
"name",
... | Iterator to loop over all callback properties. | [
"Iterator",
"to",
"loop",
"over",
"all",
"callback",
"properties",
"."
] | python | train | 34.428571 |
aerogear/digger-build-cli | digger/builds/gradle.py | https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/builds/gradle.py#L67-L83 | def sign(self, storepass=None, keypass=None, keystore=None, apk=None, alias=None, name='app'):
"""
Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default.
:param storepass(str): keystore file storepass
:param keypass(str): keystore file... | [
"def",
"sign",
"(",
"self",
",",
"storepass",
"=",
"None",
",",
"keypass",
"=",
"None",
",",
"keystore",
"=",
"None",
",",
"apk",
"=",
"None",
",",
"alias",
"=",
"None",
",",
"name",
"=",
"'app'",
")",
":",
"self",
".",
"src_folder",
"=",
"self",
... | Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default.
:param storepass(str): keystore file storepass
:param keypass(str): keystore file keypass
:param keystore(str): keystore file path
:param apk(str): apk file path to be signed
:... | [
"Signs",
"(",
"jarsign",
"and",
"zipalign",
")",
"a",
"target",
"apk",
"file",
"based",
"on",
"keystore",
"information",
"uses",
"default",
"debug",
"keystore",
"file",
"by",
"default",
"."
] | python | train | 53.823529 |
pandas-dev/pandas | pandas/core/ops.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/ops.py#L307-L356 | def _get_opstr(op, cls):
"""
Find the operation string, if any, to pass to numexpr for this
operation.
Parameters
----------
op : binary operator
cls : class
Returns
-------
op_str : string or None
"""
# numexpr is available for non-sparse classes
subtyp = getattr(c... | [
"def",
"_get_opstr",
"(",
"op",
",",
"cls",
")",
":",
"# numexpr is available for non-sparse classes",
"subtyp",
"=",
"getattr",
"(",
"cls",
",",
"'_subtyp'",
",",
"''",
")",
"use_numexpr",
"=",
"'sparse'",
"not",
"in",
"subtyp",
"if",
"not",
"use_numexpr",
":... | Find the operation string, if any, to pass to numexpr for this
operation.
Parameters
----------
op : binary operator
cls : class
Returns
-------
op_str : string or None | [
"Find",
"the",
"operation",
"string",
"if",
"any",
"to",
"pass",
"to",
"numexpr",
"for",
"this",
"operation",
"."
] | python | train | 25.8 |
tsroten/dragonmapper | dragonmapper/transcriptions.py | https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L451-L461 | def to_ipa(s):
"""Convert *s* to IPA."""
identity = identify(s)
if identity == IPA:
return s
elif identity == PINYIN:
return pinyin_to_ipa(s)
elif identity == ZHUYIN:
return zhuyin_to_ipa(s)
else:
raise ValueError("String is not a valid Chinese transcription.") | [
"def",
"to_ipa",
"(",
"s",
")",
":",
"identity",
"=",
"identify",
"(",
"s",
")",
"if",
"identity",
"==",
"IPA",
":",
"return",
"s",
"elif",
"identity",
"==",
"PINYIN",
":",
"return",
"pinyin_to_ipa",
"(",
"s",
")",
"elif",
"identity",
"==",
"ZHUYIN",
... | Convert *s* to IPA. | [
"Convert",
"*",
"s",
"*",
"to",
"IPA",
"."
] | python | train | 27.909091 |
unt-libraries/pypairtree | pypairtree/pairtree.py | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L104-L150 | def sanitizeString(name):
"""Cleans string in preparation for splitting for use as a pairtree
identifier."""
newString = name
# string cleaning, pass 1
replaceTable = [
('^', '^5e'), # we need to do this one first
('"', '^22'),
('<', '^3c'),
('?', '^3f'),
('*... | [
"def",
"sanitizeString",
"(",
"name",
")",
":",
"newString",
"=",
"name",
"# string cleaning, pass 1",
"replaceTable",
"=",
"[",
"(",
"'^'",
",",
"'^5e'",
")",
",",
"# we need to do this one first",
"(",
"'\"'",
",",
"'^22'",
")",
",",
"(",
"'<'",
",",
"'^3c... | Cleans string in preparation for splitting for use as a pairtree
identifier. | [
"Cleans",
"string",
"in",
"preparation",
"for",
"splitting",
"for",
"use",
"as",
"a",
"pairtree",
"identifier",
"."
] | python | train | 27.531915 |
gc3-uzh-ch/elasticluster | elasticluster/providers/azure_provider.py | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/azure_provider.py#L428-L443 | def is_instance_running(self, instance_id):
"""
Check if the instance is up and running.
:param str instance_id: instance identifier
:return: bool - True if running, False otherwise
"""
self._init_az_api()
# Here, it's always better if we update the instance.
... | [
"def",
"is_instance_running",
"(",
"self",
",",
"instance_id",
")",
":",
"self",
".",
"_init_az_api",
"(",
")",
"# Here, it's always better if we update the instance.",
"vm",
"=",
"self",
".",
"_get_vm",
"(",
"instance_id",
",",
"force_reload",
"=",
"True",
")",
"... | Check if the instance is up and running.
:param str instance_id: instance identifier
:return: bool - True if running, False otherwise | [
"Check",
"if",
"the",
"instance",
"is",
"up",
"and",
"running",
"."
] | python | train | 40.9375 |
thombashi/pytablewriter | pytablewriter/writer/_table_writer.py | https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/_table_writer.py#L654-L686 | def from_series(self, series, add_index_column=True):
"""
Set tabular attributes to the writer from :py:class:`pandas.Series`.
Following attributes are set by the method:
- :py:attr:`~.headers`
- :py:attr:`~.value_matrix`
- :py:attr:`~.type_hints`
Ar... | [
"def",
"from_series",
"(",
"self",
",",
"series",
",",
"add_index_column",
"=",
"True",
")",
":",
"if",
"series",
".",
"name",
":",
"self",
".",
"headers",
"=",
"[",
"series",
".",
"name",
"]",
"else",
":",
"self",
".",
"headers",
"=",
"[",
"\"value\... | Set tabular attributes to the writer from :py:class:`pandas.Series`.
Following attributes are set by the method:
- :py:attr:`~.headers`
- :py:attr:`~.value_matrix`
- :py:attr:`~.type_hints`
Args:
series(pandas.Series):
Input pandas.Series... | [
"Set",
"tabular",
"attributes",
"to",
"the",
"writer",
"from",
":",
"py",
":",
"class",
":",
"pandas",
".",
"Series",
".",
"Following",
"attributes",
"are",
"set",
"by",
"the",
"method",
":"
] | python | train | 34.121212 |
bcbio/bcbio-nextgen | bcbio/distributed/transaction.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/transaction.py#L102-L127 | def _move_file_with_sizecheck(tx_file, final_file):
"""Move transaction file to final location,
with size checks avoiding failed transfers.
Creates an empty file with '.bcbiotmp' extention in the destination
location, which serves as a flag. If a file like that is present,
it means that... | [
"def",
"_move_file_with_sizecheck",
"(",
"tx_file",
",",
"final_file",
")",
":",
"#logger.debug(\"Moving %s to %s\" % (tx_file, final_file))",
"tmp_file",
"=",
"final_file",
"+",
"\".bcbiotmp\"",
"open",
"(",
"tmp_file",
",",
"'wb'",
")",
".",
"close",
"(",
")",
"want... | Move transaction file to final location,
with size checks avoiding failed transfers.
Creates an empty file with '.bcbiotmp' extention in the destination
location, which serves as a flag. If a file like that is present,
it means that transaction didn't finish successfully. | [
"Move",
"transaction",
"file",
"to",
"final",
"location",
"with",
"size",
"checks",
"avoiding",
"failed",
"transfers",
"."
] | python | train | 38.615385 |
elifesciences/elife-tools | elifetools/utils.py | https://github.com/elifesciences/elife-tools/blob/4b9e38cbe485c61a4ed7cbd8970c6b318334fd86/elifetools/utils.py#L460-L478 | def text_to_title(value):
"""when a title is required, generate one from the value"""
title = None
if not value:
return title
words = value.split(" ")
keep_words = []
for word in words:
if word.endswith(".") or word.endswith(":"):
keep_words.append(word)
i... | [
"def",
"text_to_title",
"(",
"value",
")",
":",
"title",
"=",
"None",
"if",
"not",
"value",
":",
"return",
"title",
"words",
"=",
"value",
".",
"split",
"(",
"\" \"",
")",
"keep_words",
"=",
"[",
"]",
"for",
"word",
"in",
"words",
":",
"if",
"word",
... | when a title is required, generate one from the value | [
"when",
"a",
"title",
"is",
"required",
"generate",
"one",
"from",
"the",
"value"
] | python | train | 31.789474 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.