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 |
|---|---|---|---|---|---|---|---|---|---|
LudovicRousseau/pyscard | smartcard/wx/ReaderToolbar.py | https://github.com/LudovicRousseau/pyscard/blob/62e675028086c75656444cc21d563d9f08ebf8e7/smartcard/wx/ReaderToolbar.py#L45-L56 | def update(self, observable, handlers):
"""Toolbar ReaderObserver callback that is notified when
readers are added or removed."""
addedreaders, removedreaders = handlers
for reader in addedreaders:
item = self.Append(str(reader))
self.SetClientData(item, reader)
... | [
"def",
"update",
"(",
"self",
",",
"observable",
",",
"handlers",
")",
":",
"addedreaders",
",",
"removedreaders",
"=",
"handlers",
"for",
"reader",
"in",
"addedreaders",
":",
"item",
"=",
"self",
".",
"Append",
"(",
"str",
"(",
"reader",
")",
")",
"self... | Toolbar ReaderObserver callback that is notified when
readers are added or removed. | [
"Toolbar",
"ReaderObserver",
"callback",
"that",
"is",
"notified",
"when",
"readers",
"are",
"added",
"or",
"removed",
"."
] | python | train | 42 |
maroba/findiff | findiff/coefs.py | https://github.com/maroba/findiff/blob/5d1ccfa966ce2bd556b4425583f8b9bbcbf183ac/findiff/coefs.py#L131-L136 | def _build_rhs(p, q, deriv):
"""The right hand side of the equation system matrix"""
b = [0 for _ in range(p+q+1)]
b[deriv] = math.factorial(deriv)
return np.array(b) | [
"def",
"_build_rhs",
"(",
"p",
",",
"q",
",",
"deriv",
")",
":",
"b",
"=",
"[",
"0",
"for",
"_",
"in",
"range",
"(",
"p",
"+",
"q",
"+",
"1",
")",
"]",
"b",
"[",
"deriv",
"]",
"=",
"math",
".",
"factorial",
"(",
"deriv",
")",
"return",
"np"... | The right hand side of the equation system matrix | [
"The",
"right",
"hand",
"side",
"of",
"the",
"equation",
"system",
"matrix"
] | python | train | 29.666667 |
orbingol/NURBS-Python | geomdl/_exchange.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_exchange.py#L102-L150 | def import_surf_mesh(file_name):
""" Generates a NURBS surface object from a mesh file.
:param file_name: input mesh file
:type file_name: str
:return: a NURBS surface
:rtype: NURBS.Surface
"""
raw_content = read_file(file_name)
raw_content = raw_content.split("\n")
content = []
... | [
"def",
"import_surf_mesh",
"(",
"file_name",
")",
":",
"raw_content",
"=",
"read_file",
"(",
"file_name",
")",
"raw_content",
"=",
"raw_content",
".",
"split",
"(",
"\"\\n\"",
")",
"content",
"=",
"[",
"]",
"for",
"rc",
"in",
"raw_content",
":",
"temp",
"=... | Generates a NURBS surface object from a mesh file.
:param file_name: input mesh file
:type file_name: str
:return: a NURBS surface
:rtype: NURBS.Surface | [
"Generates",
"a",
"NURBS",
"surface",
"object",
"from",
"a",
"mesh",
"file",
"."
] | python | train | 32.428571 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L9165-L9182 | def attitude_quaternion_encode(self, time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed):
'''
The attitude in the aeronautical frame (right-handed, Z-down, X-front,
Y-right), expressed as quaternion. Quaternion order is
w, x, y, z and a zero rot... | [
"def",
"attitude_quaternion_encode",
"(",
"self",
",",
"time_boot_ms",
",",
"q1",
",",
"q2",
",",
"q3",
",",
"q4",
",",
"rollspeed",
",",
"pitchspeed",
",",
"yawspeed",
")",
":",
"return",
"MAVLink_attitude_quaternion_message",
"(",
"time_boot_ms",
",",
"q1",
... | The attitude in the aeronautical frame (right-handed, Z-down, X-front,
Y-right), expressed as quaternion. Quaternion order is
w, x, y, z and a zero rotation would be expressed as
(1 0 0 0).
time_boot_ms : Timestamp (milliseconds since system ... | [
"The",
"attitude",
"in",
"the",
"aeronautical",
"frame",
"(",
"right",
"-",
"handed",
"Z",
"-",
"down",
"X",
"-",
"front",
"Y",
"-",
"right",
")",
"expressed",
"as",
"quaternion",
".",
"Quaternion",
"order",
"is",
"w",
"x",
"y",
"z",
"and",
"a",
"zer... | python | train | 68.444444 |
sbg/sevenbridges-python | sevenbridges/models/marker.py | https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/marker.py#L96-L117 | def save(self, inplace=True):
"""
Saves all modification to the marker on the server.
:param inplace Apply edits on the current instance or get a new one.
:return: Marker instance.
"""
modified_data = self._modified_data()
if bool(modified_data):
extra... | [
"def",
"save",
"(",
"self",
",",
"inplace",
"=",
"True",
")",
":",
"modified_data",
"=",
"self",
".",
"_modified_data",
"(",
")",
"if",
"bool",
"(",
"modified_data",
")",
":",
"extra",
"=",
"{",
"'resource'",
":",
"self",
".",
"__class__",
".",
"__name... | Saves all modification to the marker on the server.
:param inplace Apply edits on the current instance or get a new one.
:return: Marker instance. | [
"Saves",
"all",
"modification",
"to",
"the",
"marker",
"on",
"the",
"server",
".",
":",
"param",
"inplace",
"Apply",
"edits",
"on",
"the",
"current",
"instance",
"or",
"get",
"a",
"new",
"one",
".",
":",
"return",
":",
"Marker",
"instance",
"."
] | python | train | 37.454545 |
ray-project/ray | python/ray/rllib/optimizers/multi_gpu_impl.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/optimizers/multi_gpu_impl.py#L118-L225 | def load_data(self, sess, inputs, state_inputs):
"""Bulk loads the specified inputs into device memory.
The shape of the inputs must conform to the shapes of the input
placeholders this optimizer was constructed with.
The data is split equally across all the devices. If the data is not... | [
"def",
"load_data",
"(",
"self",
",",
"sess",
",",
"inputs",
",",
"state_inputs",
")",
":",
"if",
"log_once",
"(",
"\"load_data\"",
")",
":",
"logger",
".",
"info",
"(",
"\"Training on concatenated sample batches:\\n\\n{}\\n\"",
".",
"format",
"(",
"summarize",
... | Bulk loads the specified inputs into device memory.
The shape of the inputs must conform to the shapes of the input
placeholders this optimizer was constructed with.
The data is split equally across all the devices. If the data is not
evenly divisible by the batch size, excess data wil... | [
"Bulk",
"loads",
"the",
"specified",
"inputs",
"into",
"device",
"memory",
"."
] | python | train | 44.305556 |
AASHE/django-constant-contact | django_constant_contact/models.py | https://github.com/AASHE/django-constant-contact/blob/2a37f00ee62531804414b35637d0dad5992d5822/django_constant_contact/models.py#L107-L162 | def update_email_marketing_campaign(self, email_marketing_campaign,
name, email_content, from_email,
from_name, reply_to_email, subject,
text_content, address,
... | [
"def",
"update_email_marketing_campaign",
"(",
"self",
",",
"email_marketing_campaign",
",",
"name",
",",
"email_content",
",",
"from_email",
",",
"from_name",
",",
"reply_to_email",
",",
"subject",
",",
"text_content",
",",
"address",
",",
"is_view_as_webpage_enabled",... | Update a Constant Contact email marketing campaign.
Returns the updated EmailMarketingCampaign object. | [
"Update",
"a",
"Constant",
"Contact",
"email",
"marketing",
"campaign",
".",
"Returns",
"the",
"updated",
"EmailMarketingCampaign",
"object",
"."
] | python | train | 47.125 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L185-L201 | def get_process_params(xmldoc, program, param, require_unique_program = True):
"""
Return a list of the values stored in the process_params table for
params named param for the program(s) named program. The values
are returned as Python native types, not as the strings appearing
in the XML document. If require_u... | [
"def",
"get_process_params",
"(",
"xmldoc",
",",
"program",
",",
"param",
",",
"require_unique_program",
"=",
"True",
")",
":",
"process_ids",
"=",
"lsctables",
".",
"ProcessTable",
".",
"get_table",
"(",
"xmldoc",
")",
".",
"get_ids_by_program",
"(",
"program",... | Return a list of the values stored in the process_params table for
params named param for the program(s) named program. The values
are returned as Python native types, not as the strings appearing
in the XML document. If require_unique_program is True (default),
then the document must contain exactly one program ... | [
"Return",
"a",
"list",
"of",
"the",
"values",
"stored",
"in",
"the",
"process_params",
"table",
"for",
"params",
"named",
"param",
"for",
"the",
"program",
"(",
"s",
")",
"named",
"program",
".",
"The",
"values",
"are",
"returned",
"as",
"Python",
"native"... | python | train | 63.294118 |
CalebBell/thermo | thermo/volume.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/volume.py#L2360-L2378 | def load_all_methods(self):
r'''Method which picks out coefficients for the specified chemical
from the various dictionaries and DataFrames storing it. All data is
stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,
and :obj:`all_methods` as a set of methods for which t... | [
"def",
"load_all_methods",
"(",
"self",
")",
":",
"methods",
"=",
"[",
"]",
"if",
"self",
".",
"CASRN",
"in",
"CRC_inorg_s_const_data",
".",
"index",
":",
"methods",
".",
"append",
"(",
"CRC_INORG_S",
")",
"self",
".",
"CRC_INORG_S_Vm",
"=",
"float",
"(",
... | r'''Method which picks out coefficients for the specified chemical
from the various dictionaries and DataFrames storing it. All data is
stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,
and :obj:`all_methods` as a set of methods for which the data exists for.
Called ... | [
"r",
"Method",
"which",
"picks",
"out",
"coefficients",
"for",
"the",
"specified",
"chemical",
"from",
"the",
"various",
"dictionaries",
"and",
"DataFrames",
"storing",
"it",
".",
"All",
"data",
"is",
"stored",
"as",
"attributes",
".",
"This",
"method",
"also"... | python | valid | 52 |
aewallin/allantools | examples/noise-color_and_PSD.py | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/examples/noise-color_and_PSD.py#L7-L18 | def many_psds(k=2,fs=1.0, b0=1.0, N=1024):
""" compute average of many PSDs """
psd=[]
for j in range(k):
print j
x = noise.white(N=2*4096,b0=b0,fs=fs)
f, tmp = noise.numpy_psd(x,fs)
if j==0:
psd = tmp
else:
psd = psd + tmp
return f, psd/k | [
"def",
"many_psds",
"(",
"k",
"=",
"2",
",",
"fs",
"=",
"1.0",
",",
"b0",
"=",
"1.0",
",",
"N",
"=",
"1024",
")",
":",
"psd",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"k",
")",
":",
"print",
"j",
"x",
"=",
"noise",
".",
"white",
"("... | compute average of many PSDs | [
"compute",
"average",
"of",
"many",
"PSDs"
] | python | train | 25.666667 |
Terrance/SkPy | skpy/conn.py | https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L877-L885 | def ping(self, timeout=12):
"""
Send a keep-alive request for the endpoint.
Args:
timeout (int): maximum amount of time for the endpoint to stay active
"""
self.conn("POST", "{0}/users/ME/endpoints/{1}/active".format(self.conn.msgsHost, self.id),
au... | [
"def",
"ping",
"(",
"self",
",",
"timeout",
"=",
"12",
")",
":",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/users/ME/endpoints/{1}/active\"",
".",
"format",
"(",
"self",
".",
"conn",
".",
"msgsHost",
",",
"self",
".",
"id",
")",
",",
"auth",
"="... | Send a keep-alive request for the endpoint.
Args:
timeout (int): maximum amount of time for the endpoint to stay active | [
"Send",
"a",
"keep",
"-",
"alive",
"request",
"for",
"the",
"endpoint",
"."
] | python | test | 41.333333 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L80-L90 | def jarFlags(target, source, env, for_signature):
"""If we have a manifest, make sure that the 'm'
flag is specified."""
jarflags = env.subst('$JARFLAGS', target=target, source=source)
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
... | [
"def",
"jarFlags",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"jarflags",
"=",
"env",
".",
"subst",
"(",
"'$JARFLAGS'",
",",
"target",
"=",
"target",
",",
"source",
"=",
"source",
")",
"for",
"src",
"in",
"source",
":",
... | If we have a manifest, make sure that the 'm'
flag is specified. | [
"If",
"we",
"have",
"a",
"manifest",
"make",
"sure",
"that",
"the",
"m",
"flag",
"is",
"specified",
"."
] | python | train | 37.454545 |
stevelittlefish/littlefish | littlefish/colourutil.py | https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/colourutil.py#L115-L143 | def blend_html_colour_to_white(html_colour, alpha):
"""
:param html_colour: Colour string like FF552B or #334455
:param alpha: Alpha value
:return: Html colour alpha blended onto white
"""
html_colour = html_colour.upper()
has_hash = False
if html_colour[0] == '#':
has_hash = Tru... | [
"def",
"blend_html_colour_to_white",
"(",
"html_colour",
",",
"alpha",
")",
":",
"html_colour",
"=",
"html_colour",
".",
"upper",
"(",
")",
"has_hash",
"=",
"False",
"if",
"html_colour",
"[",
"0",
"]",
"==",
"'#'",
":",
"has_hash",
"=",
"True",
"html_colour"... | :param html_colour: Colour string like FF552B or #334455
:param alpha: Alpha value
:return: Html colour alpha blended onto white | [
":",
"param",
"html_colour",
":",
"Colour",
"string",
"like",
"FF552B",
"or",
"#334455",
":",
"param",
"alpha",
":",
"Alpha",
"value",
":",
"return",
":",
"Html",
"colour",
"alpha",
"blended",
"onto",
"white"
] | python | test | 25.103448 |
samjabrahams/anchorhub | anchorhub/builtin/github/writer.py | https://github.com/samjabrahams/anchorhub/blob/5ade359b08297d4003a5f477389c01de9e634b54/anchorhub/builtin/github/writer.py#L12-L44 | def make_github_markdown_writer(opts):
"""
Creates a Writer object used for parsing and writing Markdown files with
a GitHub style anchor transformation
opts is a namespace object containing runtime options. It should
generally include the following attributes:
* 'open': a string correspondi... | [
"def",
"make_github_markdown_writer",
"(",
"opts",
")",
":",
"assert",
"hasattr",
"(",
"opts",
",",
"'wrapper_regex'",
")",
"atx",
"=",
"MarkdownATXWriterStrategy",
"(",
"opts",
",",
"'ATX headers'",
")",
"setext",
"=",
"MarkdownSetextWriterStrategy",
"(",
"opts",
... | Creates a Writer object used for parsing and writing Markdown files with
a GitHub style anchor transformation
opts is a namespace object containing runtime options. It should
generally include the following attributes:
* 'open': a string corresponding to the opening portion of the wrapper
... | [
"Creates",
"a",
"Writer",
"object",
"used",
"for",
"parsing",
"and",
"writing",
"Markdown",
"files",
"with",
"a",
"GitHub",
"style",
"anchor",
"transformation"
] | python | train | 45.818182 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L244-L265 | def gen_chunks(self, gen):
"""Generates byte chunks of a given size.
Takes a bytes generator and yields chunks of a maximum of
``chunk_size`` bytes.
Parameters
----------
gen : generator
The bytes generator that produces the bytes
"""
for dat... | [
"def",
"gen_chunks",
"(",
"self",
",",
"gen",
")",
":",
"for",
"data",
"in",
"gen",
":",
"size",
"=",
"len",
"(",
"data",
")",
"if",
"size",
"<",
"self",
".",
"chunk_size",
":",
"yield",
"data",
"else",
":",
"mv",
"=",
"buffer",
"(",
"data",
")",... | Generates byte chunks of a given size.
Takes a bytes generator and yields chunks of a maximum of
``chunk_size`` bytes.
Parameters
----------
gen : generator
The bytes generator that produces the bytes | [
"Generates",
"byte",
"chunks",
"of",
"a",
"given",
"size",
"."
] | python | train | 30.090909 |
intuition-io/intuition | intuition/data/universe.py | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/universe.py#L44-L49 | def _load_market_scheme(self):
''' Load market yaml description '''
try:
self.scheme = yaml.load(open(self.scheme_path, 'r'))
except Exception, error:
raise LoadMarketSchemeFailed(reason=error) | [
"def",
"_load_market_scheme",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"scheme",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"self",
".",
"scheme_path",
",",
"'r'",
")",
")",
"except",
"Exception",
",",
"error",
":",
"raise",
"LoadMarketSchemeFail... | Load market yaml description | [
"Load",
"market",
"yaml",
"description"
] | python | train | 39.333333 |
lehins/python-wepay | wepay/calls/checkout.py | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/checkout.py#L165-L187 | def __capture(self, checkout_id, **kwargs):
"""Call documentation: `/checkout/capture
<https://www.wepay.com/developer/reference/checkout#capture>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``... | [
"def",
"__capture",
"(",
"self",
",",
"checkout_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'checkout_id'",
":",
"checkout_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__capture",
",",
"params",
",",
"kwargs",
")"
] | Call documentation: `/checkout/capture
<https://www.wepay.com/developer/reference/checkout#capture>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
p... | [
"Call",
"documentation",
":",
"/",
"checkout",
"/",
"capture",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"checkout#capture",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str"... | python | train | 36.173913 |
3DLIRIOUS/MeshLabXML | meshlabxml/util.py | https://github.com/3DLIRIOUS/MeshLabXML/blob/177cce21e92baca500f56a932d66bd9a33257af8/meshlabxml/util.py#L90-L104 | def make_list(var, num_terms=1):
""" Make a variable a list if it is not already
If variable is not a list it will make it a list of the correct length with
all terms identical.
"""
if not isinstance(var, list):
if isinstance(var, tuple):
var = list(var)
else:
... | [
"def",
"make_list",
"(",
"var",
",",
"num_terms",
"=",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"var",
",",
"list",
")",
":",
"if",
"isinstance",
"(",
"var",
",",
"tuple",
")",
":",
"var",
"=",
"list",
"(",
"var",
")",
"else",
":",
"var",
... | Make a variable a list if it is not already
If variable is not a list it will make it a list of the correct length with
all terms identical. | [
"Make",
"a",
"variable",
"a",
"list",
"if",
"it",
"is",
"not",
"already"
] | python | test | 28.933333 |
rkhleics/wagtailmenus | wagtailmenus/templatetags/menu_tags.py | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/templatetags/menu_tags.py#L84-L113 | def section_menu(
context, show_section_root=True, show_multiple_levels=True,
apply_active_classes=True, allow_repeating_parents=True,
max_levels=settings.DEFAULT_SECTION_MENU_MAX_LEVELS,
template='', sub_menu_template='', sub_menu_templates=None,
use_specific=settings.DEFAULT_SECTION_MENU_USE_SPECI... | [
"def",
"section_menu",
"(",
"context",
",",
"show_section_root",
"=",
"True",
",",
"show_multiple_levels",
"=",
"True",
",",
"apply_active_classes",
"=",
"True",
",",
"allow_repeating_parents",
"=",
"True",
",",
"max_levels",
"=",
"settings",
".",
"DEFAULT_SECTION_M... | Render a section menu for the current section. | [
"Render",
"a",
"section",
"menu",
"for",
"the",
"current",
"section",
"."
] | python | train | 40.766667 |
orbingol/NURBS-Python | geomdl/exchange.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L303-L336 | def export_yaml(obj, file_name):
""" Exports curves and surfaces in YAML format.
.. note::
Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package.
YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_
as a way to input sha... | [
"def",
"export_yaml",
"(",
"obj",
",",
"file_name",
")",
":",
"def",
"callback",
"(",
"data",
")",
":",
"# Ref: https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string",
"stream",
"=",
"StringIO",
"(",
")",
"yaml",
"=",
"YAML",
"(",
")",
"yaml"... | Exports curves and surfaces in YAML format.
.. note::
Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package.
YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_
as a way to input shape data from the command line.
:para... | [
"Exports",
"curves",
"and",
"surfaces",
"in",
"YAML",
"format",
"."
] | python | train | 35.117647 |
PyHDI/Pyverilog | pyverilog/vparser/parser.py | https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L2177-L2180 | def p_single_statement_systemcall(self, p):
'single_statement : systemcall SEMICOLON'
p[0] = SingleStatement(p[1], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_single_statement_systemcall",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"SingleStatement",
"(",
"p",
"[",
"1",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
... | single_statement : systemcall SEMICOLON | [
"single_statement",
":",
"systemcall",
"SEMICOLON"
] | python | train | 46 |
StackStorm/pybind | pybind/slxos/v17s_1_02/routing_system/evpn_config/evpn/evpn_instance/vlan/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/evpn_config/evpn/evpn_instance/vlan/__init__.py#L94-L115 | def _set_vlan_add(self, v, load=False):
"""
Setter method for vlan_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/vlan/vlan_add (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan_add is considered as a private
method. Back... | [
"def",
"_set_vlan_add",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base"... | Setter method for vlan_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/vlan/vlan_add (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan_add is considered as a private
method. Backends looking to populate this variable should
do... | [
"Setter",
"method",
"for",
"vlan_add",
"mapped",
"from",
"YANG",
"variable",
"/",
"routing_system",
"/",
"evpn_config",
"/",
"evpn",
"/",
"evpn_instance",
"/",
"vlan",
"/",
"vlan_add",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only... | python | train | 75.227273 |
chainer/chainerui | chainerui/tasks/collect_results.py | https://github.com/chainer/chainerui/blob/87ad25e875bc332bfdad20197fd3d0cb81a078e8/chainerui/tasks/collect_results.py#L32-L59 | def collect_results(project, force=False):
"""collect_results."""
if not project.crawlable:
return project
now = datetime.datetime.now()
if (now - project.updated_at).total_seconds() < 4 and (not force):
return project
result_paths = []
if os.path.isdir(project.path_name):
... | [
"def",
"collect_results",
"(",
"project",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"project",
".",
"crawlable",
":",
"return",
"project",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"if",
"(",
"now",
"-",
"project",
".",
... | collect_results. | [
"collect_results",
"."
] | python | train | 27.5 |
knipknap/SpiffWorkflow | SpiffWorkflow/util/weakmethod.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/weakmethod.py#L117-L132 | def ref(function, callback=None):
"""
Returns a weak reference to the given method or function.
If the callback argument is not None, it is called as soon
as the referenced function is garbage deleted.
:type function: callable
:param function: The function to reference.
:type callback: ca... | [
"def",
"ref",
"(",
"function",
",",
"callback",
"=",
"None",
")",
":",
"try",
":",
"function",
".",
"__func__",
"except",
"AttributeError",
":",
"return",
"_WeakMethodFree",
"(",
"function",
",",
"callback",
")",
"return",
"_WeakMethodBound",
"(",
"function",
... | Returns a weak reference to the given method or function.
If the callback argument is not None, it is called as soon
as the referenced function is garbage deleted.
:type function: callable
:param function: The function to reference.
:type callback: callable
:param callback: Called when the fu... | [
"Returns",
"a",
"weak",
"reference",
"to",
"the",
"given",
"method",
"or",
"function",
".",
"If",
"the",
"callback",
"argument",
"is",
"not",
"None",
"it",
"is",
"called",
"as",
"soon",
"as",
"the",
"referenced",
"function",
"is",
"garbage",
"deleted",
"."... | python | valid | 33.25 |
apple/turicreate | src/external/xgboost/python-package/xgboost/core.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L774-L824 | def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False):
"""
Predict with data.
NOTE: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call... | [
"def",
"predict",
"(",
"self",
",",
"data",
",",
"output_margin",
"=",
"False",
",",
"ntree_limit",
"=",
"0",
",",
"pred_leaf",
"=",
"False",
")",
":",
"option_mask",
"=",
"0x00",
"if",
"output_margin",
":",
"option_mask",
"|=",
"0x01",
"if",
"pred_leaf",
... | Predict with data.
NOTE: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call bst.copy() to make copies
of model object and then call predict
Parameters... | [
"Predict",
"with",
"data",
"."
] | python | train | 37.117647 |
ekzhu/datasketch | datasketch/lshforest.py | https://github.com/ekzhu/datasketch/blob/b3e4129987890a2beb04f2c0b6dc618ae35f2e14/datasketch/lshforest.py#L62-L68 | def index(self):
'''
Index all the keys added so far and make them searchable.
'''
for i, hashtable in enumerate(self.hashtables):
self.sorted_hashtables[i] = [H for H in hashtable.keys()]
self.sorted_hashtables[i].sort() | [
"def",
"index",
"(",
"self",
")",
":",
"for",
"i",
",",
"hashtable",
"in",
"enumerate",
"(",
"self",
".",
"hashtables",
")",
":",
"self",
".",
"sorted_hashtables",
"[",
"i",
"]",
"=",
"[",
"H",
"for",
"H",
"in",
"hashtable",
".",
"keys",
"(",
")",
... | Index all the keys added so far and make them searchable. | [
"Index",
"all",
"the",
"keys",
"added",
"so",
"far",
"and",
"make",
"them",
"searchable",
"."
] | python | test | 38.714286 |
DataBiosphere/dsub | dsub/providers/local.py | https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/local.py#L641-L699 | def _get_task_from_task_dir(self, job_id, user_id, task_id, task_attempt):
"""Return a Task object with this task's info."""
# We need to be very careful about how we read and interpret the contents
# of the task directory. The directory could be changing because a new
# task is being created. The dire... | [
"def",
"_get_task_from_task_dir",
"(",
"self",
",",
"job_id",
",",
"user_id",
",",
"task_id",
",",
"task_attempt",
")",
":",
"# We need to be very careful about how we read and interpret the contents",
"# of the task directory. The directory could be changing because a new",
"# task ... | Return a Task object with this task's info. | [
"Return",
"a",
"Task",
"object",
"with",
"this",
"task",
"s",
"info",
"."
] | python | valid | 35.949153 |
openego/eTraGo | etrago/tools/utilities.py | https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L57-L75 | def buses_of_vlvl(network, voltage_level):
""" Get bus-ids of given voltage level(s).
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
voltage_level: list
Returns
-------
list
List containing bus-ids.
"""
mask = network.buses.v_n... | [
"def",
"buses_of_vlvl",
"(",
"network",
",",
"voltage_level",
")",
":",
"mask",
"=",
"network",
".",
"buses",
".",
"v_nom",
".",
"isin",
"(",
"voltage_level",
")",
"df",
"=",
"network",
".",
"buses",
"[",
"mask",
"]",
"return",
"df",
".",
"index"
] | Get bus-ids of given voltage level(s).
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
voltage_level: list
Returns
-------
list
List containing bus-ids. | [
"Get",
"bus",
"-",
"ids",
"of",
"given",
"voltage",
"level",
"(",
"s",
")",
"."
] | python | train | 19.684211 |
jrosebr1/imutils | imutils/convenience.py | https://github.com/jrosebr1/imutils/blob/4430083199793bd66db64e574379cbe18414d420/imutils/convenience.py#L304-L319 | def adjust_brightness_contrast(image, brightness=0., contrast=0.):
"""
Adjust the brightness and/or contrast of an image
:param image: OpenCV BGR image
:param contrast: Float, contrast adjustment with 0 meaning no change
:param brightness: Float, brightness adjustment with 0 meaning no change
"... | [
"def",
"adjust_brightness_contrast",
"(",
"image",
",",
"brightness",
"=",
"0.",
",",
"contrast",
"=",
"0.",
")",
":",
"beta",
"=",
"0",
"# See the OpenCV docs for more info on the `beta` parameter to addWeighted",
"# https://docs.opencv.org/3.4.2/d2/de8/group__core__array.html#g... | Adjust the brightness and/or contrast of an image
:param image: OpenCV BGR image
:param contrast: Float, contrast adjustment with 0 meaning no change
:param brightness: Float, brightness adjustment with 0 meaning no change | [
"Adjust",
"the",
"brightness",
"and",
"/",
"or",
"contrast",
"of",
"an",
"image"
] | python | train | 43.9375 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L122-L142 | def get_package_status(owner, repo, identifier):
"""Get the status for a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_status_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratel... | [
"def",
"get_package_status",
"(",
"owner",
",",
"repo",
",",
"identifier",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
"client",
".",
"packages_status_with_ht... | Get the status for a package in a repository. | [
"Get",
"the",
"status",
"for",
"a",
"package",
"in",
"a",
"repository",
"."
] | python | train | 28.952381 |
saltstack/salt | salt/modules/kubernetesmod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1467-L1510 | def __read_and_render_yaml_file(source,
template,
saltenv):
'''
Read a yaml file and, if needed, renders that using the specifieds
templating. Returns the python objects defined inside of the file.
'''
sfn = __salt__['cp.cache_file'](so... | [
"def",
"__read_and_render_yaml_file",
"(",
"source",
",",
"template",
",",
"saltenv",
")",
":",
"sfn",
"=",
"__salt__",
"[",
"'cp.cache_file'",
"]",
"(",
"source",
",",
"saltenv",
")",
"if",
"not",
"sfn",
":",
"raise",
"CommandExecutionError",
"(",
"'Source fi... | Read a yaml file and, if needed, renders that using the specifieds
templating. Returns the python objects defined inside of the file. | [
"Read",
"a",
"yaml",
"file",
"and",
"if",
"needed",
"renders",
"that",
"using",
"the",
"specifieds",
"templating",
".",
"Returns",
"the",
"python",
"objects",
"defined",
"inside",
"of",
"the",
"file",
"."
] | python | train | 37.5 |
DataDog/integrations-core | openstack_controller/datadog_checks/openstack_controller/api.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/openstack_controller/datadog_checks/openstack_controller/api.py#L598-L623 | def _get_valid_endpoint(resp, name, entry_type):
"""
Parse the service catalog returned by the Identity API for an endpoint matching
the Nova service with the requested version
Sends a CRITICAL service check when no viable candidates are found in the Catalog
"""
catalog =... | [
"def",
"_get_valid_endpoint",
"(",
"resp",
",",
"name",
",",
"entry_type",
")",
":",
"catalog",
"=",
"resp",
".",
"get",
"(",
"'token'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'catalog'",
",",
"[",
"]",
")",
"for",
"entry",
"in",
"catalog",
":",
"if... | Parse the service catalog returned by the Identity API for an endpoint matching
the Nova service with the requested version
Sends a CRITICAL service check when no viable candidates are found in the Catalog | [
"Parse",
"the",
"service",
"catalog",
"returned",
"by",
"the",
"Identity",
"API",
"for",
"an",
"endpoint",
"matching",
"the",
"Nova",
"service",
"with",
"the",
"requested",
"version",
"Sends",
"a",
"CRITICAL",
"service",
"check",
"when",
"no",
"viable",
"candi... | python | train | 43.115385 |
todstoychev/signal-dispatcher | signal_dispatcher/signal_dispatcher.py | https://github.com/todstoychev/signal-dispatcher/blob/77131d119045973d65434abbcd6accdfa9cc327a/signal_dispatcher/signal_dispatcher.py#L75-L84 | def signal_alias_exists(alias: str) -> bool:
"""
Checks if signal alias exists.
:param alias: Signal alias.
:return:
"""
if SignalDispatcher.signals.get(alias):
return True
return False | [
"def",
"signal_alias_exists",
"(",
"alias",
":",
"str",
")",
"->",
"bool",
":",
"if",
"SignalDispatcher",
".",
"signals",
".",
"get",
"(",
"alias",
")",
":",
"return",
"True",
"return",
"False"
] | Checks if signal alias exists.
:param alias: Signal alias.
:return: | [
"Checks",
"if",
"signal",
"alias",
"exists",
".",
":",
"param",
"alias",
":",
"Signal",
"alias",
".",
":",
"return",
":"
] | python | train | 24.5 |
Neurita/boyle | boyle/nifti/storage.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/storage.py#L160-L176 | def hdfpath_to_nifti1image(file_path, h5path):
"""Returns a nibabel Nifti1Image from a HDF5 group datasets
Parameters
----------
file_path: string
HDF5 file path
h5path:
HDF5 group path in file_path
Returns
-------
nibabel Nifti1Image
"""
with h5py.File(fil... | [
"def",
"hdfpath_to_nifti1image",
"(",
"file_path",
",",
"h5path",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"file_path",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"hdfgroup_to_nifti1image",
"(",
"f",
"[",
"h5path",
"]",
")"
] | Returns a nibabel Nifti1Image from a HDF5 group datasets
Parameters
----------
file_path: string
HDF5 file path
h5path:
HDF5 group path in file_path
Returns
-------
nibabel Nifti1Image | [
"Returns",
"a",
"nibabel",
"Nifti1Image",
"from",
"a",
"HDF5",
"group",
"datasets"
] | python | valid | 21.882353 |
ssalentin/plip | plip/plipcmd.py | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/plipcmd.py#L131-L177 | def main(inputstructs, inputpdbids):
"""Main function. Calls functions for processing, report generation and visualization."""
pdbid, pdbpath = None, None
# #@todo For multiprocessing, implement better stacktracing for errors
# Print title and version
title = "* Protein-Ligand Interaction Profiler v... | [
"def",
"main",
"(",
"inputstructs",
",",
"inputpdbids",
")",
":",
"pdbid",
",",
"pdbpath",
"=",
"None",
",",
"None",
"# #@todo For multiprocessing, implement better stacktracing for errors",
"# Print title and version",
"title",
"=",
"\"* Protein-Ligand Interaction Profiler v%s... | Main function. Calls functions for processing, report generation and visualization. | [
"Main",
"function",
".",
"Calls",
"functions",
"for",
"processing",
"report",
"generation",
"and",
"visualization",
"."
] | python | train | 52.148936 |
ros-infrastructure/ros_buildfarm | ros_buildfarm/status_page.py | https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/status_page.py#L489-L511 | def get_jenkins_job_urls(
rosdistro_name, jenkins_url, release_build_name, targets):
"""
Get the Jenkins job urls for each target.
The placeholder {pkg} needs to be replaced with the ROS package name.
:return: a dict indexed by targets containing a string
"""
urls = {}
for target i... | [
"def",
"get_jenkins_job_urls",
"(",
"rosdistro_name",
",",
"jenkins_url",
",",
"release_build_name",
",",
"targets",
")",
":",
"urls",
"=",
"{",
"}",
"for",
"target",
"in",
"targets",
":",
"view_name",
"=",
"get_release_view_name",
"(",
"rosdistro_name",
",",
"r... | Get the Jenkins job urls for each target.
The placeholder {pkg} needs to be replaced with the ROS package name.
:return: a dict indexed by targets containing a string | [
"Get",
"the",
"Jenkins",
"job",
"urls",
"for",
"each",
"target",
"."
] | python | valid | 37.652174 |
IEMLdev/ieml | ieml/distance/order.py | https://github.com/IEMLdev/ieml/blob/4c842ba7e6165e2f1b4a4e2e98759f9f33af5f25/ieml/distance/order.py#L25-L46 | def count_id(w0):
"""
0 -> no terms idd
1 -> most term idd are shared in root morphem
2 -> most term idd are shared in flexing morphem
3 -> most term idd are shared root <-> flexing (crossed)
:param w0:
:param w1:
:return:
"""
def f(w1):
count = [set(w0.root).intersectio... | [
"def",
"count_id",
"(",
"w0",
")",
":",
"def",
"f",
"(",
"w1",
")",
":",
"count",
"=",
"[",
"set",
"(",
"w0",
".",
"root",
")",
".",
"intersection",
"(",
"w1",
".",
"root",
")",
",",
"set",
"(",
"w0",
".",
"flexing",
")",
".",
"intersection",
... | 0 -> no terms idd
1 -> most term idd are shared in root morphem
2 -> most term idd are shared in flexing morphem
3 -> most term idd are shared root <-> flexing (crossed)
:param w0:
:param w1:
:return: | [
"0",
"-",
">",
"no",
"terms",
"idd",
"1",
"-",
">",
"most",
"term",
"idd",
"are",
"shared",
"in",
"root",
"morphem",
"2",
"-",
">",
"most",
"term",
"idd",
"are",
"shared",
"in",
"flexing",
"morphem",
"3",
"-",
">",
"most",
"term",
"idd",
"are",
"... | python | test | 27.409091 |
craffel/mir_eval | mir_eval/melody.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/melody.py#L358-L426 | def voicing_measures(ref_voicing, est_voicing):
"""Compute the voicing recall and false alarm rates given two voicing
indicator sequences, one as reference (truth) and the other as the estimate
(prediction). The sequences must be of the same length.
Examples
--------
>>> ref_time, ref_freq = m... | [
"def",
"voicing_measures",
"(",
"ref_voicing",
",",
"est_voicing",
")",
":",
"validate_voicing",
"(",
"ref_voicing",
",",
"est_voicing",
")",
"ref_voicing",
"=",
"ref_voicing",
".",
"astype",
"(",
"bool",
")",
"est_voicing",
"=",
"est_voicing",
".",
"astype",
"(... | Compute the voicing recall and false alarm rates given two voicing
indicator sequences, one as reference (truth) and the other as the estimate
(prediction). The sequences must be of the same length.
Examples
--------
>>> ref_time, ref_freq = mir_eval.io.load_time_series('ref.txt')
>>> est_time... | [
"Compute",
"the",
"voicing",
"recall",
"and",
"false",
"alarm",
"rates",
"given",
"two",
"voicing",
"indicator",
"sequences",
"one",
"as",
"reference",
"(",
"truth",
")",
"and",
"the",
"other",
"as",
"the",
"estimate",
"(",
"prediction",
")",
".",
"The",
"... | python | train | 35.028986 |
PmagPy/PmagPy | pmagpy/builder2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/builder2.py#L110-L119 | def find_or_create_by_name(self, item_name, items_list, item_type):
"""
See if item with item_name exists in item_list.
If not, create that item.
Either way, return an item of type item_type.
"""
item = self.find_by_name(item_name, items_list)
if not item:
... | [
"def",
"find_or_create_by_name",
"(",
"self",
",",
"item_name",
",",
"items_list",
",",
"item_type",
")",
":",
"item",
"=",
"self",
".",
"find_by_name",
"(",
"item_name",
",",
"items_list",
")",
"if",
"not",
"item",
":",
"item",
"=",
"self",
".",
"data_lis... | See if item with item_name exists in item_list.
If not, create that item.
Either way, return an item of type item_type. | [
"See",
"if",
"item",
"with",
"item_name",
"exists",
"in",
"item_list",
".",
"If",
"not",
"create",
"that",
"item",
".",
"Either",
"way",
"return",
"an",
"item",
"of",
"type",
"item_type",
"."
] | python | train | 38.9 |
scott-griffiths/bitstring | bitstring.py | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1472-L1477 | def _readintbe(self, length, start):
"""Read bits and interpret as a big-endian signed int."""
if length % 8:
raise InterpretError("Big-endian integers must be whole-byte. "
"Length = {0} bits.", length)
return self._readint(length, start) | [
"def",
"_readintbe",
"(",
"self",
",",
"length",
",",
"start",
")",
":",
"if",
"length",
"%",
"8",
":",
"raise",
"InterpretError",
"(",
"\"Big-endian integers must be whole-byte. \"",
"\"Length = {0} bits.\"",
",",
"length",
")",
"return",
"self",
".",
"_readint",... | Read bits and interpret as a big-endian signed int. | [
"Read",
"bits",
"and",
"interpret",
"as",
"a",
"big",
"-",
"endian",
"signed",
"int",
"."
] | python | train | 50.5 |
GNS3/gns3-server | gns3server/compute/dynamips/__init__.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L328-L395 | def create_nio(self, node, nio_settings):
"""
Creates a new NIO.
:param node: Dynamips node instance
:param nio_settings: information to create the NIO
:returns: a NIO object
"""
nio = None
if nio_settings["type"] == "nio_udp":
lport = nio_s... | [
"def",
"create_nio",
"(",
"self",
",",
"node",
",",
"nio_settings",
")",
":",
"nio",
"=",
"None",
"if",
"nio_settings",
"[",
"\"type\"",
"]",
"==",
"\"nio_udp\"",
":",
"lport",
"=",
"nio_settings",
"[",
"\"lport\"",
"]",
"rhost",
"=",
"nio_settings",
"[",
... | Creates a new NIO.
:param node: Dynamips node instance
:param nio_settings: information to create the NIO
:returns: a NIO object | [
"Creates",
"a",
"new",
"NIO",
"."
] | python | train | 50.294118 |
Galarzaa90/tibia.py | tibiapy/house.py | https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/tibiapy/house.py#L120-L171 | def from_content(cls, content):
"""Parses a Tibia.com response into a House object.
Parameters
----------
content: :class:`str`
HTML content of the page.
Returns
-------
:class:`House`
The house contained in the page, or None if the house... | [
"def",
"from_content",
"(",
"cls",
",",
"content",
")",
":",
"parsed_content",
"=",
"parse_tibiacom_content",
"(",
"content",
")",
"image_column",
",",
"desc_column",
",",
"",
"*",
"_",
"=",
"parsed_content",
".",
"find_all",
"(",
"'td'",
")",
"if",
"\"Error... | Parses a Tibia.com response into a House object.
Parameters
----------
content: :class:`str`
HTML content of the page.
Returns
-------
:class:`House`
The house contained in the page, or None if the house doesn't exist.
Raises
---... | [
"Parses",
"a",
"Tibia",
".",
"com",
"response",
"into",
"a",
"House",
"object",
"."
] | python | train | 33.846154 |
trendels/rhino | rhino/mapper.py | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L629-L673 | def path(self, target, args, kw):
"""Build a URL path fragment for a resource or route.
Possible values for `target`:
A string that does not start with a '.' and does not contain ':'.
: Looks up the route of the same name on this mapper and returns it's
path.
A s... | [
"def",
"path",
"(",
"self",
",",
"target",
",",
"args",
",",
"kw",
")",
":",
"if",
"type",
"(",
"target",
")",
"in",
"string_types",
":",
"if",
"':'",
"in",
"target",
":",
"# Build path a nested route name",
"prefix",
",",
"rest",
"=",
"target",
".",
"... | Build a URL path fragment for a resource or route.
Possible values for `target`:
A string that does not start with a '.' and does not contain ':'.
: Looks up the route of the same name on this mapper and returns it's
path.
A string of the form 'a:b', 'a:b:c', etc.
... | [
"Build",
"a",
"URL",
"path",
"fragment",
"for",
"a",
"resource",
"or",
"route",
"."
] | python | train | 44.644444 |
south-coast-science/scs_core | src/scs_core/gas/pid_datum.py | https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/pid_datum.py#L44-L58 | def __we_c(cls, calib, tc, temp, we_v):
"""
Compute weC from sensor temperature compensation of weV
"""
offset_v = calib.pid_elc_mv / 1000.0
response_v = we_v - offset_v # remove electronic zero
response_c = tc.correct(temp, response_v) # correct the res... | [
"def",
"__we_c",
"(",
"cls",
",",
"calib",
",",
"tc",
",",
"temp",
",",
"we_v",
")",
":",
"offset_v",
"=",
"calib",
".",
"pid_elc_mv",
"/",
"1000.0",
"response_v",
"=",
"we_v",
"-",
"offset_v",
"# remove electronic zero",
"response_c",
"=",
"tc",
".",
"c... | Compute weC from sensor temperature compensation of weV | [
"Compute",
"weC",
"from",
"sensor",
"temperature",
"compensation",
"of",
"weV"
] | python | train | 31.8 |
sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L206-L212 | def middle(self):
""" Returns the middle point of the bounding box
:return: middle point
:rtype: (float, float)
"""
return (self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2 | [
"def",
"middle",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"min_x",
"+",
"self",
".",
"max_x",
")",
"/",
"2",
",",
"(",
"self",
".",
"min_y",
"+",
"self",
".",
"max_y",
")",
"/",
"2"
] | Returns the middle point of the bounding box
:return: middle point
:rtype: (float, float) | [
"Returns",
"the",
"middle",
"point",
"of",
"the",
"bounding",
"box"
] | python | train | 31.142857 |
nagius/snmp_passpersist | snmp_passpersist.py | https://github.com/nagius/snmp_passpersist/blob/8cc584d2e90c920ae98a318164a55bde209a18f7/snmp_passpersist.py#L222-L224 | def add_ip(self,oid,value,label=None):
"""Short helper to add an IP address value to the MIB subtree."""
self.add_oid_entry(oid,'IPADDRESS',value,label=label) | [
"def",
"add_ip",
"(",
"self",
",",
"oid",
",",
"value",
",",
"label",
"=",
"None",
")",
":",
"self",
".",
"add_oid_entry",
"(",
"oid",
",",
"'IPADDRESS'",
",",
"value",
",",
"label",
"=",
"label",
")"
] | Short helper to add an IP address value to the MIB subtree. | [
"Short",
"helper",
"to",
"add",
"an",
"IP",
"address",
"value",
"to",
"the",
"MIB",
"subtree",
"."
] | python | train | 53.333333 |
ksbg/sparklanes | sparklanes/_submit/submit.py | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_submit/submit.py#L127-L155 | def __validate_and_fix_spark_args(spark_args):
"""
Prepares spark arguments. In the command-line script, they are passed as for example
`-s master=local[4] deploy-mode=client verbose`, which would be passed to spark-submit as
`--master local[4] --deploy-mode client --verbose`
Parameters
-------... | [
"def",
"__validate_and_fix_spark_args",
"(",
"spark_args",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'[\\w\\-_]+=.+'",
")",
"fixed_args",
"=",
"[",
"]",
"for",
"arg",
"in",
"spark_args",
":",
"if",
"arg",
"not",
"in",
"SPARK_SUBMIT_FLAGS",
":",
... | Prepares spark arguments. In the command-line script, they are passed as for example
`-s master=local[4] deploy-mode=client verbose`, which would be passed to spark-submit as
`--master local[4] --deploy-mode client --verbose`
Parameters
----------
spark_args (List): List of spark arguments
Ret... | [
"Prepares",
"spark",
"arguments",
".",
"In",
"the",
"command",
"-",
"line",
"script",
"they",
"are",
"passed",
"as",
"for",
"example",
"-",
"s",
"master",
"=",
"local",
"[",
"4",
"]",
"deploy",
"-",
"mode",
"=",
"client",
"verbose",
"which",
"would",
"... | python | train | 38.655172 |
mitsei/dlkit | dlkit/json_/authorization/queries.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/authorization/queries.py#L230-L240 | def match_agent_id(self, agent_id, match):
"""Matches the agent identified by the given ``Id``.
arg: agent_id (osid.id.Id): the Id of the ``Agent``
arg: match (boolean): ``true`` if a positive match, ``false``
for a negative match
raise: NullArgument - ``agent_id`... | [
"def",
"match_agent_id",
"(",
"self",
",",
"agent_id",
",",
"match",
")",
":",
"self",
".",
"_add_match",
"(",
"'agentId'",
",",
"str",
"(",
"agent_id",
")",
",",
"bool",
"(",
"match",
")",
")"
] | Matches the agent identified by the given ``Id``.
arg: agent_id (osid.id.Id): the Id of the ``Agent``
arg: match (boolean): ``true`` if a positive match, ``false``
for a negative match
raise: NullArgument - ``agent_id`` is ``null``
*compliance: mandatory -- This m... | [
"Matches",
"the",
"agent",
"identified",
"by",
"the",
"given",
"Id",
"."
] | python | train | 42.454545 |
brandjon/simplestruct | simplestruct/type.py | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/type.py#L61-L106 | def checktype_seq(self, seq, kind, *, unique=False, **kargs):
"""Raise TypeError if seq is not a sequence of elements satisfying
kind. Optionally require elements to be unique.
As a special case, a string is considered to be an atomic value
rather than a sequence of single-chara... | [
"def",
"checktype_seq",
"(",
"self",
",",
"seq",
",",
"kind",
",",
"*",
",",
"unique",
"=",
"False",
",",
"*",
"*",
"kargs",
")",
":",
"exp",
"=",
"self",
".",
"str_kind",
"(",
"kind",
")",
"# Make sure we have a sequence.",
"try",
":",
"iterator",
"="... | Raise TypeError if seq is not a sequence of elements satisfying
kind. Optionally require elements to be unique.
As a special case, a string is considered to be an atomic value
rather than a sequence of single-character strings. (Thus,
checktype_seq('foo', str) will fail.) | [
"Raise",
"TypeError",
"if",
"seq",
"is",
"not",
"a",
"sequence",
"of",
"elements",
"satisfying",
"kind",
".",
"Optionally",
"require",
"elements",
"to",
"be",
"unique",
".",
"As",
"a",
"special",
"case",
"a",
"string",
"is",
"considered",
"to",
"be",
"an",... | python | train | 43.304348 |
aliyun/aliyun-log-python-sdk | aliyun/log/logclient_operator.py | https://github.com/aliyun/aliyun-log-python-sdk/blob/ac383db0a16abf1e5ef7df36074374184b43516e/aliyun/log/logclient_operator.py#L780-L889 | def transform_data(from_client, from_project, from_logstore, from_time,
to_time=None,
to_client=None, to_project=None, to_logstore=None,
shard_list=None,
config=None,
batch_size=None, compress=None,
cg_name... | [
"def",
"transform_data",
"(",
"from_client",
",",
"from_project",
",",
"from_logstore",
",",
"from_time",
",",
"to_time",
"=",
"None",
",",
"to_client",
"=",
"None",
",",
"to_project",
"=",
"None",
",",
"to_logstore",
"=",
"None",
",",
"shard_list",
"=",
"No... | transform data from one logstore to another one (could be the same or in different region), the time is log received time on server side. | [
"transform",
"data",
"from",
"one",
"logstore",
"to",
"another",
"one",
"(",
"could",
"be",
"the",
"same",
"or",
"in",
"different",
"region",
")",
"the",
"time",
"is",
"log",
"received",
"time",
"on",
"server",
"side",
"."
] | python | train | 48.818182 |
hanguokai/youku | youku/youku_videos.py | https://github.com/hanguokai/youku/blob/b2df060c7dccfad990bcfa289fff68bb77d1e69b/youku/youku_videos.py#L21-L31 | def find_video_by_id(self, video_id):
"""doc: http://open.youku.com/docs/doc?id=44
"""
url = 'https://openapi.youku.com/v2/videos/show_basic.json'
params = {
'client_id': self.client_id,
'video_id': video_id
}
r = requests.get(url, params=params)
... | [
"def",
"find_video_by_id",
"(",
"self",
",",
"video_id",
")",
":",
"url",
"=",
"'https://openapi.youku.com/v2/videos/show_basic.json'",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'video_id'",
":",
"video_id",
"}",
"r",
"=",
"requests",... | doc: http://open.youku.com/docs/doc?id=44 | [
"doc",
":",
"http",
":",
"//",
"open",
".",
"youku",
".",
"com",
"/",
"docs",
"/",
"doc?id",
"=",
"44"
] | python | train | 32.272727 |
markovmodel/msmtools | msmtools/analysis/sparse/committor.py | https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/sparse/committor.py#L104-L175 | def backward_committor(T, A, B):
r"""Backward committor between given sets.
The backward committor u(x) between sets A and B is the
probability for the chain starting in x to have come from A last
rather than from B.
Parameters
----------
T : (M, M) ndarray
Transition matrix
A ... | [
"def",
"backward_committor",
"(",
"T",
",",
"A",
",",
"B",
")",
":",
"X",
"=",
"set",
"(",
"range",
"(",
"T",
".",
"shape",
"[",
"0",
"]",
")",
")",
"A",
"=",
"set",
"(",
"A",
")",
"B",
"=",
"set",
"(",
"B",
")",
"AB",
"=",
"A",
".",
"i... | r"""Backward committor between given sets.
The backward committor u(x) between sets A and B is the
probability for the chain starting in x to have come from A last
rather than from B.
Parameters
----------
T : (M, M) ndarray
Transition matrix
A : array_like
List of integer ... | [
"r",
"Backward",
"committor",
"between",
"given",
"sets",
"."
] | python | train | 25.305556 |
litl/rauth | rauth/service.py | https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/service.py#L261-L292 | def get_raw_access_token(self,
request_token,
request_token_secret,
method='GET',
**kwargs):
'''
Returns a Requests' response over the
:attr:`rauth.OAuth1Service.access_token_url`.... | [
"def",
"get_raw_access_token",
"(",
"self",
",",
"request_token",
",",
"request_token_secret",
",",
"method",
"=",
"'GET'",
",",
"*",
"*",
"kwargs",
")",
":",
"# ensure we've set the access_token_url",
"if",
"self",
".",
"access_token_url",
"is",
"None",
":",
"rai... | Returns a Requests' response over the
:attr:`rauth.OAuth1Service.access_token_url`.
Use this if your endpoint if you need the full `Response` object.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param re... | [
"Returns",
"a",
"Requests",
"response",
"over",
"the",
":",
"attr",
":",
"rauth",
".",
"OAuth1Service",
".",
"access_token_url",
"."
] | python | train | 42.84375 |
googlemaps/google-maps-services-python | googlemaps/places.py | https://github.com/googlemaps/google-maps-services-python/blob/7ed40b4d8df63479794c46ce29d03ed6083071d7/googlemaps/places.py#L175-L249 | def places_nearby(client, location=None, radius=None, keyword=None,
language=None, min_price=None, max_price=None, name=None,
open_now=False, rank_by=None, type=None, page_token=None):
"""
Performs nearby search for places.
:param location: The latitude/longitude value f... | [
"def",
"places_nearby",
"(",
"client",
",",
"location",
"=",
"None",
",",
"radius",
"=",
"None",
",",
"keyword",
"=",
"None",
",",
"language",
"=",
"None",
",",
"min_price",
"=",
"None",
",",
"max_price",
"=",
"None",
",",
"name",
"=",
"None",
",",
"... | Performs nearby search for places.
:param location: The latitude/longitude value for which you wish to obtain the
closest, human-readable address.
:type location: string, dict, list, or tuple
:param radius: Distance in meters within which to bias results.
:type radius: int
:p... | [
"Performs",
"nearby",
"search",
"for",
"places",
"."
] | python | train | 43.44 |
tus/tus-py-client | tusclient/uploader.py | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L274-L292 | def upload(self, stop_at=None):
"""
Perform file upload.
Performs continous upload of chunks of the file. The size uploaded at each cycle is
the value of the attribute 'chunk_size'.
:Args:
- stop_at (Optional[int]):
Determines at what offset value th... | [
"def",
"upload",
"(",
"self",
",",
"stop_at",
"=",
"None",
")",
":",
"self",
".",
"stop_at",
"=",
"stop_at",
"or",
"self",
".",
"file_size",
"while",
"self",
".",
"offset",
"<",
"self",
".",
"stop_at",
":",
"self",
".",
"upload_chunk",
"(",
")",
"els... | Perform file upload.
Performs continous upload of chunks of the file. The size uploaded at each cycle is
the value of the attribute 'chunk_size'.
:Args:
- stop_at (Optional[int]):
Determines at what offset value the upload should stop. If not specified this
... | [
"Perform",
"file",
"upload",
"."
] | python | train | 35.473684 |
PaulHancock/Aegean | AegeanTools/catalogs.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L714-L782 | def writeDB(filename, catalog, meta=None):
"""
Output an sqlite3 database containing one table for each source type
Parameters
----------
filename : str
Output filename
catalog : list
List of sources of type :class:`AegeanTools.models.OutputSource`,
:class:`AegeanTools.... | [
"def",
"writeDB",
"(",
"filename",
",",
"catalog",
",",
"meta",
"=",
"None",
")",
":",
"def",
"sqlTypes",
"(",
"obj",
",",
"names",
")",
":",
"\"\"\"\n Return the sql type corresponding to each named parameter in obj\n \"\"\"",
"types",
"=",
"[",
"]",
... | Output an sqlite3 database containing one table for each source type
Parameters
----------
filename : str
Output filename
catalog : list
List of sources of type :class:`AegeanTools.models.OutputSource`,
:class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.Isl... | [
"Output",
"an",
"sqlite3",
"database",
"containing",
"one",
"table",
"for",
"each",
"source",
"type"
] | python | train | 37.57971 |
henzk/django-productline | django_productline/features/staticfiles/urls.py | https://github.com/henzk/django-productline/blob/24ff156924c1a8c07b99cbb8a1de0a42b8d81f60/django_productline/features/staticfiles/urls.py#L4-L26 | def refine_get_urls(original):
"""
serve static files (and media files also)
in production the webserver should serve requested
static files itself and never let requests to /static/*
and /media/* get to the django application.
"""
def get_urls():
from django.conf.urls import url
... | [
"def",
"refine_get_urls",
"(",
"original",
")",
":",
"def",
"get_urls",
"(",
")",
":",
"from",
"django",
".",
"conf",
".",
"urls",
"import",
"url",
"from",
"django",
".",
"conf",
"import",
"settings",
"from",
"django",
".",
"contrib",
".",
"staticfiles",
... | serve static files (and media files also)
in production the webserver should serve requested
static files itself and never let requests to /static/*
and /media/* get to the django application. | [
"serve",
"static",
"files",
"(",
"and",
"media",
"files",
"also",
")"
] | python | train | 32.956522 |
apache/incubator-heron | heron/instance/src/python/instance/st_heron_instance.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/instance/st_heron_instance.py#L118-L142 | def handle_new_tuple_set_2(self, hts2):
"""Called when new HeronTupleSet2 arrives
Convert(Assemble) HeronTupleSet2(raw byte array) to HeronTupleSet
See more at GitHub PR #1421
:param tuple_msg_set: HeronTupleSet2 type
"""
if self.my_pplan_helper is None or self.my_instance is None:
L... | [
"def",
"handle_new_tuple_set_2",
"(",
"self",
",",
"hts2",
")",
":",
"if",
"self",
".",
"my_pplan_helper",
"is",
"None",
"or",
"self",
".",
"my_instance",
"is",
"None",
":",
"Log",
".",
"error",
"(",
"\"Got tuple set when no instance assigned yet\"",
")",
"else"... | Called when new HeronTupleSet2 arrives
Convert(Assemble) HeronTupleSet2(raw byte array) to HeronTupleSet
See more at GitHub PR #1421
:param tuple_msg_set: HeronTupleSet2 type | [
"Called",
"when",
"new",
"HeronTupleSet2",
"arrives",
"Convert",
"(",
"Assemble",
")",
"HeronTupleSet2",
"(",
"raw",
"byte",
"array",
")",
"to",
"HeronTupleSet",
"See",
"more",
"at",
"GitHub",
"PR",
"#1421",
":",
"param",
"tuple_msg_set",
":",
"HeronTupleSet2",
... | python | valid | 39.64 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/ext/ipy_inputhook.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/ipy_inputhook.py#L138-L152 | def set_inputhook(self, callback):
"""Set PyOS_InputHook to callback and return the previous one."""
# On platforms with 'readline' support, it's all too likely to
# have a KeyboardInterrupt signal delivered *even before* an
# initial ``try:`` clause in the callback can be executed, so
... | [
"def",
"set_inputhook",
"(",
"self",
",",
"callback",
")",
":",
"# On platforms with 'readline' support, it's all too likely to",
"# have a KeyboardInterrupt signal delivered *even before* an",
"# initial ``try:`` clause in the callback can be executed, so",
"# we need to disable CTRL+C in thi... | Set PyOS_InputHook to callback and return the previous one. | [
"Set",
"PyOS_InputHook",
"to",
"callback",
"and",
"return",
"the",
"previous",
"one",
"."
] | python | train | 49.933333 |
prompt-toolkit/pymux | pymux/key_bindings.py | https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/key_bindings.py#L85-L195 | def _load_builtins(self):
"""
Fill the Registry with the hard coded key bindings.
"""
pymux = self.pymux
kb = KeyBindings()
# Create filters.
has_prefix = HasPrefix(pymux)
waits_for_confirmation = WaitsForConfirmation(pymux)
prompt_or_command_focu... | [
"def",
"_load_builtins",
"(",
"self",
")",
":",
"pymux",
"=",
"self",
".",
"pymux",
"kb",
"=",
"KeyBindings",
"(",
")",
"# Create filters.",
"has_prefix",
"=",
"HasPrefix",
"(",
"pymux",
")",
"waits_for_confirmation",
"=",
"WaitsForConfirmation",
"(",
"pymux",
... | Fill the Registry with the hard coded key bindings. | [
"Fill",
"the",
"Registry",
"with",
"the",
"hard",
"coded",
"key",
"bindings",
"."
] | python | train | 37.288288 |
neithere/monk | monk/manipulation.py | https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/manipulation.py#L108-L139 | def normalize_list_of_dicts(value, default_key, default_value=UNDEFINED):
"""
Converts given value to a list of dictionaries as follows:
* ``[{...}]`` → ``[{...}]``
* ``{...}`` → ``[{...}]``
* ``'xyz'`` → ``[{default_key: 'xyz'}]``
* ``None`` → ``[{default_key: default_value}]`` (if spe... | [
"def",
"normalize_list_of_dicts",
"(",
"value",
",",
"default_key",
",",
"default_value",
"=",
"UNDEFINED",
")",
":",
"if",
"value",
"is",
"None",
":",
"if",
"default_value",
"is",
"UNDEFINED",
":",
"return",
"[",
"]",
"value",
"=",
"default_value",
"if",
"i... | Converts given value to a list of dictionaries as follows:
* ``[{...}]`` → ``[{...}]``
* ``{...}`` → ``[{...}]``
* ``'xyz'`` → ``[{default_key: 'xyz'}]``
* ``None`` → ``[{default_key: default_value}]`` (if specified)
* ``None`` → ``[]``
:param default_value:
only Unicode, i.... | [
"Converts",
"given",
"value",
"to",
"a",
"list",
"of",
"dictionaries",
"as",
"follows",
":"
] | python | train | 29.28125 |
SCIP-Interfaces/PySCIPOpt | examples/unfinished/tsptw.py | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/unfinished/tsptw.py#L52-L92 | def mtz2tw(n,c,e,l):
"""mtz: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting ... | [
"def",
"mtz2tw",
"(",
"n",
",",
"c",
",",
"e",
",",
"l",
")",
":",
"model",
"=",
"Model",
"(",
"\"tsptw - mtz-strong\"",
")",
"x",
",",
"u",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n",
"+",
"1",
")",
":",
... | mtz: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting node i
- l[i]: lates... | [
"mtz",
":",
"model",
"for",
"the",
"traveling",
"salesman",
"problem",
"with",
"time",
"windows",
"(",
"based",
"on",
"Miller",
"-",
"Tucker",
"-",
"Zemlin",
"s",
"one",
"-",
"index",
"potential",
"formulation",
"stronger",
"constraints",
")",
"Parameters",
... | python | train | 40 |
googleapis/gax-python | google/gax/errors.py | https://github.com/googleapis/gax-python/blob/309aedfcfd48e4c8fa22dd60e9c84c3cc71bb20e/google/gax/errors.py#L73-L90 | def create_error(msg, cause=None):
"""Creates a ``GaxError`` or subclass.
Attributes:
msg (string): describes the error that occurred.
cause (Exception, optional): the exception raised by a lower
layer of the RPC stack (for example, gRPC) that caused this
exception, or N... | [
"def",
"create_error",
"(",
"msg",
",",
"cause",
"=",
"None",
")",
":",
"status_code",
"=",
"config",
".",
"exc_to_code",
"(",
"cause",
")",
"status_name",
"=",
"config",
".",
"NAME_STATUS_CODES",
".",
"get",
"(",
"status_code",
")",
"if",
"status_name",
"... | Creates a ``GaxError`` or subclass.
Attributes:
msg (string): describes the error that occurred.
cause (Exception, optional): the exception raised by a lower
layer of the RPC stack (for example, gRPC) that caused this
exception, or None if this exception originated in GAX.
... | [
"Creates",
"a",
"GaxError",
"or",
"subclass",
"."
] | python | train | 37.333333 |
iotile/coretools | iotilecore/iotile/core/utilities/intelhex/__init__.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L1071-L1096 | def bin2hex(fin, fout, offset=0):
"""Simple bin-to-hex convertor.
@return 0 if all OK
@param fin input bin file (filename or file-like object)
@param fout output hex file (filename or file-like object)
@param offset starting address offset for loading bin
"""
h = IntelHex()... | [
"def",
"bin2hex",
"(",
"fin",
",",
"fout",
",",
"offset",
"=",
"0",
")",
":",
"h",
"=",
"IntelHex",
"(",
")",
"try",
":",
"h",
".",
"loadbin",
"(",
"fin",
",",
"offset",
")",
"except",
"IOError",
":",
"e",
"=",
"sys",
".",
"exc_info",
"(",
")",... | Simple bin-to-hex convertor.
@return 0 if all OK
@param fin input bin file (filename or file-like object)
@param fout output hex file (filename or file-like object)
@param offset starting address offset for loading bin | [
"Simple",
"bin",
"-",
"to",
"-",
"hex",
"convertor",
".",
"@return",
"0",
"if",
"all",
"OK"
] | python | train | 28.615385 |
explosion/thinc | examples/text-pair/glove_mwe_multipool_siamese.py | https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/examples/text-pair/glove_mwe_multipool_siamese.py#L46-L64 | def track_progress(**context):
"""Print training progress. Called after each epoch."""
model = context["model"]
train_X = context["train_X"]
dev_X = context["dev_X"]
dev_y = context["dev_y"]
n_train = len(train_X)
trainer = context["trainer"]
def each_epoch():
global epoch_train... | [
"def",
"track_progress",
"(",
"*",
"*",
"context",
")",
":",
"model",
"=",
"context",
"[",
"\"model\"",
"]",
"train_X",
"=",
"context",
"[",
"\"train_X\"",
"]",
"dev_X",
"=",
"context",
"[",
"\"dev_X\"",
"]",
"dev_y",
"=",
"context",
"[",
"\"dev_y\"",
"]... | Print training progress. Called after each epoch. | [
"Print",
"training",
"progress",
".",
"Called",
"after",
"each",
"epoch",
"."
] | python | train | 33.947368 |
opencobra/memote | memote/utils.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/utils.py#L71-L130 | def annotate(title, format_type, message=None, data=None, metric=1.0):
"""
Annotate a test case with info that should be displayed in the reports.
Parameters
----------
title : str
A human-readable descriptive title of the test case.
format_type : str
A string that determines ho... | [
"def",
"annotate",
"(",
"title",
",",
"format_type",
",",
"message",
"=",
"None",
",",
"data",
"=",
"None",
",",
"metric",
"=",
"1.0",
")",
":",
"if",
"format_type",
"not",
"in",
"TYPES",
":",
"raise",
"ValueError",
"(",
"\"Invalid type. Expected one of: {}.... | Annotate a test case with info that should be displayed in the reports.
Parameters
----------
title : str
A human-readable descriptive title of the test case.
format_type : str
A string that determines how the result data is formatted in the
report. It is expected not to be None... | [
"Annotate",
"a",
"test",
"case",
"with",
"info",
"that",
"should",
"be",
"displayed",
"in",
"the",
"reports",
"."
] | python | train | 38 |
nickmilon/Hellas | Hellas/Athens.py | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Athens.py#L37-L66 | def haversine(lon1, lat1, lon2, lat2, earth_radius=6357000):
"""Calculate the great circle distance between two points on earth in Kilometers
on the earth (specified in decimal degrees)
.. seealso:: :func:`distance_points`
:param float lon1: longitude of first place (decimal degrees)
:param float ... | [
"def",
"haversine",
"(",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
",",
"earth_radius",
"=",
"6357000",
")",
":",
"# convert decimal degrees to radiant",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
"=",
"list",
"(",
"map",
"(",
"math",
".",
"radi... | Calculate the great circle distance between two points on earth in Kilometers
on the earth (specified in decimal degrees)
.. seealso:: :func:`distance_points`
:param float lon1: longitude of first place (decimal degrees)
:param float lat1: latitude of first place (decimal degrees)
:param float lon... | [
"Calculate",
"the",
"great",
"circle",
"distance",
"between",
"two",
"points",
"on",
"earth",
"in",
"Kilometers",
"on",
"the",
"earth",
"(",
"specified",
"in",
"decimal",
"degrees",
")"
] | python | train | 45.3 |
knagra/farnsworth | threads/views.py | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/threads/views.py#L193-L216 | def list_user_threads_view(request, targetUsername):
''' View of threads a user has created. '''
targetUser = get_object_or_404(User, username=targetUsername)
targetProfile = get_object_or_404(UserProfile, user=targetUser)
threads = Thread.objects.filter(owner=targetProfile)
page_name = "{0}'s Threa... | [
"def",
"list_user_threads_view",
"(",
"request",
",",
"targetUsername",
")",
":",
"targetUser",
"=",
"get_object_or_404",
"(",
"User",
",",
"username",
"=",
"targetUsername",
")",
"targetProfile",
"=",
"get_object_or_404",
"(",
"UserProfile",
",",
"user",
"=",
"ta... | View of threads a user has created. | [
"View",
"of",
"threads",
"a",
"user",
"has",
"created",
"."
] | python | train | 43.916667 |
simpleai-team/simpleai | simpleai/search/local.py | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L21-L38 | def beam(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Req... | [
"def",
"beam",
"(",
"problem",
",",
"beam_size",
"=",
"100",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_all_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fri... | Beam search.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
an... | [
"Beam",
"search",
"."
] | python | train | 42.722222 |
waqasbhatti/astrobase | astrobase/timeutils.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/timeutils.py#L294-L388 | def get_epochs_given_midtimes_and_period(
t_mid,
period,
err_t_mid=None,
t0_fixed=None,
t0_percentile=None,
verbose=False
):
'''This calculates the future epochs for a transit, given a period and a
starting epoch
The equation used is::
t_mid = period... | [
"def",
"get_epochs_given_midtimes_and_period",
"(",
"t_mid",
",",
"period",
",",
"err_t_mid",
"=",
"None",
",",
"t0_fixed",
"=",
"None",
",",
"t0_percentile",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"kwargarr",
"=",
"np",
".",
"array",
"(",
"[... | This calculates the future epochs for a transit, given a period and a
starting epoch
The equation used is::
t_mid = period*epoch + t0
Default behavior if no kwargs are used is to define `t0` as the median
finite time of the passed `t_mid` array.
Only one of `err_t_mid` or `t0_fixed` shou... | [
"This",
"calculates",
"the",
"future",
"epochs",
"for",
"a",
"transit",
"given",
"a",
"period",
"and",
"a",
"starting",
"epoch"
] | python | valid | 33.2 |
pappasam/latexbuild | latexbuild/__init__.py | https://github.com/pappasam/latexbuild/blob/596a2a0a4c42eaa5eb9503d64f9073ad5d0640d5/latexbuild/__init__.py#L40-L56 | def build_html(path_jinja2, template_name, path_outfile, template_kwargs=None):
'''Helper function for building an html from a latex jinja2 template
:param path_jinja2: the root directory for latex jinja2 templates
:param template_name: the relative path, to path_jinja2, to the desired
jinja2 Latex... | [
"def",
"build_html",
"(",
"path_jinja2",
",",
"template_name",
",",
"path_outfile",
",",
"template_kwargs",
"=",
"None",
")",
":",
"latex_template_object",
"=",
"LatexBuild",
"(",
"path_jinja2",
",",
"template_name",
",",
"template_kwargs",
",",
")",
"return",
"la... | Helper function for building an html from a latex jinja2 template
:param path_jinja2: the root directory for latex jinja2 templates
:param template_name: the relative path, to path_jinja2, to the desired
jinja2 Latex template
:param path_outfile: the full path to the desired final output file
... | [
"Helper",
"function",
"for",
"building",
"an",
"html",
"from",
"a",
"latex",
"jinja2",
"template"
] | python | train | 46.117647 |
inveniosoftware/kwalitee | kwalitee/hooks.py | https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/hooks.py#L285-L306 | def run(command, raw_output=False):
"""Run a command using subprocess.
:param command: command line to be run
:type command: str
:param raw_output: does not attempt to convert the output as unicode
:type raw_output: bool
:return: error code, output (``stdout``) and error (``stderr``)
:rtype... | [
"def",
"run",
"(",
"command",
",",
"raw_output",
"=",
"False",
")",
":",
"p",
"=",
"Popen",
"(",
"command",
".",
"split",
"(",
")",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
"(",
"stdout",
",",
"stderr",
")",
"=",
"p",
".",
"... | Run a command using subprocess.
:param command: command line to be run
:type command: str
:param raw_output: does not attempt to convert the output as unicode
:type raw_output: bool
:return: error code, output (``stdout``) and error (``stderr``)
:rtype: tuple | [
"Run",
"a",
"command",
"using",
"subprocess",
"."
] | python | train | 34.318182 |
annayqho/TheCannon | TheCannon/normalization.py | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L380-L398 | def _cont_norm_running_quantile_regions(wl, fluxes, ivars, q, delta_lambda,
ranges, verbose=True):
""" Perform continuum normalization using running quantile, for spectrum
that comes in chunks
"""
print("contnorm.py: continuum norm using running quantile")
pri... | [
"def",
"_cont_norm_running_quantile_regions",
"(",
"wl",
",",
"fluxes",
",",
"ivars",
",",
"q",
",",
"delta_lambda",
",",
"ranges",
",",
"verbose",
"=",
"True",
")",
":",
"print",
"(",
"\"contnorm.py: continuum norm using running quantile\"",
")",
"print",
"(",
"\... | Perform continuum normalization using running quantile, for spectrum
that comes in chunks | [
"Perform",
"continuum",
"normalization",
"using",
"running",
"quantile",
"for",
"spectrum",
"that",
"comes",
"in",
"chunks"
] | python | train | 42.736842 |
carlosp420/dataset-creator | dataset_creator/utils.py | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/utils.py#L59-L72 | def convert_nexus_to_format(dataset_as_nexus, dataset_format):
"""
Converts nexus format to Phylip and Fasta using Biopython tools.
:param dataset_as_nexus:
:param dataset_format:
:return:
"""
fake_handle = StringIO(dataset_as_nexus)
nexus_al = AlignIO.parse(fake_handle, 'nexus')
tm... | [
"def",
"convert_nexus_to_format",
"(",
"dataset_as_nexus",
",",
"dataset_format",
")",
":",
"fake_handle",
"=",
"StringIO",
"(",
"dataset_as_nexus",
")",
"nexus_al",
"=",
"AlignIO",
".",
"parse",
"(",
"fake_handle",
",",
"'nexus'",
")",
"tmp_file",
"=",
"make_rand... | Converts nexus format to Phylip and Fasta using Biopython tools.
:param dataset_as_nexus:
:param dataset_format:
:return: | [
"Converts",
"nexus",
"format",
"to",
"Phylip",
"and",
"Fasta",
"using",
"Biopython",
"tools",
"."
] | python | train | 34.142857 |
boriel/zxbasic | zxbparser.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L912-L917 | def p_statement_draw_attr(p):
""" statement : DRAW attr_list expr COMMA expr
"""
p[0] = make_sentence('DRAW',
make_typecast(TYPE.integer, p[3], p.lineno(4)),
make_typecast(TYPE.integer, p[5], p.lineno(4)), p[2]) | [
"def",
"p_statement_draw_attr",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"make_sentence",
"(",
"'DRAW'",
",",
"make_typecast",
"(",
"TYPE",
".",
"integer",
",",
"p",
"[",
"3",
"]",
",",
"p",
".",
"lineno",
"(",
"4",
")",
")",
",",
"make_typecas... | statement : DRAW attr_list expr COMMA expr | [
"statement",
":",
"DRAW",
"attr_list",
"expr",
"COMMA",
"expr"
] | python | train | 44.666667 |
obulpathi/cdn-fastly-python | fastly/__init__.py | https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L286-L294 | def content_edge_check(self, url):
"""Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server."""
prefixes = ["http://", "https://"]
for prefix in prefixes:
if url.startswith(prefix):
url = url[len(prefix):]
break
content = self._fetch("/content/edge_check/%s" %... | [
"def",
"content_edge_check",
"(",
"self",
",",
"url",
")",
":",
"prefixes",
"=",
"[",
"\"http://\"",
",",
"\"https://\"",
"]",
"for",
"prefix",
"in",
"prefixes",
":",
"if",
"url",
".",
"startswith",
"(",
"prefix",
")",
":",
"url",
"=",
"url",
"[",
"len... | Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server. | [
"Retrieve",
"headers",
"and",
"MD5",
"hash",
"of",
"the",
"content",
"for",
"a",
"particular",
"url",
"from",
"each",
"Fastly",
"edge",
"server",
"."
] | python | train | 37.111111 |
bitprophet/ssh | ssh/transport.py | https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/transport.py#L1466-L1482 | def _compute_key(self, id, nbytes):
"id is 'A' - 'F' for the various keys used by ssh"
m = Message()
m.add_mpint(self.K)
m.add_bytes(self.H)
m.add_byte(id)
m.add_bytes(self.session_id)
out = sofar = SHA.new(str(m)).digest()
while len(out) < nbytes:
... | [
"def",
"_compute_key",
"(",
"self",
",",
"id",
",",
"nbytes",
")",
":",
"m",
"=",
"Message",
"(",
")",
"m",
".",
"add_mpint",
"(",
"self",
".",
"K",
")",
"m",
".",
"add_bytes",
"(",
"self",
".",
"H",
")",
"m",
".",
"add_byte",
"(",
"id",
")",
... | id is 'A' - 'F' for the various keys used by ssh | [
"id",
"is",
"A",
"-",
"F",
"for",
"the",
"various",
"keys",
"used",
"by",
"ssh"
] | python | train | 32.058824 |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/namespace_range.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L283-L303 | def make_datastore_query(self, cursor=None):
"""Returns a datastore.Query that generates all namespaces in the range.
Args:
cursor: start cursor for the query.
Returns:
A datastore.Query instance that generates db.Keys for each namespace in
the NamespaceRange.
"""
filters = {}
... | [
"def",
"make_datastore_query",
"(",
"self",
",",
"cursor",
"=",
"None",
")",
":",
"filters",
"=",
"{",
"}",
"filters",
"[",
"'__key__ >= '",
"]",
"=",
"_key_for_namespace",
"(",
"self",
".",
"namespace_start",
",",
"self",
".",
"app",
")",
"filters",
"[",
... | Returns a datastore.Query that generates all namespaces in the range.
Args:
cursor: start cursor for the query.
Returns:
A datastore.Query instance that generates db.Keys for each namespace in
the NamespaceRange. | [
"Returns",
"a",
"datastore",
".",
"Query",
"that",
"generates",
"all",
"namespaces",
"in",
"the",
"range",
"."
] | python | train | 32.809524 |
mottosso/be | be/vendor/requests/packages/urllib3/util/retry.py | https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/retry.py#L158-L167 | def get_backoff_time(self):
""" Formula for computing the current backoff
:rtype: float
"""
if self._observed_errors <= 1:
return 0
backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1))
return min(self.BACKOFF_MAX, backoff_value) | [
"def",
"get_backoff_time",
"(",
"self",
")",
":",
"if",
"self",
".",
"_observed_errors",
"<=",
"1",
":",
"return",
"0",
"backoff_value",
"=",
"self",
".",
"backoff_factor",
"*",
"(",
"2",
"**",
"(",
"self",
".",
"_observed_errors",
"-",
"1",
")",
")",
... | Formula for computing the current backoff
:rtype: float | [
"Formula",
"for",
"computing",
"the",
"current",
"backoff"
] | python | train | 30.1 |
numenta/htmresearch | htmresearch/frameworks/layers/physical_objects.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/physical_objects.py#L316-L337 | def plot(self, numPoints=100):
"""
Specific plotting method for cylinders.
"""
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# generate cylinder
x = np.linspace(- self.radius, self.radius, numPoints)
z = np.linspace(- self.height / 2., self.height / 2., numPoints)
Xc... | [
"def",
"plot",
"(",
"self",
",",
"numPoints",
"=",
"100",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
",",
"projection",
"=",
"'3d'",
")",
"# generate cylinder",
"x",
"=",
"np",
".",
"lins... | Specific plotting method for cylinders. | [
"Specific",
"plotting",
"method",
"for",
"cylinders",
"."
] | python | train | 28.954545 |
LISE-B26/pylabcontrol | build/lib/pylabcontrol/src/instruments/instrument_dummy.py | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/instruments/instrument_dummy.py#L139-L159 | def run(self):
"""
this is the actual execution of the instrument thread: continuously read values from the probes
"""
eta = self.settings['noise_strength']
gamma = 2 * np.pi * self.settings['noise_bandwidth']
dt = 1. / self.settings['update frequency']
control =... | [
"def",
"run",
"(",
"self",
")",
":",
"eta",
"=",
"self",
".",
"settings",
"[",
"'noise_strength'",
"]",
"gamma",
"=",
"2",
"*",
"np",
".",
"pi",
"*",
"self",
".",
"settings",
"[",
"'noise_bandwidth'",
"]",
"dt",
"=",
"1.",
"/",
"self",
".",
"settin... | this is the actual execution of the instrument thread: continuously read values from the probes | [
"this",
"is",
"the",
"actual",
"execution",
"of",
"the",
"instrument",
"thread",
":",
"continuously",
"read",
"values",
"from",
"the",
"probes"
] | python | train | 32.142857 |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/optoanalysis.py | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/optoanalysis.py#L4233-L4278 | def get_wigner(z, freq, sample_freq, histbins=200, show_plot=False):
"""
Calculates an approximation to the wigner quasi-probability distribution
by splitting the z position array into slices of the length of one period
of the motion. This slice is then associated with phase from -180 to 180
degrees... | [
"def",
"get_wigner",
"(",
"z",
",",
"freq",
",",
"sample_freq",
",",
"histbins",
"=",
"200",
",",
"show_plot",
"=",
"False",
")",
":",
"phase",
",",
"phase_slices",
"=",
"extract_slices",
"(",
"z",
",",
"freq",
",",
"sample_freq",
",",
"show_plot",
"=",
... | Calculates an approximation to the wigner quasi-probability distribution
by splitting the z position array into slices of the length of one period
of the motion. This slice is then associated with phase from -180 to 180
degrees. These slices are then histogramed in order to get a distribution
of counts ... | [
"Calculates",
"an",
"approximation",
"to",
"the",
"wigner",
"quasi",
"-",
"probability",
"distribution",
"by",
"splitting",
"the",
"z",
"position",
"array",
"into",
"slices",
"of",
"the",
"length",
"of",
"one",
"period",
"of",
"the",
"motion",
".",
"This",
"... | python | train | 36.891304 |
lawsie/guizero | guizero/event.py | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/event.py#L177-L190 | def set_event(self, ref, tk_event, callback):
"""
Sets a callback for this widget against a ref (reference) for a
tk_event, setting the callback to None will remove it.
"""
# has an EventCallback been created for this tk event
if tk_event not in self._event_callbacks:
... | [
"def",
"set_event",
"(",
"self",
",",
"ref",
",",
"tk_event",
",",
"callback",
")",
":",
"# has an EventCallback been created for this tk event",
"if",
"tk_event",
"not",
"in",
"self",
".",
"_event_callbacks",
":",
"self",
".",
"_event_callbacks",
"[",
"tk_event",
... | Sets a callback for this widget against a ref (reference) for a
tk_event, setting the callback to None will remove it. | [
"Sets",
"a",
"callback",
"for",
"this",
"widget",
"against",
"a",
"ref",
"(",
"reference",
")",
"for",
"a",
"tk_event",
"setting",
"the",
"callback",
"to",
"None",
"will",
"remove",
"it",
"."
] | python | train | 42.071429 |
spotify/luigi | luigi/contrib/s3.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L177-L195 | def exists(self, path):
"""
Does provided path exist on S3?
"""
(bucket, key) = self._path_to_bucket_and_key(path)
# root always exists
if self._is_root(key):
return True
# file
if self._exists(bucket, key):
return True
i... | [
"def",
"exists",
"(",
"self",
",",
"path",
")",
":",
"(",
"bucket",
",",
"key",
")",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"path",
")",
"# root always exists",
"if",
"self",
".",
"_is_root",
"(",
"key",
")",
":",
"return",
"True",
"# file",
... | Does provided path exist on S3? | [
"Does",
"provided",
"path",
"exist",
"on",
"S3?"
] | python | train | 22.105263 |
hvac/hvac | hvac/api/system_backend/key.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/system_backend/key.py#L7-L20 | def read_root_generation_progress(self):
"""Read the configuration and process of the current root generation attempt.
Supported methods:
GET: /sys/generate-root/attempt. Produces: 200 application/json
:return: The JSON response of the request.
:rtype: dict
"""
... | [
"def",
"read_root_generation_progress",
"(",
"self",
")",
":",
"api_path",
"=",
"'/v1/sys/generate-root/attempt'",
"response",
"=",
"self",
".",
"_adapter",
".",
"get",
"(",
"url",
"=",
"api_path",
",",
")",
"return",
"response",
".",
"json",
"(",
")"
] | Read the configuration and process of the current root generation attempt.
Supported methods:
GET: /sys/generate-root/attempt. Produces: 200 application/json
:return: The JSON response of the request.
:rtype: dict | [
"Read",
"the",
"configuration",
"and",
"process",
"of",
"the",
"current",
"root",
"generation",
"attempt",
"."
] | python | train | 32.714286 |
klmitch/turnstile | turnstile/control.py | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/control.py#L82-L98 | def get_limits(self, limit_sum=None):
"""
Gets the current limit data if it is different from the data
indicated by limit_sum. The db argument is used for hydrating
the limit objects. Raises a NoChangeException if the
limit_sum represents no change, otherwise returns a tuple
... | [
"def",
"get_limits",
"(",
"self",
",",
"limit_sum",
"=",
"None",
")",
":",
"with",
"self",
".",
"limit_lock",
":",
"# Any changes?",
"if",
"limit_sum",
"and",
"self",
".",
"limit_sum",
"==",
"limit_sum",
":",
"raise",
"NoChangeException",
"(",
")",
"# Return... | Gets the current limit data if it is different from the data
indicated by limit_sum. The db argument is used for hydrating
the limit objects. Raises a NoChangeException if the
limit_sum represents no change, otherwise returns a tuple
consisting of the current limit_sum and a list of Li... | [
"Gets",
"the",
"current",
"limit",
"data",
"if",
"it",
"is",
"different",
"from",
"the",
"data",
"indicated",
"by",
"limit_sum",
".",
"The",
"db",
"argument",
"is",
"used",
"for",
"hydrating",
"the",
"limit",
"objects",
".",
"Raises",
"a",
"NoChangeException... | python | train | 39 |
connectordb/connectordb-python | connectordb/_connection.py | https://github.com/connectordb/connectordb-python/blob/2092b0cb30898139a247176bcf433d5a4abde7cb/connectordb/_connection.py#L117-L121 | def ping(self):
"""Attempts to ping the server using current credentials, and responds with the path of the currently
authenticated device"""
return self.handleresult(self.r.get(self.url,
params={"q": "this"})).text | [
"def",
"ping",
"(",
"self",
")",
":",
"return",
"self",
".",
"handleresult",
"(",
"self",
".",
"r",
".",
"get",
"(",
"self",
".",
"url",
",",
"params",
"=",
"{",
"\"q\"",
":",
"\"this\"",
"}",
")",
")",
".",
"text"
] | Attempts to ping the server using current credentials, and responds with the path of the currently
authenticated device | [
"Attempts",
"to",
"ping",
"the",
"server",
"using",
"current",
"credentials",
"and",
"responds",
"with",
"the",
"path",
"of",
"the",
"currently",
"authenticated",
"device"
] | python | test | 55.8 |
iotile/coretools | iotilegateway/iotilegateway/device.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L110-L120 | def get_config(self, name, default=_MISSING):
"""Get a configuration setting from this DeviceAdapter.
See :meth:`AbstractDeviceAdapter.get_config`.
"""
val = self._config.get(name, default)
if val is _MISSING:
raise ArgumentError("DeviceAdapter config {} did not exi... | [
"def",
"get_config",
"(",
"self",
",",
"name",
",",
"default",
"=",
"_MISSING",
")",
":",
"val",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"name",
",",
"default",
")",
"if",
"val",
"is",
"_MISSING",
":",
"raise",
"ArgumentError",
"(",
"\"DeviceAdap... | Get a configuration setting from this DeviceAdapter.
See :meth:`AbstractDeviceAdapter.get_config`. | [
"Get",
"a",
"configuration",
"setting",
"from",
"this",
"DeviceAdapter",
"."
] | python | train | 32.909091 |
quantumlib/Cirq | cirq/google/sim/xmon_stepper.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L304-L339 | def simulate_w(self,
index: int,
half_turns: float,
axis_half_turns: float):
"""Simulate a single qubit rotation gate about a X + b Y.
The gate simulated is U = exp(-i pi/2 W half_turns)
where W = cos(pi axis_half_turns) X + sin(pi ax... | [
"def",
"simulate_w",
"(",
"self",
",",
"index",
":",
"int",
",",
"half_turns",
":",
"float",
",",
"axis_half_turns",
":",
"float",
")",
":",
"args",
"=",
"self",
".",
"_shard_num_args",
"(",
"{",
"'index'",
":",
"index",
",",
"'half_turns'",
":",
"half_t... | Simulate a single qubit rotation gate about a X + b Y.
The gate simulated is U = exp(-i pi/2 W half_turns)
where W = cos(pi axis_half_turns) X + sin(pi axis_half_turns) Y
Args:
index: The qubit to act on.
half_turns: The amount of the overall rotation, see the formula
... | [
"Simulate",
"a",
"single",
"qubit",
"rotation",
"gate",
"about",
"a",
"X",
"+",
"b",
"Y",
"."
] | python | train | 36.277778 |
ray-project/ray | python/ray/rllib/agents/dqn/dqn_policy_graph.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L679-L700 | def _scope_vars(scope, trainable_only=False):
"""
Get variables inside a scope
The scope can be specified as a string
Parameters
----------
scope: str or VariableScope
scope in which the variables reside.
trainable_only: bool
whether or not to return only the variables that were... | [
"def",
"_scope_vars",
"(",
"scope",
",",
"trainable_only",
"=",
"False",
")",
":",
"return",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
"if",
"trainable_only",
"else",
"tf",
".",
"GraphKeys",
".",
"VARIABLES",
",",
... | Get variables inside a scope
The scope can be specified as a string
Parameters
----------
scope: str or VariableScope
scope in which the variables reside.
trainable_only: bool
whether or not to return only the variables that were marked as
trainable.
Returns
-------
v... | [
"Get",
"variables",
"inside",
"a",
"scope",
"The",
"scope",
"can",
"be",
"specified",
"as",
"a",
"string"
] | python | train | 27.636364 |
ga4gh/ga4gh-server | ga4gh/server/datamodel/__init__.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/__init__.py#L68-L90 | def getFileHandle(self, dataFile, openMethod):
"""
Returns handle associated to the filename. If the file is
already opened, update its priority in the cache and return
its handle. Otherwise, open the file using openMethod, store
it in the cache and return the corresponding handl... | [
"def",
"getFileHandle",
"(",
"self",
",",
"dataFile",
",",
"openMethod",
")",
":",
"if",
"dataFile",
"in",
"self",
".",
"_memoTable",
":",
"handle",
"=",
"self",
".",
"_memoTable",
"[",
"dataFile",
"]",
"self",
".",
"_update",
"(",
"dataFile",
",",
"hand... | Returns handle associated to the filename. If the file is
already opened, update its priority in the cache and return
its handle. Otherwise, open the file using openMethod, store
it in the cache and return the corresponding handle. | [
"Returns",
"handle",
"associated",
"to",
"the",
"filename",
".",
"If",
"the",
"file",
"is",
"already",
"opened",
"update",
"its",
"priority",
"in",
"the",
"cache",
"and",
"return",
"its",
"handle",
".",
"Otherwise",
"open",
"the",
"file",
"using",
"openMetho... | python | train | 39.391304 |
tanghaibao/jcvi | jcvi/formats/fastq.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fastq.py#L238-L267 | def uniq(args):
"""
%prog uniq fastqfile
Retain only first instance of duplicate reads. Duplicate is defined as
having the same read name.
"""
p = OptionParser(uniq.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
... | [
"def",
"uniq",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"uniq",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
"... | %prog uniq fastqfile
Retain only first instance of duplicate reads. Duplicate is defined as
having the same read name. | [
"%prog",
"uniq",
"fastqfile"
] | python | train | 25.066667 |
cjdrake/pyeda | pyeda/boolalg/expr.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L242-L245 | def expr2dimacscnf(ex):
"""Convert an expression into an equivalent DIMACS CNF."""
litmap, nvars, clauses = ex.encode_cnf()
return litmap, DimacsCNF(nvars, clauses) | [
"def",
"expr2dimacscnf",
"(",
"ex",
")",
":",
"litmap",
",",
"nvars",
",",
"clauses",
"=",
"ex",
".",
"encode_cnf",
"(",
")",
"return",
"litmap",
",",
"DimacsCNF",
"(",
"nvars",
",",
"clauses",
")"
] | Convert an expression into an equivalent DIMACS CNF. | [
"Convert",
"an",
"expression",
"into",
"an",
"equivalent",
"DIMACS",
"CNF",
"."
] | python | train | 43.25 |
jtwhite79/pyemu | pyemu/utils/helpers.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/helpers.py#L601-L713 | def kl_setup(num_eig,sr,struct,prefixes,
factors_file="kl_factors.dat",islog=True, basis_file=None,
tpl_dir="."):
"""setup a karhuenen-Loeve based parameterization for a given
geostatistical structure.
Parameters
----------
num_eig : int
number of basis vectors to ... | [
"def",
"kl_setup",
"(",
"num_eig",
",",
"sr",
",",
"struct",
",",
"prefixes",
",",
"factors_file",
"=",
"\"kl_factors.dat\"",
",",
"islog",
"=",
"True",
",",
"basis_file",
"=",
"None",
",",
"tpl_dir",
"=",
"\".\"",
")",
":",
"try",
":",
"import",
"flopy"... | setup a karhuenen-Loeve based parameterization for a given
geostatistical structure.
Parameters
----------
num_eig : int
number of basis vectors to retain in the reduced basis
sr : flopy.reference.SpatialReference
struct : str or pyemu.geostats.Geostruct
geostatistical structur... | [
"setup",
"a",
"karhuenen",
"-",
"Loeve",
"based",
"parameterization",
"for",
"a",
"given",
"geostatistical",
"structure",
"."
] | python | train | 32.902655 |
chaoss/grimoirelab-elk | grimoire_elk/enriched/mediawiki.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/mediawiki.py#L109-L116 | def get_review_sh(self, revision, item):
""" Add sorting hat enrichment fields for the author of the revision """
identity = self.get_sh_identity(revision)
update = parser.parse(item[self.get_field_date()])
erevision = self.get_item_sh_fields(identity, update)
return erevision | [
"def",
"get_review_sh",
"(",
"self",
",",
"revision",
",",
"item",
")",
":",
"identity",
"=",
"self",
".",
"get_sh_identity",
"(",
"revision",
")",
"update",
"=",
"parser",
".",
"parse",
"(",
"item",
"[",
"self",
".",
"get_field_date",
"(",
")",
"]",
"... | Add sorting hat enrichment fields for the author of the revision | [
"Add",
"sorting",
"hat",
"enrichment",
"fields",
"for",
"the",
"author",
"of",
"the",
"revision"
] | python | train | 39 |
HIPS/autograd | examples/generative_adversarial_net.py | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/generative_adversarial_net.py#L59-L91 | def adam_minimax(grad_both, init_params_max, init_params_min, callback=None, num_iters=100,
step_size_max=0.001, step_size_min=0.001, b1=0.9, b2=0.999, eps=10**-8):
"""Adam modified to do minimiax optimization, for instance to help with
training generative adversarial networks."""
x_max, unflatten... | [
"def",
"adam_minimax",
"(",
"grad_both",
",",
"init_params_max",
",",
"init_params_min",
",",
"callback",
"=",
"None",
",",
"num_iters",
"=",
"100",
",",
"step_size_max",
"=",
"0.001",
",",
"step_size_min",
"=",
"0.001",
",",
"b1",
"=",
"0.9",
",",
"b2",
"... | Adam modified to do minimiax optimization, for instance to help with
training generative adversarial networks. | [
"Adam",
"modified",
"to",
"do",
"minimiax",
"optimization",
"for",
"instance",
"to",
"help",
"with",
"training",
"generative",
"adversarial",
"networks",
"."
] | python | train | 49.454545 |
saltstack/salt | salt/utils/thin.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/thin.py#L298-L320 | def _get_supported_py_config(tops, extended_cfg):
'''
Based on the Salt SSH configuration, create a YAML configuration
for the supported Python interpreter versions. This is then written into the thin.tgz
archive and then verified by salt.client.ssh.ssh_py_shim.get_executable()
Note: Minimum defaul... | [
"def",
"_get_supported_py_config",
"(",
"tops",
",",
"extended_cfg",
")",
":",
"pymap",
"=",
"[",
"]",
"for",
"py_ver",
",",
"tops",
"in",
"_six",
".",
"iteritems",
"(",
"copy",
".",
"deepcopy",
"(",
"tops",
")",
")",
":",
"py_ver",
"=",
"int",
"(",
... | Based on the Salt SSH configuration, create a YAML configuration
for the supported Python interpreter versions. This is then written into the thin.tgz
archive and then verified by salt.client.ssh.ssh_py_shim.get_executable()
Note: Minimum default of 2.x versions is 2.7 and 3.x is 3.0, unless specified in n... | [
"Based",
"on",
"the",
"Salt",
"SSH",
"configuration",
"create",
"a",
"YAML",
"configuration",
"for",
"the",
"supported",
"Python",
"interpreter",
"versions",
".",
"This",
"is",
"then",
"written",
"into",
"the",
"thin",
".",
"tgz",
"archive",
"and",
"then",
"... | python | train | 36.826087 |
bcbio/bcbio-nextgen | bcbio/cwl/tool.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/tool.py#L137-L154 | def _run_bunny(args):
"""Run CWL with rabix bunny.
"""
main_file, json_file, project_name = _get_main_and_json(args.directory)
work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "bunny_work"))
flags = ["-b", work_dir]
log_file = os.path.join(work_dir, "%s-bunny.log" % project_name)
if o... | [
"def",
"_run_bunny",
"(",
"args",
")",
":",
"main_file",
",",
"json_file",
",",
"project_name",
"=",
"_get_main_and_json",
"(",
"args",
".",
"directory",
")",
"work_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
... | Run CWL with rabix bunny. | [
"Run",
"CWL",
"with",
"rabix",
"bunny",
"."
] | python | train | 44.388889 |
saltstack/salt | salt/modules/netaddress.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netaddress.py#L59-L68 | def cidr_netmask(cidr):
'''
Get the netmask address associated with a CIDR address.
CLI example::
salt myminion netaddress.cidr_netmask 192.168.0.0/20
'''
ips = netaddr.IPNetwork(cidr)
return six.text_type(ips.netmask) | [
"def",
"cidr_netmask",
"(",
"cidr",
")",
":",
"ips",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"cidr",
")",
"return",
"six",
".",
"text_type",
"(",
"ips",
".",
"netmask",
")"
] | Get the netmask address associated with a CIDR address.
CLI example::
salt myminion netaddress.cidr_netmask 192.168.0.0/20 | [
"Get",
"the",
"netmask",
"address",
"associated",
"with",
"a",
"CIDR",
"address",
"."
] | python | train | 24.3 |
dereneaton/ipyrad | ipyrad/assemble/util.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/util.py#L865-L886 | def clustdealer(pairdealer, optim):
""" return optim clusters given iterators, and whether it got all or not"""
ccnt = 0
chunk = []
while ccnt < optim:
## try refreshing taker, else quit
try:
taker = itertools.takewhile(lambda x: x[0] != "//\n", pairdealer)
oneclu... | [
"def",
"clustdealer",
"(",
"pairdealer",
",",
"optim",
")",
":",
"ccnt",
"=",
"0",
"chunk",
"=",
"[",
"]",
"while",
"ccnt",
"<",
"optim",
":",
"## try refreshing taker, else quit",
"try",
":",
"taker",
"=",
"itertools",
".",
"takewhile",
"(",
"lambda",
"x"... | return optim clusters given iterators, and whether it got all or not | [
"return",
"optim",
"clusters",
"given",
"iterators",
"and",
"whether",
"it",
"got",
"all",
"or",
"not"
] | python | valid | 31.227273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.