repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
estnltk/estnltk | estnltk/wordnet/eurown.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/wordnet/eurown.py#L231-L238 | def addFeature(self, feature):
'''Appends Feature'''
if isinstance(feature, Feature):
self.features.append(feature)
else:
raise TypeError(
'feature Type should be Feature, not %s' % type(feature)) | [
"def",
"addFeature",
"(",
"self",
",",
"feature",
")",
":",
"if",
"isinstance",
"(",
"feature",
",",
"Feature",
")",
":",
"self",
".",
"features",
".",
"append",
"(",
"feature",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'feature Type should be Feature, n... | Appends Feature | [
"Appends",
"Feature"
] | python | train |
Shizmob/pydle | pydle/features/rfc1459/client.py | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L362-L370 | async def set_mode(self, target, *modes):
"""
Set mode on target.
Users should only rely on the mode actually being changed when receiving an on_{channel,user}_mode_change callback.
"""
if self.is_channel(target) and not self.in_channel(target):
raise NotInChannel(tar... | [
"async",
"def",
"set_mode",
"(",
"self",
",",
"target",
",",
"*",
"modes",
")",
":",
"if",
"self",
".",
"is_channel",
"(",
"target",
")",
"and",
"not",
"self",
".",
"in_channel",
"(",
"target",
")",
":",
"raise",
"NotInChannel",
"(",
"target",
")",
"... | Set mode on target.
Users should only rely on the mode actually being changed when receiving an on_{channel,user}_mode_change callback. | [
"Set",
"mode",
"on",
"target",
".",
"Users",
"should",
"only",
"rely",
"on",
"the",
"mode",
"actually",
"being",
"changed",
"when",
"receiving",
"an",
"on_",
"{",
"channel",
"user",
"}",
"_mode_change",
"callback",
"."
] | python | train |
daethnir/authprogs | authprogs/authprogs.py | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L260-L278 | def install_key_data(self, keydata, target):
"""Install the key data into the open file."""
target.seek(0)
contents = target.read()
ssh_opts = 'no-port-forwarding'
if keydata in contents:
raise InstallError('key data already in file - refusing '
... | [
"def",
"install_key_data",
"(",
"self",
",",
"keydata",
",",
"target",
")",
":",
"target",
".",
"seek",
"(",
"0",
")",
"contents",
"=",
"target",
".",
"read",
"(",
")",
"ssh_opts",
"=",
"'no-port-forwarding'",
"if",
"keydata",
"in",
"contents",
":",
"rai... | Install the key data into the open file. | [
"Install",
"the",
"key",
"data",
"into",
"the",
"open",
"file",
"."
] | python | train |
mk-fg/feedjack | feedjack/models.py | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/models.py#L178-L187 | def handler(self):
'Handler function'
from feedjack import filters # shouldn't be imported globally, as they may depend on models
proc_func = getattr(filters, self.handler_name or self.name, None)
if proc_func is None:
if '.' not in self.handler_name:
raise ImportError('Processing function not available:... | [
"def",
"handler",
"(",
"self",
")",
":",
"from",
"feedjack",
"import",
"filters",
"# shouldn't be imported globally, as they may depend on models",
"proc_func",
"=",
"getattr",
"(",
"filters",
",",
"self",
".",
"handler_name",
"or",
"self",
".",
"name",
",",
"None",... | Handler function | [
"Handler",
"function"
] | python | train |
gmr/queries | queries/tornado_session.py | https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/tornado_session.py#L468-L478 | def _on_io_events(self, fd=None, _events=None):
"""Invoked by Tornado's IOLoop when there are events for the fd
:param int fd: The file descriptor for the event
:param int _events: The events raised
"""
if fd not in self._connections:
LOGGER.warning('Received IO eve... | [
"def",
"_on_io_events",
"(",
"self",
",",
"fd",
"=",
"None",
",",
"_events",
"=",
"None",
")",
":",
"if",
"fd",
"not",
"in",
"self",
".",
"_connections",
":",
"LOGGER",
".",
"warning",
"(",
"'Received IO event for non-existing connection'",
")",
"return",
"s... | Invoked by Tornado's IOLoop when there are events for the fd
:param int fd: The file descriptor for the event
:param int _events: The events raised | [
"Invoked",
"by",
"Tornado",
"s",
"IOLoop",
"when",
"there",
"are",
"events",
"for",
"the",
"fd"
] | python | train |
sixty-north/asq | asq/queryables.py | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L486-L543 | def group_by(self, key_selector=identity,
element_selector=identity,
result_selector=lambda key, grouping: grouping):
'''Groups the elements according to the value of a key extracted by a
selector function.
Note: This method has different behaviour to itertools... | [
"def",
"group_by",
"(",
"self",
",",
"key_selector",
"=",
"identity",
",",
"element_selector",
"=",
"identity",
",",
"result_selector",
"=",
"lambda",
"key",
",",
"grouping",
":",
"grouping",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
... | Groups the elements according to the value of a key extracted by a
selector function.
Note: This method has different behaviour to itertools.groupby in the
Python standard library because it aggregates all items with the
same key, rather than returning groups of consecutive item... | [
"Groups",
"the",
"elements",
"according",
"to",
"the",
"value",
"of",
"a",
"key",
"extracted",
"by",
"a",
"selector",
"function",
"."
] | python | train |
thecynic/pylutron | pylutron/__init__.py | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L259-L275 | def _parse_button(self, keypad, component_xml):
"""Parses a button device that part of a keypad."""
button_xml = component_xml.find('Button')
name = button_xml.get('Engraving')
button_type = button_xml.get('ButtonType')
direction = button_xml.get('Direction')
# Hybrid keypads have dimmer buttons... | [
"def",
"_parse_button",
"(",
"self",
",",
"keypad",
",",
"component_xml",
")",
":",
"button_xml",
"=",
"component_xml",
".",
"find",
"(",
"'Button'",
")",
"name",
"=",
"button_xml",
".",
"get",
"(",
"'Engraving'",
")",
"button_type",
"=",
"button_xml",
".",
... | Parses a button device that part of a keypad. | [
"Parses",
"a",
"button",
"device",
"that",
"part",
"of",
"a",
"keypad",
"."
] | python | train |
sdispater/orator | orator/query/builder.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1094-L1117 | def simple_paginate(self, per_page=15, current_page=None, columns=None):
"""
Paginate the given query.
:param per_page: The number of records per page
:type per_page: int
:param current_page: The current page of results
:type current_page: int
:param columns: T... | [
"def",
"simple_paginate",
"(",
"self",
",",
"per_page",
"=",
"15",
",",
"current_page",
"=",
"None",
",",
"columns",
"=",
"None",
")",
":",
"if",
"columns",
"is",
"None",
":",
"columns",
"=",
"[",
"\"*\"",
"]",
"page",
"=",
"current_page",
"or",
"Pagin... | Paginate the given query.
:param per_page: The number of records per page
:type per_page: int
:param current_page: The current page of results
:type current_page: int
:param columns: The columns to return
:type columns: list
:return: The paginator
:rty... | [
"Paginate",
"the",
"given",
"query",
"."
] | python | train |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L4454-L4473 | def libvlc_media_discoverer_new(p_inst, psz_name):
'''Create a media discoverer object by name.
After this object is created, you should attach to events in order to be
notified of the discoverer state.
You should also attach to media_list events in order to be notified of new
items discovered.
... | [
"def",
"libvlc_media_discoverer_new",
"(",
"p_inst",
",",
"psz_name",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_discoverer_new'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_discoverer_new'",
",",
"(",
"(",
"1",
",",
")",
... | Create a media discoverer object by name.
After this object is created, you should attach to events in order to be
notified of the discoverer state.
You should also attach to media_list events in order to be notified of new
items discovered.
You need to call L{libvlc_media_discoverer_start}() in ord... | [
"Create",
"a",
"media",
"discoverer",
"object",
"by",
"name",
".",
"After",
"this",
"object",
"is",
"created",
"you",
"should",
"attach",
"to",
"events",
"in",
"order",
"to",
"be",
"notified",
"of",
"the",
"discoverer",
"state",
".",
"You",
"should",
"also... | python | train |
mfcloud/python-zvm-sdk | zvmsdk/networkops.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/networkops.py#L242-L258 | def _create_network_doscript(self, network_file_path):
"""doscript: contains a invokeScript.sh which will do the special work
The network.doscript contains network configuration files and it will
be used by zvmguestconfigure to configure zLinux os network when it
starts up
"""
... | [
"def",
"_create_network_doscript",
"(",
"self",
",",
"network_file_path",
")",
":",
"# Generate the tar package for punch",
"LOG",
".",
"debug",
"(",
"'Creating network doscript in the folder %s'",
"%",
"network_file_path",
")",
"network_doscript",
"=",
"os",
".",
"path",
... | doscript: contains a invokeScript.sh which will do the special work
The network.doscript contains network configuration files and it will
be used by zvmguestconfigure to configure zLinux os network when it
starts up | [
"doscript",
":",
"contains",
"a",
"invokeScript",
".",
"sh",
"which",
"will",
"do",
"the",
"special",
"work"
] | python | train |
hovren/crisp | crisp/znccpyr.py | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/znccpyr.py#L41-L71 | def subsample(time_series, downsample_factor):
"""Subsample with Gaussian prefilter
The prefilter will have the filter size $\sigma_g=.5*ssfactor$
Parameters
--------------
time_series : ndarray
Input signal
downsample_factor : float
Downsampling factor
Retu... | [
"def",
"subsample",
"(",
"time_series",
",",
"downsample_factor",
")",
":",
"Ns",
"=",
"np",
".",
"int",
"(",
"np",
".",
"floor",
"(",
"np",
".",
"size",
"(",
"time_series",
")",
"/",
"downsample_factor",
")",
")",
"g",
"=",
"gaussian_kernel",
"(",
"0.... | Subsample with Gaussian prefilter
The prefilter will have the filter size $\sigma_g=.5*ssfactor$
Parameters
--------------
time_series : ndarray
Input signal
downsample_factor : float
Downsampling factor
Returns
--------------
ts_out : ndarray
... | [
"Subsample",
"with",
"Gaussian",
"prefilter"
] | python | train |
O365/python-o365 | O365/utils/attachment.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/utils/attachment.py#L383-L419 | def download_attachments(self):
""" Downloads this message attachments into memory.
Need a call to 'attachment.save' to save them on disk.
:return: Success / Failure
:rtype: bool
"""
if not self._parent.has_attachments:
log.debug(
'Parent {} h... | [
"def",
"download_attachments",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_parent",
".",
"has_attachments",
":",
"log",
".",
"debug",
"(",
"'Parent {} has no attachments, skipping out early.'",
".",
"format",
"(",
"self",
".",
"_parent",
".",
"__class__",
... | Downloads this message attachments into memory.
Need a call to 'attachment.save' to save them on disk.
:return: Success / Failure
:rtype: bool | [
"Downloads",
"this",
"message",
"attachments",
"into",
"memory",
".",
"Need",
"a",
"call",
"to",
"attachment",
".",
"save",
"to",
"save",
"them",
"on",
"disk",
"."
] | python | train |
elastic/apm-agent-python | elasticapm/contrib/django/client.py | https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/contrib/django/client.py#L212-L223 | def send(self, url, **kwargs):
"""
Serializes and signs ``data`` and passes the payload off to ``send_remote``
If ``server`` was passed into the constructor, this will serialize the data and pipe it to
the server using ``send_remote()``.
"""
if self.config.server_url:
... | [
"def",
"send",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"config",
".",
"server_url",
":",
"return",
"super",
"(",
"DjangoClient",
",",
"self",
")",
".",
"send",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"else... | Serializes and signs ``data`` and passes the payload off to ``send_remote``
If ``server`` was passed into the constructor, this will serialize the data and pipe it to
the server using ``send_remote()``. | [
"Serializes",
"and",
"signs",
"data",
"and",
"passes",
"the",
"payload",
"off",
"to",
"send_remote"
] | python | train |
Qiskit/qiskit-terra | qiskit/quantum_info/random/utils.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/random/utils.py#L128-L142 | def __random_density_hs(N, rank=None, seed=None):
"""
Generate a random density matrix from the Hilbert-Schmidt metric.
Args:
N (int): the length of the density matrix.
rank (int or None): the rank of the density matrix. The default
value is full-rank.
seed (int): Option... | [
"def",
"__random_density_hs",
"(",
"N",
",",
"rank",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"G",
"=",
"__ginibre_matrix",
"(",
"N",
",",
"rank",
",",
"seed",
")",
"G",
"=",
"G",
".",
"dot",
"(",
"G",
".",
"conj",
"(",
")",
".",
"T",
... | Generate a random density matrix from the Hilbert-Schmidt metric.
Args:
N (int): the length of the density matrix.
rank (int or None): the rank of the density matrix. The default
value is full-rank.
seed (int): Optional. To set a random seed.
Returns:
ndarray: rho (N... | [
"Generate",
"a",
"random",
"density",
"matrix",
"from",
"the",
"Hilbert",
"-",
"Schmidt",
"metric",
"."
] | python | test |
robotools/fontParts | Lib/fontParts/base/glyph.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/glyph.py#L622-L644 | def drawPoints(self, pen, contours=True, components=True):
"""
Draw the glyph's outline data (contours and components) to
the given :ref:`type-pointpen`.
>>> glyph.drawPoints(pointPen)
If ``contours`` is set to ``False``, the glyph's
contours will not be drawn.
... | [
"def",
"drawPoints",
"(",
"self",
",",
"pen",
",",
"contours",
"=",
"True",
",",
"components",
"=",
"True",
")",
":",
"if",
"contours",
":",
"for",
"contour",
"in",
"self",
":",
"contour",
".",
"drawPoints",
"(",
"pen",
")",
"if",
"components",
":",
... | Draw the glyph's outline data (contours and components) to
the given :ref:`type-pointpen`.
>>> glyph.drawPoints(pointPen)
If ``contours`` is set to ``False``, the glyph's
contours will not be drawn.
>>> glyph.drawPoints(pointPen, contours=False)
If ``component... | [
"Draw",
"the",
"glyph",
"s",
"outline",
"data",
"(",
"contours",
"and",
"components",
")",
"to",
"the",
"given",
":",
"ref",
":",
"type",
"-",
"pointpen",
"."
] | python | train |
pandeylab/pythomics | pythomics/genomics/structures.py | https://github.com/pandeylab/pythomics/blob/ab0a5651a2e02a25def4d277b35fa09d1631bfcb/pythomics/genomics/structures.py#L278-L289 | def is_homozygous(self, individual=None):
"""This will give a boolean list corresponding to whether each individual
is homozygous for the alternative allele.
"""
if individual is not None:
if isinstance(individual, str):
individual = self.individuals[individu... | [
"def",
"is_homozygous",
"(",
"self",
",",
"individual",
"=",
"None",
")",
":",
"if",
"individual",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"individual",
",",
"str",
")",
":",
"individual",
"=",
"self",
".",
"individuals",
"[",
"individual",
"]... | This will give a boolean list corresponding to whether each individual
is homozygous for the alternative allele. | [
"This",
"will",
"give",
"a",
"boolean",
"list",
"corresponding",
"to",
"whether",
"each",
"individual",
"is",
"homozygous",
"for",
"the",
"alternative",
"allele",
"."
] | python | train |
IdentityPython/pysaml2 | src/saml2/__init__.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L335-L369 | def find_extensions(self, tag=None, namespace=None):
"""Searches extension elements for child nodes with the desired name.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all extensions in
a particular namespace, specify ... | [
"def",
"find_extensions",
"(",
"self",
",",
"tag",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"tag",
"and",
"namespace",
":",
"for",
"element",
"in",
"self",
".",
"extension_elements",
":",
"if",
"element",
".... | Searches extension elements for child nodes with the desired name.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all extensions in
a particular namespace, specify the namespace but not the tag name.
If you specify only ... | [
"Searches",
"extension",
"elements",
"for",
"child",
"nodes",
"with",
"the",
"desired",
"name",
"."
] | python | train |
inspirehep/harvesting-kit | harvestingkit/elsevier_package.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/elsevier_package.py#L864-L1083 | def get_record(self, path=None, no_pdf=False,
test=False, refextract_callback=None):
"""Convert a record to MARCXML format.
:param path: path to a record.
:type path: string
:param test: flag to determine if it is a test call.
:type test: bool
:param r... | [
"def",
"get_record",
"(",
"self",
",",
"path",
"=",
"None",
",",
"no_pdf",
"=",
"False",
",",
"test",
"=",
"False",
",",
"refextract_callback",
"=",
"None",
")",
":",
"xml_doc",
"=",
"self",
".",
"get_article",
"(",
"path",
")",
"rec",
"=",
"create_rec... | Convert a record to MARCXML format.
:param path: path to a record.
:type path: string
:param test: flag to determine if it is a test call.
:type test: bool
:param refextract_callback: callback to be used to extract
unstructured references. It ... | [
"Convert",
"a",
"record",
"to",
"MARCXML",
"format",
"."
] | python | valid |
wrobstory/vincent | vincent/visualization.py | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/visualization.py#L350-L377 | def validate(self, require_all=True, scale='colors'):
"""Validate the visualization contents.
Parameters
----------
require_all : boolean, default True
If True (default), then all fields ``data``, ``scales``,
``axes``, and ``marks`` must be defined. The user is a... | [
"def",
"validate",
"(",
"self",
",",
"require_all",
"=",
"True",
",",
"scale",
"=",
"'colors'",
")",
":",
"super",
"(",
"self",
".",
"__class__",
",",
"self",
")",
".",
"validate",
"(",
")",
"required_attribs",
"=",
"(",
"'data'",
",",
"'scales'",
",",... | Validate the visualization contents.
Parameters
----------
require_all : boolean, default True
If True (default), then all fields ``data``, ``scales``,
``axes``, and ``marks`` must be defined. The user is allowed to
disable this if the intent is to define the... | [
"Validate",
"the",
"visualization",
"contents",
"."
] | python | train |
quantopian/pgcontents | pgcontents/query.py | https://github.com/quantopian/pgcontents/blob/ed36268b7917332d16868208e1e565742a8753e1/pgcontents/query.py#L56-L67 | def preprocess_incoming_content(content, encrypt_func, max_size_bytes):
"""
Apply preprocessing steps to file/notebook content that we're going to
write to the database.
Applies ``encrypt_func`` to ``content`` and checks that the result is
smaller than ``max_size_bytes``.
"""
encrypted = en... | [
"def",
"preprocess_incoming_content",
"(",
"content",
",",
"encrypt_func",
",",
"max_size_bytes",
")",
":",
"encrypted",
"=",
"encrypt_func",
"(",
"content",
")",
"if",
"max_size_bytes",
"!=",
"UNLIMITED",
"and",
"len",
"(",
"encrypted",
")",
">",
"max_size_bytes"... | Apply preprocessing steps to file/notebook content that we're going to
write to the database.
Applies ``encrypt_func`` to ``content`` and checks that the result is
smaller than ``max_size_bytes``. | [
"Apply",
"preprocessing",
"steps",
"to",
"file",
"/",
"notebook",
"content",
"that",
"we",
"re",
"going",
"to",
"write",
"to",
"the",
"database",
"."
] | python | test |
fermiPy/fermipy | fermipy/gtanalysis.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/gtanalysis.py#L5670-L5675 | def write_xml(self, xmlfile):
"""Write the XML model for this analysis component."""
xmlfile = self.get_model_path(xmlfile)
self.logger.info('Writing %s...', xmlfile)
self.like.writeXml(str(xmlfile)) | [
"def",
"write_xml",
"(",
"self",
",",
"xmlfile",
")",
":",
"xmlfile",
"=",
"self",
".",
"get_model_path",
"(",
"xmlfile",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'Writing %s...'",
",",
"xmlfile",
")",
"self",
".",
"like",
".",
"writeXml",
"(",
"... | Write the XML model for this analysis component. | [
"Write",
"the",
"XML",
"model",
"for",
"this",
"analysis",
"component",
"."
] | python | train |
OSSOS/MOP | src/ossos/plotting/scripts/rose_topdown.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/plotting/scripts/rose_topdown.py#L247-L286 | def orbit_fit_residuals(discoveries, blockID='O13AE'):
"""Brett: What are relevant and stunning are the actual orbit fit residuals
for orbits with d(a)/a<1%. I would be happy with a simple histogram of all those numbers,
although the 'tail' (probably blended and not yet completely flagged) should
perhap... | [
"def",
"orbit_fit_residuals",
"(",
"discoveries",
",",
"blockID",
"=",
"'O13AE'",
")",
":",
"ra_residuals",
"=",
"[",
"]",
"dec_residuals",
"=",
"[",
"]",
"ressum",
"=",
"[",
"]",
"for",
"i",
",",
"orbit",
"in",
"enumerate",
"(",
"discoveries",
")",
":",... | Brett: What are relevant and stunning are the actual orbit fit residuals
for orbits with d(a)/a<1%. I would be happy with a simple histogram of all those numbers,
although the 'tail' (probably blended and not yet completely flagged) should
perhaps be excluded. There will be a pretty clear gaussian I would ... | [
"Brett",
":",
"What",
"are",
"relevant",
"and",
"stunning",
"are",
"the",
"actual",
"orbit",
"fit",
"residuals",
"for",
"orbits",
"with",
"d",
"(",
"a",
")",
"/",
"a<1%",
".",
"I",
"would",
"be",
"happy",
"with",
"a",
"simple",
"histogram",
"of",
"all"... | python | train |
EntilZha/PyFunctional | functional/execution.py | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/execution.py#L17-L32 | def evaluate(self, sequence, transformations):
"""
Execute the sequence of transformations in serial
:param sequence: Sequence to evaluation
:param transformations: Transformations to apply
:return: Resulting sequence or value
"""
# pylint: disable=no-self-use
... | [
"def",
"evaluate",
"(",
"self",
",",
"sequence",
",",
"transformations",
")",
":",
"# pylint: disable=no-self-use",
"result",
"=",
"sequence",
"for",
"transform",
"in",
"transformations",
":",
"strategies",
"=",
"transform",
".",
"execution_strategies",
"if",
"strat... | Execute the sequence of transformations in serial
:param sequence: Sequence to evaluation
:param transformations: Transformations to apply
:return: Resulting sequence or value | [
"Execute",
"the",
"sequence",
"of",
"transformations",
"in",
"serial",
":",
"param",
"sequence",
":",
"Sequence",
"to",
"evaluation",
":",
"param",
"transformations",
":",
"Transformations",
"to",
"apply",
":",
"return",
":",
"Resulting",
"sequence",
"or",
"valu... | python | train |
seequent/properties | properties/basic.py | https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L685-L706 | def sphinx(self):
"""Basic docstring formatted for Sphinx docs"""
if callable(self.default):
default_val = self.default()
default_str = 'new instance of {}'.format(
default_val.__class__.__name__
)
else:
default_val = self.default
... | [
"def",
"sphinx",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"self",
".",
"default",
")",
":",
"default_val",
"=",
"self",
".",
"default",
"(",
")",
"default_str",
"=",
"'new instance of {}'",
".",
"format",
"(",
"default_val",
".",
"__class__",
".",
"... | Basic docstring formatted for Sphinx docs | [
"Basic",
"docstring",
"formatted",
"for",
"Sphinx",
"docs"
] | python | train |
SpockBotMC/SpockBot | spockbot/vector.py | https://github.com/SpockBotMC/SpockBot/blob/f89911551f18357720034fbaa52837a0d09f66ea/spockbot/vector.py#L114-L117 | def dist_cubic(self, other=None):
""" Manhattan distance """
v = self - other if other else self
return sum(map(abs, v.vector)) | [
"def",
"dist_cubic",
"(",
"self",
",",
"other",
"=",
"None",
")",
":",
"v",
"=",
"self",
"-",
"other",
"if",
"other",
"else",
"self",
"return",
"sum",
"(",
"map",
"(",
"abs",
",",
"v",
".",
"vector",
")",
")"
] | Manhattan distance | [
"Manhattan",
"distance"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/lib/latextools.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/latextools.py#L34-L58 | def latex_to_png(s, encode=False, backend='mpl'):
"""Render a LaTeX string to PNG.
Parameters
----------
s : str
The raw string containing valid inline LaTeX.
encode : bool, optional
Should the PNG data bebase64 encoded to make it JSON'able.
backend : {mpl, dvipng}
Backe... | [
"def",
"latex_to_png",
"(",
"s",
",",
"encode",
"=",
"False",
",",
"backend",
"=",
"'mpl'",
")",
":",
"if",
"backend",
"==",
"'mpl'",
":",
"f",
"=",
"latex_to_png_mpl",
"elif",
"backend",
"==",
"'dvipng'",
":",
"f",
"=",
"latex_to_png_dvipng",
"else",
":... | Render a LaTeX string to PNG.
Parameters
----------
s : str
The raw string containing valid inline LaTeX.
encode : bool, optional
Should the PNG data bebase64 encoded to make it JSON'able.
backend : {mpl, dvipng}
Backend for producing PNG data.
None is returned when the... | [
"Render",
"a",
"LaTeX",
"string",
"to",
"PNG",
"."
] | python | test |
mitsei/dlkit | dlkit/handcar/relationship/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/relationship/sessions.py#L87-L97 | def get_family(self):
"""Gets the ``Family`` associated with this session.
return: (osid.relationship.Family) - the family
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemen... | [
"def",
"get_family",
"(",
"self",
")",
":",
"return",
"FamilyLookupSession",
"(",
"proxy",
"=",
"self",
".",
"_proxy",
",",
"runtime",
"=",
"self",
".",
"_runtime",
")",
".",
"get_family",
"(",
"self",
".",
"_family_id",
")"
] | Gets the ``Family`` associated with this session.
return: (osid.relationship.Family) - the family
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"Family",
"associated",
"with",
"this",
"session",
"."
] | python | train |
ambitioninc/newrelic-api | newrelic_api/alert_policies.py | https://github.com/ambitioninc/newrelic-api/blob/07b4430aa6ae61e4704e2928a6e7a24c76f0f424/newrelic_api/alert_policies.py#L90-L132 | def update(self, id, name, incident_preference):
"""
This API endpoint allows you to update an alert policy
:type id: integer
:param id: The id of the policy
:type name: str
:param name: The name of the policy
:type incident_preference: str
:param incid... | [
"def",
"update",
"(",
"self",
",",
"id",
",",
"name",
",",
"incident_preference",
")",
":",
"data",
"=",
"{",
"\"policy\"",
":",
"{",
"\"name\"",
":",
"name",
",",
"\"incident_preference\"",
":",
"incident_preference",
"}",
"}",
"return",
"self",
".",
"_pu... | This API endpoint allows you to update an alert policy
:type id: integer
:param id: The id of the policy
:type name: str
:param name: The name of the policy
:type incident_preference: str
:param incident_preference: Can be PER_POLICY, PER_CONDITION or
PER_C... | [
"This",
"API",
"endpoint",
"allows",
"you",
"to",
"update",
"an",
"alert",
"policy"
] | python | train |
reingart/gui2py | gui/doc/ext/autosummary/generate.py | https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/doc/ext/autosummary/generate.py#L274-L285 | def find_autosummary_in_files(filenames):
"""Find out what items are documented in source/*.rst.
See `find_autosummary_in_lines`.
"""
documented = []
for filename in filenames:
f = open(filename, 'r')
lines = f.read().splitlines()
documented.extend(find_autosummary_in_lines(... | [
"def",
"find_autosummary_in_files",
"(",
"filenames",
")",
":",
"documented",
"=",
"[",
"]",
"for",
"filename",
"in",
"filenames",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"splitlines",
"("... | Find out what items are documented in source/*.rst.
See `find_autosummary_in_lines`. | [
"Find",
"out",
"what",
"items",
"are",
"documented",
"in",
"source",
"/",
"*",
".",
"rst",
"."
] | python | test |
vkruoso/receita-tools | receita/tools/get.py | https://github.com/vkruoso/receita-tools/blob/fd62a252c76541c9feac6470b9048b31348ffe86/receita/tools/get.py#L88-L125 | def valid(self, cnpj):
"""Check if a CNPJ is valid.
We should avoid sending invalid CNPJ to the web service as we know
it is going to be a waste of bandwidth. Assumes CNPJ is a string.
"""
if len(cnpj) != 14:
return False
tam = 12
nums = cnpj[:tam]
... | [
"def",
"valid",
"(",
"self",
",",
"cnpj",
")",
":",
"if",
"len",
"(",
"cnpj",
")",
"!=",
"14",
":",
"return",
"False",
"tam",
"=",
"12",
"nums",
"=",
"cnpj",
"[",
":",
"tam",
"]",
"digs",
"=",
"cnpj",
"[",
"tam",
":",
"]",
"tot",
"=",
"0",
... | Check if a CNPJ is valid.
We should avoid sending invalid CNPJ to the web service as we know
it is going to be a waste of bandwidth. Assumes CNPJ is a string. | [
"Check",
"if",
"a",
"CNPJ",
"is",
"valid",
"."
] | python | train |
fabioz/PyDev.Debugger | _pydevd_frame_eval/pydevd_modify_bytecode.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_frame_eval/pydevd_modify_bytecode.py#L10-L43 | def _add_attr_values_from_insert_to_original(original_code, insert_code, insert_code_list, attribute_name, op_list):
"""
This function appends values of the attribute `attribute_name` of the inserted code to the original values,
and changes indexes inside inserted code. If some bytecode instruction in the ... | [
"def",
"_add_attr_values_from_insert_to_original",
"(",
"original_code",
",",
"insert_code",
",",
"insert_code_list",
",",
"attribute_name",
",",
"op_list",
")",
":",
"orig_value",
"=",
"getattr",
"(",
"original_code",
",",
"attribute_name",
")",
"insert_value",
"=",
... | This function appends values of the attribute `attribute_name` of the inserted code to the original values,
and changes indexes inside inserted code. If some bytecode instruction in the inserted code used to call argument
number i, after modification it calls argument n + i, where n - length of the values in ... | [
"This",
"function",
"appends",
"values",
"of",
"the",
"attribute",
"attribute_name",
"of",
"the",
"inserted",
"code",
"to",
"the",
"original",
"values",
"and",
"changes",
"indexes",
"inside",
"inserted",
"code",
".",
"If",
"some",
"bytecode",
"instruction",
"in"... | python | train |
CalebBell/fluids | fluids/two_phase.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L2399-L2481 | def two_phase_dP_acceleration(m, D, xi, xo, alpha_i, alpha_o, rho_li, rho_gi,
rho_lo=None, rho_go=None):
r'''This function handles calculation of two-phase liquid-gas pressure drop
due to acceleration for flow inside channels. This is a discrete
calculation for a segment wit... | [
"def",
"two_phase_dP_acceleration",
"(",
"m",
",",
"D",
",",
"xi",
",",
"xo",
",",
"alpha_i",
",",
"alpha_o",
",",
"rho_li",
",",
"rho_gi",
",",
"rho_lo",
"=",
"None",
",",
"rho_go",
"=",
"None",
")",
":",
"G",
"=",
"4",
"*",
"m",
"/",
"(",
"pi",... | r'''This function handles calculation of two-phase liquid-gas pressure drop
due to acceleration for flow inside channels. This is a discrete
calculation for a segment with a known difference in quality (and ideally
known inlet and outlet pressures so density dependence can be included).
.. math::... | [
"r",
"This",
"function",
"handles",
"calculation",
"of",
"two",
"-",
"phase",
"liquid",
"-",
"gas",
"pressure",
"drop",
"due",
"to",
"acceleration",
"for",
"flow",
"inside",
"channels",
".",
"This",
"is",
"a",
"discrete",
"calculation",
"for",
"a",
"segment"... | python | train |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L4510-L4535 | def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table
classes defined in this module when parsing XML documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWContentHandler):
... p... | [
"def",
"use_in",
"(",
"ContentHandler",
")",
":",
"ContentHandler",
"=",
"table",
".",
"use_in",
"(",
"ContentHandler",
")",
"def",
"startTable",
"(",
"self",
",",
"parent",
",",
"attrs",
",",
"__orig_startTable",
"=",
"ContentHandler",
".",
"startTable",
")",... | Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table
classes defined in this module when parsing XML documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(MyContentHand... | [
"Modify",
"ContentHandler",
"a",
"sub",
"-",
"class",
"of",
"pycbc_glue",
".",
"ligolw",
".",
"LIGOLWContentHandler",
"to",
"cause",
"it",
"to",
"use",
"the",
"Table",
"classes",
"defined",
"in",
"this",
"module",
"when",
"parsing",
"XML",
"documents",
"."
] | python | train |
basvandenbroek/gcloud_taskqueue | gcloud_taskqueue/taskqueue.py | https://github.com/basvandenbroek/gcloud_taskqueue/blob/b147b57f7c0ad9e8030ee9797d6526a448aa5007/gcloud_taskqueue/taskqueue.py#L98-L103 | def full_name(self):
"""Fully-qualified name used in taskqueues / tasks APIs"""
if self._full_name is None:
self._full_name = 'projects/{project}/taskqueues/{taskqueue}'.format(project=self.project,
taskqueue=se... | [
"def",
"full_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_full_name",
"is",
"None",
":",
"self",
".",
"_full_name",
"=",
"'projects/{project}/taskqueues/{taskqueue}'",
".",
"format",
"(",
"project",
"=",
"self",
".",
"project",
",",
"taskqueue",
"=",
"... | Fully-qualified name used in taskqueues / tasks APIs | [
"Fully",
"-",
"qualified",
"name",
"used",
"in",
"taskqueues",
"/",
"tasks",
"APIs"
] | python | train |
apple/turicreate | src/unity/python/turicreate/meta/bytecodetools/pyc_file.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/bytecodetools/pyc_file.py#L20-L39 | def extract(binary):
'''
Extract a code object from a binary pyc file.
:param binary: a sequence of bytes from a pyc file.
'''
if len(binary) <= 8:
raise Exception("Binary pyc must be greater than 8 bytes (got %i)" % len(binary))
magic = binary[:4]
MAGIC = get_magic()
... | [
"def",
"extract",
"(",
"binary",
")",
":",
"if",
"len",
"(",
"binary",
")",
"<=",
"8",
":",
"raise",
"Exception",
"(",
"\"Binary pyc must be greater than 8 bytes (got %i)\"",
"%",
"len",
"(",
"binary",
")",
")",
"magic",
"=",
"binary",
"[",
":",
"4",
"]",
... | Extract a code object from a binary pyc file.
:param binary: a sequence of bytes from a pyc file. | [
"Extract",
"a",
"code",
"object",
"from",
"a",
"binary",
"pyc",
"file",
".",
":",
"param",
"binary",
":",
"a",
"sequence",
"of",
"bytes",
"from",
"a",
"pyc",
"file",
"."
] | python | train |
svartalf/python-opus | opus/api/ctl.py | https://github.com/svartalf/python-opus/blob/a3c1d556d2772b5be659ddd08c033ddd4d566b3a/opus/api/ctl.py#L48-L56 | def set(request):
"""Set new CTL value to a encoder/decoder"""
def inner(func, obj, value):
result_code = func(obj, request, value)
if result_code is not constants.OK:
raise OpusError(result_code)
return inner | [
"def",
"set",
"(",
"request",
")",
":",
"def",
"inner",
"(",
"func",
",",
"obj",
",",
"value",
")",
":",
"result_code",
"=",
"func",
"(",
"obj",
",",
"request",
",",
"value",
")",
"if",
"result_code",
"is",
"not",
"constants",
".",
"OK",
":",
"rais... | Set new CTL value to a encoder/decoder | [
"Set",
"new",
"CTL",
"value",
"to",
"a",
"encoder",
"/",
"decoder"
] | python | train |
openstates/billy | billy/web/public/templatetags/customtags.py | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/templatetags/customtags.py#L77-L81 | def decimal_format(value, TWOPLACES=Decimal(100) ** -2):
'Format a decimal.Decimal like to 2 decimal places.'
if not isinstance(value, Decimal):
value = Decimal(str(value))
return value.quantize(TWOPLACES) | [
"def",
"decimal_format",
"(",
"value",
",",
"TWOPLACES",
"=",
"Decimal",
"(",
"100",
")",
"**",
"-",
"2",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Decimal",
")",
":",
"value",
"=",
"Decimal",
"(",
"str",
"(",
"value",
")",
")",
"ret... | Format a decimal.Decimal like to 2 decimal places. | [
"Format",
"a",
"decimal",
".",
"Decimal",
"like",
"to",
"2",
"decimal",
"places",
"."
] | python | train |
estnltk/estnltk | estnltk/syntax/utils.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/syntax/utils.py#L920-L979 | def build_trees_from_text( text, layer, **kwargs ):
''' Given a text object and the name of the layer where dependency syntactic
relations are stored, builds trees ( estnltk.syntax.utils.Tree objects )
from all the sentences of the text and returns as a list of Trees.
Uses the meth... | [
"def",
"build_trees_from_text",
"(",
"text",
",",
"layer",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"estnltk",
".",
"text",
"import",
"Text",
"assert",
"isinstance",
"(",
"text",
",",
"Text",
")",
",",
"'(!) Unexpected text argument! Should be Estnltk\\'s Text o... | Given a text object and the name of the layer where dependency syntactic
relations are stored, builds trees ( estnltk.syntax.utils.Tree objects )
from all the sentences of the text and returns as a list of Trees.
Uses the method build_trees_from_sentence() for acquiring trees of each... | [
"Given",
"a",
"text",
"object",
"and",
"the",
"name",
"of",
"the",
"layer",
"where",
"dependency",
"syntactic",
"relations",
"are",
"stored",
"builds",
"trees",
"(",
"estnltk",
".",
"syntax",
".",
"utils",
".",
"Tree",
"objects",
")",
"from",
"all",
"the",... | python | train |
aiven/pghoard | pghoard/wal.py | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/wal.py#L93-L103 | def construct_wal_name(sysinfo):
"""Get wal file name out of something like this:
{'dbname': '', 'systemid': '6181331723016416192', 'timeline': '1', 'xlogpos': '0/90001B0'}
"""
log_hex, seg_hex = sysinfo["xlogpos"].split("/", 1)
# seg_hex's topmost 8 bits are filename, low 24 bits are position in
... | [
"def",
"construct_wal_name",
"(",
"sysinfo",
")",
":",
"log_hex",
",",
"seg_hex",
"=",
"sysinfo",
"[",
"\"xlogpos\"",
"]",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"# seg_hex's topmost 8 bits are filename, low 24 bits are position in",
"# file which we are not intereste... | Get wal file name out of something like this:
{'dbname': '', 'systemid': '6181331723016416192', 'timeline': '1', 'xlogpos': '0/90001B0'} | [
"Get",
"wal",
"file",
"name",
"out",
"of",
"something",
"like",
"this",
":",
"{",
"dbname",
":",
"systemid",
":",
"6181331723016416192",
"timeline",
":",
"1",
"xlogpos",
":",
"0",
"/",
"90001B0",
"}"
] | python | train |
sammchardy/python-binance | binance/websockets.py | https://github.com/sammchardy/python-binance/blob/31c0d0a32f9edd528c6c2c1dd3044d9a34ce43cc/binance/websockets.py#L174-L218 | def start_kline_socket(self, symbol, callback, interval=Client.KLINE_INTERVAL_1MINUTE):
"""Start a websocket for symbol kline data
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams
:param symbol: required
:type symb... | [
"def",
"start_kline_socket",
"(",
"self",
",",
"symbol",
",",
"callback",
",",
"interval",
"=",
"Client",
".",
"KLINE_INTERVAL_1MINUTE",
")",
":",
"socket_name",
"=",
"'{}@kline_{}'",
".",
"format",
"(",
"symbol",
".",
"lower",
"(",
")",
",",
"interval",
")"... | Start a websocket for symbol kline data
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams
:param symbol: required
:type symbol: str
:param callback: callback function to handle messages
:type callback: funct... | [
"Start",
"a",
"websocket",
"for",
"symbol",
"kline",
"data"
] | python | train |
tensorlayer/tensorlayer | tensorlayer/prepro.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L794-L833 | def crop(x, wrg, hrg, is_random=False, row_index=0, col_index=1):
"""Randomly or centrally crop an image.
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
wrg : int
Size of width.
hrg : int
Size of height.
is_random : bo... | [
"def",
"crop",
"(",
"x",
",",
"wrg",
",",
"hrg",
",",
"is_random",
"=",
"False",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
")",
":",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"row_index",
"]",
",",
"x",
".",
"shape",
"[",
"col... | Randomly or centrally crop an image.
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
wrg : int
Size of width.
hrg : int
Size of height.
is_random : boolean,
If True, randomly crop, else central crop. Default is Fals... | [
"Randomly",
"or",
"centrally",
"crop",
"an",
"image",
"."
] | python | valid |
thiagokokada/livedumper | src/livedumper/dumper.py | https://github.com/thiagokokada/livedumper/blob/f6441283269b4a602cafea3be5cda9446fc64005/src/livedumper/dumper.py#L86-L114 | def open(self, url, quality):
"""Attempt to open stream from *url*.
Exits with '-1' (using self.exit()) in case of error, including
an error msg.
"""
self.original_url = url
try:
self.livestreamer = Livestreamer()
self._load_config()
... | [
"def",
"open",
"(",
"self",
",",
"url",
",",
"quality",
")",
":",
"self",
".",
"original_url",
"=",
"url",
"try",
":",
"self",
".",
"livestreamer",
"=",
"Livestreamer",
"(",
")",
"self",
".",
"_load_config",
"(",
")",
"streams",
"=",
"self",
".",
"li... | Attempt to open stream from *url*.
Exits with '-1' (using self.exit()) in case of error, including
an error msg. | [
"Attempt",
"to",
"open",
"stream",
"from",
"*",
"url",
"*",
"."
] | python | train |
jrabbit/taskd-client-py | taskc/transaction.py | https://github.com/jrabbit/taskd-client-py/blob/473f121eca7fdb358874c9c00827f9a6ecdcda4e/taskc/transaction.py#L12-L24 | def mk_message(org, user, key):
"""
Make message
"""
m = Message()
m['client'] = "taskc-py {0}".format(__version__)
m['protocol'] = "v1"
m['org'] = org
m['user'] = user
m['key'] = key
return m | [
"def",
"mk_message",
"(",
"org",
",",
"user",
",",
"key",
")",
":",
"m",
"=",
"Message",
"(",
")",
"m",
"[",
"'client'",
"]",
"=",
"\"taskc-py {0}\"",
".",
"format",
"(",
"__version__",
")",
"m",
"[",
"'protocol'",
"]",
"=",
"\"v1\"",
"m",
"[",
"'o... | Make message | [
"Make",
"message"
] | python | train |
wecatch/app-turbo | turbo/util.py | https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/util.py#L74-L86 | def default_encode(v):
"""convert ObjectId, datetime, date into string
"""
if isinstance(v, ObjectId):
return unicode_type(v)
if isinstance(v, datetime):
return format_time(v)
if isinstance(v, date):
return format_time(v)
return v | [
"def",
"default_encode",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"ObjectId",
")",
":",
"return",
"unicode_type",
"(",
"v",
")",
"if",
"isinstance",
"(",
"v",
",",
"datetime",
")",
":",
"return",
"format_time",
"(",
"v",
")",
"if",
"isi... | convert ObjectId, datetime, date into string | [
"convert",
"ObjectId",
"datetime",
"date",
"into",
"string"
] | python | train |
roboogle/gtkmvc3 | gtkmvco/gtkmvc3/model.py | https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/model.py#L46-L55 | def count_leaves(x):
"""
Return the number of non-sequence items in a given recursive sequence.
"""
if hasattr(x, 'keys'):
x = list(x.values())
if hasattr(x, '__getitem__'):
return sum(map(count_leaves, x))
return 1 | [
"def",
"count_leaves",
"(",
"x",
")",
":",
"if",
"hasattr",
"(",
"x",
",",
"'keys'",
")",
":",
"x",
"=",
"list",
"(",
"x",
".",
"values",
"(",
")",
")",
"if",
"hasattr",
"(",
"x",
",",
"'__getitem__'",
")",
":",
"return",
"sum",
"(",
"map",
"("... | Return the number of non-sequence items in a given recursive sequence. | [
"Return",
"the",
"number",
"of",
"non",
"-",
"sequence",
"items",
"in",
"a",
"given",
"recursive",
"sequence",
"."
] | python | train |
RedHatQE/Sentaku | examples/mini_example.py | https://github.com/RedHatQE/Sentaku/blob/b336cef5b6ee2db4e8dff28dcdb2be35a1f3d01c/examples/mini_example.py#L85-L100 | def cli_main():
"""cli entrypoitns, sets up everything needed"""
SearchContext.commit()
args = parser.parse_args()
# open up a browser
firefox_remote = Remote("http://127.0.0.1:4444/wd/hub", DesiredCapabilities.FIREFOX)
with contextlib.closing(firefox_remote):
context = SearchContext.fro... | [
"def",
"cli_main",
"(",
")",
":",
"SearchContext",
".",
"commit",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"# open up a browser",
"firefox_remote",
"=",
"Remote",
"(",
"\"http://127.0.0.1:4444/wd/hub\"",
",",
"DesiredCapabilities",
".",
"FIREF... | cli entrypoitns, sets up everything needed | [
"cli",
"entrypoitns",
"sets",
"up",
"everything",
"needed"
] | python | train |
fhs/pyhdf | pyhdf/SD.py | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/SD.py#L1536-L1558 | def setfillmode(self, fill_mode):
"""Set the fill mode for all the datasets in the file.
Args::
fill_mode : fill mode; one of :
SDC.FILL write the fill value to all the datasets
of the file by default
SDC.NOF... | [
"def",
"setfillmode",
"(",
"self",
",",
"fill_mode",
")",
":",
"if",
"not",
"fill_mode",
"in",
"[",
"SDC",
".",
"FILL",
",",
"SDC",
".",
"NOFILL",
"]",
":",
"raise",
"HDF4Error",
"(",
"\"bad fill mode\"",
")",
"old_mode",
"=",
"_C",
".",
"SDsetfillmode",... | Set the fill mode for all the datasets in the file.
Args::
fill_mode : fill mode; one of :
SDC.FILL write the fill value to all the datasets
of the file by default
SDC.NOFILL do not write fill values to all datasets
... | [
"Set",
"the",
"fill",
"mode",
"for",
"all",
"the",
"datasets",
"in",
"the",
"file",
"."
] | python | train |
trac-hacks/trac-github | tracext/github/__init__.py | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L588-L599 | def members(self):
"""
Return a list of all users in this organization. Users are identified
by their login name. Note that this is computed from the teams in the
organization, because GitHub does not currently offer a WebHook for
organization membership, so converting org member... | [
"def",
"members",
"(",
"self",
")",
":",
"allmembers",
"=",
"set",
"(",
")",
"for",
"team",
"in",
"self",
".",
"teams",
"(",
")",
":",
"allmembers",
".",
"update",
"(",
"team",
".",
"members",
"(",
")",
")",
"return",
"sorted",
"(",
"allmembers",
"... | Return a list of all users in this organization. Users are identified
by their login name. Note that this is computed from the teams in the
organization, because GitHub does not currently offer a WebHook for
organization membership, so converting org membership would lead to
stale data. | [
"Return",
"a",
"list",
"of",
"all",
"users",
"in",
"this",
"organization",
".",
"Users",
"are",
"identified",
"by",
"their",
"login",
"name",
".",
"Note",
"that",
"this",
"is",
"computed",
"from",
"the",
"teams",
"in",
"the",
"organization",
"because",
"Gi... | python | train |
graphql-python/graphql-core | graphql/language/parser.py | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L199-L210 | def any(parser, open_kind, parse_fn, close_kind):
# type: (Parser, int, Callable, int) -> Any
"""Returns a possibly empty list of parse nodes, determined by
the parse_fn. This list begins with a lex token of openKind
and ends with a lex token of closeKind. Advances the parser
to the next lex token a... | [
"def",
"any",
"(",
"parser",
",",
"open_kind",
",",
"parse_fn",
",",
"close_kind",
")",
":",
"# type: (Parser, int, Callable, int) -> Any",
"expect",
"(",
"parser",
",",
"open_kind",
")",
"nodes",
"=",
"[",
"]",
"while",
"not",
"skip",
"(",
"parser",
",",
"c... | Returns a possibly empty list of parse nodes, determined by
the parse_fn. This list begins with a lex token of openKind
and ends with a lex token of closeKind. Advances the parser
to the next lex token after the closing token. | [
"Returns",
"a",
"possibly",
"empty",
"list",
"of",
"parse",
"nodes",
"determined",
"by",
"the",
"parse_fn",
".",
"This",
"list",
"begins",
"with",
"a",
"lex",
"token",
"of",
"openKind",
"and",
"ends",
"with",
"a",
"lex",
"token",
"of",
"closeKind",
".",
... | python | train |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L361-L403 | def getExtentAddress(self, zoom, extent=None, contained=False):
"""
Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based
on the instance's extent or a user defined extent. Generic method
that works with regular and irregular pyramids.
Parameters:
zoom... | [
"def",
"getExtentAddress",
"(",
"self",
",",
"zoom",
",",
"extent",
"=",
"None",
",",
"contained",
"=",
"False",
")",
":",
"if",
"extent",
":",
"bbox",
"=",
"extent",
"else",
":",
"bbox",
"=",
"self",
".",
"extent",
"minX",
"=",
"bbox",
"[",
"0",
"... | Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based
on the instance's extent or a user defined extent. Generic method
that works with regular and irregular pyramids.
Parameters:
zoom -- the zoom for which we want the bounding addresses
extent (optional) ... | [
"Return",
"the",
"bounding",
"addresses",
"(",
"[",
"minRow",
"minCol",
"maxRow",
"maxCol",
"]",
"based",
"on",
"the",
"instance",
"s",
"extent",
"or",
"a",
"user",
"defined",
"extent",
".",
"Generic",
"method",
"that",
"works",
"with",
"regular",
"and",
"... | python | train |
enkore/i3pystatus | i3pystatus/sabnzbd.py | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/sabnzbd.py#L108-L111 | def open_browser(self):
"""Open the URL of SABnzbd inside a browser."""
webbrowser.open(
"http://{host}:{port}/".format(host=self.host, port=self.port)) | [
"def",
"open_browser",
"(",
"self",
")",
":",
"webbrowser",
".",
"open",
"(",
"\"http://{host}:{port}/\"",
".",
"format",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
")",
")"
] | Open the URL of SABnzbd inside a browser. | [
"Open",
"the",
"URL",
"of",
"SABnzbd",
"inside",
"a",
"browser",
"."
] | python | train |
aio-libs/aioredis | aioredis/pubsub.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/pubsub.py#L295-L299 | def is_active(self):
"""Returns True if listener has any active subscription."""
if self._queue.exhausted:
return False
return any(ch.is_active for ch in self._refs.values()) | [
"def",
"is_active",
"(",
"self",
")",
":",
"if",
"self",
".",
"_queue",
".",
"exhausted",
":",
"return",
"False",
"return",
"any",
"(",
"ch",
".",
"is_active",
"for",
"ch",
"in",
"self",
".",
"_refs",
".",
"values",
"(",
")",
")"
] | Returns True if listener has any active subscription. | [
"Returns",
"True",
"if",
"listener",
"has",
"any",
"active",
"subscription",
"."
] | python | train |
dswah/pyGAM | pygam/pygam.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2112-L2162 | def _bootstrap_samples_of_smoothing(self, X, y, weights=None,
n_bootstraps=1, objective='auto'):
"""Sample the smoothing parameters using simulated response data.
For now, the grid of `lam` values is 11 random points in M-dimensional
space, where M = the... | [
"def",
"_bootstrap_samples_of_smoothing",
"(",
"self",
",",
"X",
",",
"y",
",",
"weights",
"=",
"None",
",",
"n_bootstraps",
"=",
"1",
",",
"objective",
"=",
"'auto'",
")",
":",
"mu",
"=",
"self",
".",
"predict_mu",
"(",
"X",
")",
"# Wood pg. 198 step 1",
... | Sample the smoothing parameters using simulated response data.
For now, the grid of `lam` values is 11 random points in M-dimensional
space, where M = the number of lam values, ie len(flatten(gam.lam))
all values are in [1e-3, 1e3] | [
"Sample",
"the",
"smoothing",
"parameters",
"using",
"simulated",
"response",
"data",
"."
] | python | train |
nickmckay/LiPD-utilities | Python/lipd/doi_resolver.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/doi_resolver.py#L149-L173 | def compile_fetch(self, raw, doi_id):
"""
Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict:
"""
fetch_dict = OrderedDict()
order = {'author': 'author', 'type': 'typ... | [
"def",
"compile_fetch",
"(",
"self",
",",
"raw",
",",
"doi_id",
")",
":",
"fetch_dict",
"=",
"OrderedDict",
"(",
")",
"order",
"=",
"{",
"'author'",
":",
"'author'",
",",
"'type'",
":",
"'type'",
",",
"'identifier'",
":",
"''",
",",
"'title'",
":",
"'t... | Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict: | [
"Loop",
"over",
"Raw",
"and",
"add",
"selected",
"items",
"to",
"Fetch",
"with",
"proper",
"formatting",
":",
"param",
"dict",
"raw",
":",
"JSON",
"data",
"from",
"doi",
".",
"org",
":",
"param",
"str",
"doi_id",
":",
":",
"return",
"dict",
":"
] | python | train |
gtaylor/django-athumb | athumb/pial/engines/pil_engine.py | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/pial/engines/pil_engine.py#L35-L50 | def is_valid_image(self, raw_data):
"""
Checks if the supplied raw data is valid image data.
:param str raw_data: A string representation of the image data.
:rtype: bool
:returns: ``True`` if ``raw_data`` is valid, ``False`` if not.
"""
buf = StringIO(raw_data)
... | [
"def",
"is_valid_image",
"(",
"self",
",",
"raw_data",
")",
":",
"buf",
"=",
"StringIO",
"(",
"raw_data",
")",
"try",
":",
"trial_image",
"=",
"Image",
".",
"open",
"(",
"buf",
")",
"trial_image",
".",
"verify",
"(",
")",
"except",
"Exception",
":",
"#... | Checks if the supplied raw data is valid image data.
:param str raw_data: A string representation of the image data.
:rtype: bool
:returns: ``True`` if ``raw_data`` is valid, ``False`` if not. | [
"Checks",
"if",
"the",
"supplied",
"raw",
"data",
"is",
"valid",
"image",
"data",
"."
] | python | train |
nerdvegas/rez | src/rez/resolved_context.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L922-L933 | def get_environ(self, parent_environ=None):
"""Get the environ dict resulting from interpreting this context.
@param parent_environ Environment to interpret the context within,
defaults to os.environ if None.
@returns The environment dict generated by this context, when
... | [
"def",
"get_environ",
"(",
"self",
",",
"parent_environ",
"=",
"None",
")",
":",
"interp",
"=",
"Python",
"(",
"target_environ",
"=",
"{",
"}",
",",
"passive",
"=",
"True",
")",
"executor",
"=",
"self",
".",
"_create_executor",
"(",
"interp",
",",
"paren... | Get the environ dict resulting from interpreting this context.
@param parent_environ Environment to interpret the context within,
defaults to os.environ if None.
@returns The environment dict generated by this context, when
interpreted in a python rex interpreter. | [
"Get",
"the",
"environ",
"dict",
"resulting",
"from",
"interpreting",
"this",
"context",
"."
] | python | train |
brutasse/graphite-api | graphite_api/_vendor/whisper.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/_vendor/whisper.py#L322-L370 | def validateArchiveList(archiveList):
""" Validates an archiveList.
An ArchiveList must:
1. Have at least one archive config. Example: (60, 86400)
2. No archive may be a duplicate of another.
3. Higher precision archives' precision must evenly divide all lower precision archives' precision.
4. Lower precisi... | [
"def",
"validateArchiveList",
"(",
"archiveList",
")",
":",
"if",
"not",
"archiveList",
":",
"raise",
"InvalidConfiguration",
"(",
"\"You must specify at least one archive configuration!\"",
")",
"archiveList",
"=",
"sorted",
"(",
"archiveList",
",",
"key",
"=",
"lambda... | Validates an archiveList.
An ArchiveList must:
1. Have at least one archive config. Example: (60, 86400)
2. No archive may be a duplicate of another.
3. Higher precision archives' precision must evenly divide all lower precision archives' precision.
4. Lower precision archives must cover larger time intervals... | [
"Validates",
"an",
"archiveList",
".",
"An",
"ArchiveList",
"must",
":",
"1",
".",
"Have",
"at",
"least",
"one",
"archive",
"config",
".",
"Example",
":",
"(",
"60",
"86400",
")",
"2",
".",
"No",
"archive",
"may",
"be",
"a",
"duplicate",
"of",
"another... | python | train |
apache/incubator-heron | heronpy/api/component/component_spec.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/component/component_spec.py#L275-L288 | def get_out_streamids(self):
"""Returns a set of output stream ids registered for this component"""
if self.outputs is None:
return set()
if not isinstance(self.outputs, (list, tuple)):
raise TypeError("Argument to outputs must be either list or tuple, given: %s"
% str(typ... | [
"def",
"get_out_streamids",
"(",
"self",
")",
":",
"if",
"self",
".",
"outputs",
"is",
"None",
":",
"return",
"set",
"(",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"outputs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError"... | Returns a set of output stream ids registered for this component | [
"Returns",
"a",
"set",
"of",
"output",
"stream",
"ids",
"registered",
"for",
"this",
"component"
] | python | valid |
quantumlib/Cirq | cirq/linalg/combinators.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/combinators.py#L104-L133 | def block_diag(*blocks: np.ndarray) -> np.ndarray:
"""Concatenates blocks into a block diagonal matrix.
Args:
*blocks: Square matrices to place along the diagonal of the result.
Returns:
A block diagonal matrix with the given blocks along its diagonal.
Raises:
ValueError: A bl... | [
"def",
"block_diag",
"(",
"*",
"blocks",
":",
"np",
".",
"ndarray",
")",
"->",
"np",
".",
"ndarray",
":",
"for",
"b",
"in",
"blocks",
":",
"if",
"b",
".",
"shape",
"[",
"0",
"]",
"!=",
"b",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError... | Concatenates blocks into a block diagonal matrix.
Args:
*blocks: Square matrices to place along the diagonal of the result.
Returns:
A block diagonal matrix with the given blocks along its diagonal.
Raises:
ValueError: A block isn't square. | [
"Concatenates",
"blocks",
"into",
"a",
"block",
"diagonal",
"matrix",
"."
] | python | train |
pandas-dev/pandas | pandas/core/internals/managers.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/internals/managers.py#L186-L204 | def _rebuild_blknos_and_blklocs(self):
"""
Update mgr._blknos / mgr._blklocs.
"""
new_blknos = np.empty(self.shape[0], dtype=np.int64)
new_blklocs = np.empty(self.shape[0], dtype=np.int64)
new_blknos.fill(-1)
new_blklocs.fill(-1)
for blkno, blk in enumera... | [
"def",
"_rebuild_blknos_and_blklocs",
"(",
"self",
")",
":",
"new_blknos",
"=",
"np",
".",
"empty",
"(",
"self",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"new_blklocs",
"=",
"np",
".",
"empty",
"(",
"self",
".",
"shape... | Update mgr._blknos / mgr._blklocs. | [
"Update",
"mgr",
".",
"_blknos",
"/",
"mgr",
".",
"_blklocs",
"."
] | python | train |
saltstack/salt | salt/utils/msgpack.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msgpack.py#L20-L38 | def pack(o, stream, **kwargs):
'''
.. versionadded:: 2018.3.4
Wraps msgpack.pack and ensures that the passed object is unwrapped if it is
a proxy.
By default, this function uses the msgpack module and falls back to
msgpack_pure, if the msgpack is not available. You can pass an alternate
ms... | [
"def",
"pack",
"(",
"o",
",",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"msgpack_module",
"=",
"kwargs",
".",
"pop",
"(",
"'_msgpack_module'",
",",
"msgpack",
")",
"orig_enc_func",
"=",
"kwargs",
".",
"pop",
"(",
"'default'",
",",
"lambda",
"x",
":"... | .. versionadded:: 2018.3.4
Wraps msgpack.pack and ensures that the passed object is unwrapped if it is
a proxy.
By default, this function uses the msgpack module and falls back to
msgpack_pure, if the msgpack is not available. You can pass an alternate
msgpack module using the _msgpack_module argu... | [
"..",
"versionadded",
"::",
"2018",
".",
"3",
".",
"4"
] | python | train |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/input_processor.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/input_processor.py#L204-L227 | def process_keys(self):
"""
Process all the keys in the `input_queue`.
(To be called after `feed`.)
Note: because of the `feed`/`process_keys` separation, it is
possible to call `feed` from inside a key binding.
This function keeps looping until the queue is ... | [
"def",
"process_keys",
"(",
"self",
")",
":",
"while",
"self",
".",
"input_queue",
":",
"key_press",
"=",
"self",
".",
"input_queue",
".",
"popleft",
"(",
")",
"if",
"key_press",
".",
"key",
"!=",
"Keys",
".",
"CPRResponse",
":",
"self",
".",
"beforeKeyP... | Process all the keys in the `input_queue`.
(To be called after `feed`.)
Note: because of the `feed`/`process_keys` separation, it is
possible to call `feed` from inside a key binding.
This function keeps looping until the queue is empty. | [
"Process",
"all",
"the",
"keys",
"in",
"the",
"input_queue",
".",
"(",
"To",
"be",
"called",
"after",
"feed",
".",
")"
] | python | train |
apache/incubator-mxnet | python/mxnet/ndarray/sparse.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L1421-L1503 | def divide(lhs, rhs):
"""Returns element-wise division of the input arrays with broadcasting.
Equivalent to ``lhs / rhs`` and ``mx.nd.broadcast_div(lhs, rhs)``
when shapes of lhs and rhs do not match. If lhs.shape == rhs.shape,
this is equivalent to ``mx.nd.elemwise_div(lhs, rhs)``
.. note::
... | [
"def",
"divide",
"(",
"lhs",
",",
"rhs",
")",
":",
"# pylint: disable= no-member, protected-access",
"if",
"isinstance",
"(",
"lhs",
",",
"NDArray",
")",
"and",
"isinstance",
"(",
"rhs",
",",
"NDArray",
")",
"and",
"lhs",
".",
"shape",
"==",
"rhs",
".",
"s... | Returns element-wise division of the input arrays with broadcasting.
Equivalent to ``lhs / rhs`` and ``mx.nd.broadcast_div(lhs, rhs)``
when shapes of lhs and rhs do not match. If lhs.shape == rhs.shape,
this is equivalent to ``mx.nd.elemwise_div(lhs, rhs)``
.. note::
If the corresponding dime... | [
"Returns",
"element",
"-",
"wise",
"division",
"of",
"the",
"input",
"arrays",
"with",
"broadcasting",
"."
] | python | train |
NICTA/revrand | revrand/likelihoods.py | https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/likelihoods.py#L456-L481 | def loglike(self, y, f):
r"""
Poisson log likelihood.
Parameters
----------
y: ndarray
array of integer targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
--... | [
"def",
"loglike",
"(",
"self",
",",
"y",
",",
"f",
")",
":",
"y",
",",
"f",
"=",
"np",
".",
"broadcast_arrays",
"(",
"y",
",",
"f",
")",
"if",
"self",
".",
"tranfcn",
"==",
"'exp'",
":",
"g",
"=",
"np",
".",
"exp",
"(",
"f",
")",
"logg",
"=... | r"""
Poisson log likelihood.
Parameters
----------
y: ndarray
array of integer targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
-------
logp: ndarray
... | [
"r",
"Poisson",
"log",
"likelihood",
"."
] | python | train |
majerteam/sqla_inspect | sqla_inspect/py3o.py | https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/py3o.py#L318-L327 | def _get_relationship_value(self, obj, column):
"""
Compute datas produced for a given relationship
"""
if column['__col__'].uselist:
value = self._get_to_many_relationship_value(obj, column)
else:
value = self._get_to_one_relationship_value(obj, column)
... | [
"def",
"_get_relationship_value",
"(",
"self",
",",
"obj",
",",
"column",
")",
":",
"if",
"column",
"[",
"'__col__'",
"]",
".",
"uselist",
":",
"value",
"=",
"self",
".",
"_get_to_many_relationship_value",
"(",
"obj",
",",
"column",
")",
"else",
":",
"valu... | Compute datas produced for a given relationship | [
"Compute",
"datas",
"produced",
"for",
"a",
"given",
"relationship"
] | python | train |
PyGithub/PyGithub | github/Organization.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/Organization.py#L353-L379 | def create_hook(self, name, config, events=github.GithubObject.NotSet, active=github.GithubObject.NotSet):
"""
:calls: `POST /orgs/:owner/hooks <http://developer.github.com/v3/orgs/hooks>`_
:param name: string
:param config: dict
:param events: list of string
:param activ... | [
"def",
"create_hook",
"(",
"self",
",",
"name",
",",
"config",
",",
"events",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"active",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"(",
... | :calls: `POST /orgs/:owner/hooks <http://developer.github.com/v3/orgs/hooks>`_
:param name: string
:param config: dict
:param events: list of string
:param active: bool
:rtype: :class:`github.Hook.Hook` | [
":",
"calls",
":",
"POST",
"/",
"orgs",
"/",
":",
"owner",
"/",
"hooks",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"orgs",
"/",
"hooks",
">",
"_",
":",
"param",
"name",
":",
"string",
":",
"param",
"config",
":",... | python | train |
googleapis/google-cloud-python | api_core/google/api_core/protobuf_helpers.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/protobuf_helpers.py#L201-L226 | def _set_field_on_message(msg, key, value):
"""Set helper for protobuf Messages."""
# Attempt to set the value on the types of objects we know how to deal
# with.
if isinstance(value, (collections_abc.MutableSequence, tuple)):
# Clear the existing repeated protobuf message of any elements
... | [
"def",
"_set_field_on_message",
"(",
"msg",
",",
"key",
",",
"value",
")",
":",
"# Attempt to set the value on the types of objects we know how to deal",
"# with.",
"if",
"isinstance",
"(",
"value",
",",
"(",
"collections_abc",
".",
"MutableSequence",
",",
"tuple",
")",... | Set helper for protobuf Messages. | [
"Set",
"helper",
"for",
"protobuf",
"Messages",
"."
] | python | train |
suryakencana007/baka_model | baka_model/model/meta/schema.py | https://github.com/suryakencana007/baka_model/blob/915c2da9920e973302f5764ae63799acd5ecf0b7/baka_model/model/meta/schema.py#L42-L58 | def _reference_table(cls, ref_table):
"""Create a foreign key reference from the local class to the given remote
table.
Adds column references to the declarative class and adds a
ForeignKeyConstraint.
"""
# create pairs of (Foreign key column, primary key column)
... | [
"def",
"_reference_table",
"(",
"cls",
",",
"ref_table",
")",
":",
"# create pairs of (Foreign key column, primary key column)",
"cols",
"=",
"[",
"(",
"sa",
".",
"Column",
"(",
")",
",",
"refcol",
")",
"for",
"refcol",
"in",
"ref_table",
".",
"primary_key",
"]"... | Create a foreign key reference from the local class to the given remote
table.
Adds column references to the declarative class and adds a
ForeignKeyConstraint. | [
"Create",
"a",
"foreign",
"key",
"reference",
"from",
"the",
"local",
"class",
"to",
"the",
"given",
"remote",
"table",
"."
] | python | valid |
walkr/nanoservice | setup.py | https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/setup.py#L13-L27 | def read_long_description(readme_file):
""" Read package long description from README file """
try:
import pypandoc
except (ImportError, OSError) as exception:
print('No pypandoc or pandoc: %s' % (exception,))
if sys.version_info.major == 3:
handle = open(readme_file, enc... | [
"def",
"read_long_description",
"(",
"readme_file",
")",
":",
"try",
":",
"import",
"pypandoc",
"except",
"(",
"ImportError",
",",
"OSError",
")",
"as",
"exception",
":",
"print",
"(",
"'No pypandoc or pandoc: %s'",
"%",
"(",
"exception",
",",
")",
")",
"if",
... | Read package long description from README file | [
"Read",
"package",
"long",
"description",
"from",
"README",
"file"
] | python | train |
6809/MC6809 | MC6809/components/mc6809_ops_branches.py | https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_ops_branches.py#L193-L211 | def instruction_BHI(self, opcode, ea):
"""
Causes a branch if the previous operation caused neither a carry nor a
zero result. When used after a subtract or compare operation on unsigned
binary values, this instruction will branch if the register was higher
than the memory regist... | [
"def",
"instruction_BHI",
"(",
"self",
",",
"opcode",
",",
"ea",
")",
":",
"if",
"self",
".",
"C",
"==",
"0",
"and",
"self",
".",
"Z",
"==",
"0",
":",
"# log.info(\"$%x BHI branch to $%x, because C==0 and Z==0 \\t| %s\" % (",
"# self.program_... | Causes a branch if the previous operation caused neither a carry nor a
zero result. When used after a subtract or compare operation on unsigned
binary values, this instruction will branch if the register was higher
than the memory register.
Generally not useful after INC/DEC, LD/TST, an... | [
"Causes",
"a",
"branch",
"if",
"the",
"previous",
"operation",
"caused",
"neither",
"a",
"carry",
"nor",
"a",
"zero",
"result",
".",
"When",
"used",
"after",
"a",
"subtract",
"or",
"compare",
"operation",
"on",
"unsigned",
"binary",
"values",
"this",
"instru... | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L983-L1000 | def hash32(data: Any, seed=0) -> int:
"""
Non-cryptographic, deterministic, fast hash.
Args:
data: data to hash
seed: seed
Returns:
signed 32-bit integer
"""
with MultiTimerContext(timer, TIMING_HASH):
c_data = to_str(data)
if mmh3:
return mm... | [
"def",
"hash32",
"(",
"data",
":",
"Any",
",",
"seed",
"=",
"0",
")",
"->",
"int",
":",
"with",
"MultiTimerContext",
"(",
"timer",
",",
"TIMING_HASH",
")",
":",
"c_data",
"=",
"to_str",
"(",
"data",
")",
"if",
"mmh3",
":",
"return",
"mmh3",
".",
"h... | Non-cryptographic, deterministic, fast hash.
Args:
data: data to hash
seed: seed
Returns:
signed 32-bit integer | [
"Non",
"-",
"cryptographic",
"deterministic",
"fast",
"hash",
"."
] | python | train |
jobovy/galpy | galpy/df/streamdf.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L1428-L1452 | def _interpolate_stream_track_aA(self):
"""Build interpolations of the stream track in action-angle coordinates"""
if hasattr(self,'_interpolatedObsTrackAA'):
return None #Already did this
#Calculate 1D meanOmega on a fine grid in angle and interpolate
if not hasattr(self,'_i... | [
"def",
"_interpolate_stream_track_aA",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_interpolatedObsTrackAA'",
")",
":",
"return",
"None",
"#Already did this",
"#Calculate 1D meanOmega on a fine grid in angle and interpolate",
"if",
"not",
"hasattr",
"(",
"... | Build interpolations of the stream track in action-angle coordinates | [
"Build",
"interpolations",
"of",
"the",
"stream",
"track",
"in",
"action",
"-",
"angle",
"coordinates"
] | python | train |
shichao-an/115wangpan | u115/api.py | https://github.com/shichao-an/115wangpan/blob/e7cc935313f675e886bceca831fcffcdedf1e880/u115/api.py#L450-L463 | def get_storage_info(self, human=False):
"""
Get storage info
:param bool human: whether return human-readable size
:return: total and used storage
:rtype: dict
"""
res = self._req_get_storage_info()
if human:
res['total'] = humanize.naturals... | [
"def",
"get_storage_info",
"(",
"self",
",",
"human",
"=",
"False",
")",
":",
"res",
"=",
"self",
".",
"_req_get_storage_info",
"(",
")",
"if",
"human",
":",
"res",
"[",
"'total'",
"]",
"=",
"humanize",
".",
"naturalsize",
"(",
"res",
"[",
"'total'",
"... | Get storage info
:param bool human: whether return human-readable size
:return: total and used storage
:rtype: dict | [
"Get",
"storage",
"info"
] | python | train |
jefflovejapan/drench | drench/drench.py | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/drench.py#L211-L262 | def handshake_peers(self):
'''
pstrlen = length of pstr as one byte
pstr = BitTorrent protocol
reserved = chr(0)*8
info_hash = 20-byte hash above (aka self.hash_string)
peer_id = 20-byte string
'''
pstr = 'BitTorrent protocol'
pstrlen = len(pstr)
... | [
"def",
"handshake_peers",
"(",
"self",
")",
":",
"pstr",
"=",
"'BitTorrent protocol'",
"pstrlen",
"=",
"len",
"(",
"pstr",
")",
"info_hash",
"=",
"self",
".",
"hash_string",
"peer_id",
"=",
"self",
".",
"peer_id",
"packet",
"=",
"''",
".",
"join",
"(",
"... | pstrlen = length of pstr as one byte
pstr = BitTorrent protocol
reserved = chr(0)*8
info_hash = 20-byte hash above (aka self.hash_string)
peer_id = 20-byte string | [
"pstrlen",
"=",
"length",
"of",
"pstr",
"as",
"one",
"byte",
"pstr",
"=",
"BitTorrent",
"protocol",
"reserved",
"=",
"chr",
"(",
"0",
")",
"*",
"8",
"info_hash",
"=",
"20",
"-",
"byte",
"hash",
"above",
"(",
"aka",
"self",
".",
"hash_string",
")",
"p... | python | train |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L151-L156 | def get_device_by_ain(self, ain):
"""Returns a device specified by the AIN."""
devices = self.get_devices()
for device in devices:
if device.ain == ain:
return device | [
"def",
"get_device_by_ain",
"(",
"self",
",",
"ain",
")",
":",
"devices",
"=",
"self",
".",
"get_devices",
"(",
")",
"for",
"device",
"in",
"devices",
":",
"if",
"device",
".",
"ain",
"==",
"ain",
":",
"return",
"device"
] | Returns a device specified by the AIN. | [
"Returns",
"a",
"device",
"specified",
"by",
"the",
"AIN",
"."
] | python | train |
johntfoster/bspline | bspline/splinelab.py | https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L81-L145 | def aptknt(tau, order):
"""Create an acceptable knot vector.
Minimal emulation of MATLAB's ``aptknt``.
The returned knot vector can be used to generate splines of desired `order`
that are suitable for interpolation to the collocation sites `tau`.
Note that this is only possible when ``len(tau)`` >= `order` + 1.
... | [
"def",
"aptknt",
"(",
"tau",
",",
"order",
")",
":",
"tau",
"=",
"np",
".",
"atleast_1d",
"(",
"tau",
")",
"k",
"=",
"order",
"+",
"1",
"if",
"tau",
".",
"ndim",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"tau must be a list or a rank-1 array\"",
")"... | Create an acceptable knot vector.
Minimal emulation of MATLAB's ``aptknt``.
The returned knot vector can be used to generate splines of desired `order`
that are suitable for interpolation to the collocation sites `tau`.
Note that this is only possible when ``len(tau)`` >= `order` + 1.
When this condition does not h... | [
"Create",
"an",
"acceptable",
"knot",
"vector",
"."
] | python | train |
openmicroanalysis/pyxray | pyxray/composition.py | https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L220-L236 | def from_mass_fractions(cls, mass_fractions, formula=None):
"""
Creates a composition from a mass fraction :class:`dict`.
Args:
mass_fractions (dict): mass fraction :class:`dict`.
The keys are atomic numbers and the values weight fractions.
Wildcard a... | [
"def",
"from_mass_fractions",
"(",
"cls",
",",
"mass_fractions",
",",
"formula",
"=",
"None",
")",
":",
"mass_fractions",
"=",
"process_wildcard",
"(",
"mass_fractions",
")",
"atomic_fractions",
"=",
"convert_mass_to_atomic_fractions",
"(",
"mass_fractions",
")",
"if"... | Creates a composition from a mass fraction :class:`dict`.
Args:
mass_fractions (dict): mass fraction :class:`dict`.
The keys are atomic numbers and the values weight fractions.
Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron
will get a m... | [
"Creates",
"a",
"composition",
"from",
"a",
"mass",
"fraction",
":",
"class",
":",
"dict",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/works.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/works.py#L609-L638 | def allocate(self, manager=None):
"""
This function is called once we have completed the initialization
of the :class:`Work`. It sets the manager of each task (if not already done)
and defines the working directories of the tasks.
Args:
manager: :class:`TaskManager` ... | [
"def",
"allocate",
"(",
"self",
",",
"manager",
"=",
"None",
")",
":",
"for",
"i",
",",
"task",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"task",
",",
"\"manager\"",
")",
":",
"# Set the manager",
"# Use the one provided in inp... | This function is called once we have completed the initialization
of the :class:`Work`. It sets the manager of each task (if not already done)
and defines the working directories of the tasks.
Args:
manager: :class:`TaskManager` object or None | [
"This",
"function",
"is",
"called",
"once",
"we",
"have",
"completed",
"the",
"initialization",
"of",
"the",
":",
"class",
":",
"Work",
".",
"It",
"sets",
"the",
"manager",
"of",
"each",
"task",
"(",
"if",
"not",
"already",
"done",
")",
"and",
"defines",... | python | train |
solidsnack/v2 | v2/__init__.py | https://github.com/solidsnack/v2/blob/95736855a0188cc892dea451617df0efbfa404de/v2/__init__.py#L45-L67 | def from_git(self, path=None, prefer_daily=False):
"""Use Git to determine the package version.
This routine uses the __file__ value of the caller to determine
which Git repository root to use.
"""
if self._version is None:
frame = caller(1)
path = ... | [
"def",
"from_git",
"(",
"self",
",",
"path",
"=",
"None",
",",
"prefer_daily",
"=",
"False",
")",
":",
"if",
"self",
".",
"_version",
"is",
"None",
":",
"frame",
"=",
"caller",
"(",
"1",
")",
"path",
"=",
"frame",
".",
"f_globals",
".",
"get",
"(",... | Use Git to determine the package version.
This routine uses the __file__ value of the caller to determine
which Git repository root to use. | [
"Use",
"Git",
"to",
"determine",
"the",
"package",
"version",
"."
] | python | train |
census-instrumentation/opencensus-python | contrib/opencensus-ext-requests/opencensus/ext/requests/trace.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-requests/opencensus/ext/requests/trace.py#L94-L133 | def wrap_session_request(wrapped, instance, args, kwargs):
"""Wrap the session function to trace it."""
method = kwargs.get('method') or args[0]
url = kwargs.get('url') or args[1]
blacklist_hostnames = execution_context.get_opencensus_attr(
'blacklist_hostnames')
parsed_url = urlparse(url)
... | [
"def",
"wrap_session_request",
"(",
"wrapped",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"method",
"=",
"kwargs",
".",
"get",
"(",
"'method'",
")",
"or",
"args",
"[",
"0",
"]",
"url",
"=",
"kwargs",
".",
"get",
"(",
"'url'",
")",
"or",
... | Wrap the session function to trace it. | [
"Wrap",
"the",
"session",
"function",
"to",
"trace",
"it",
"."
] | python | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/hhea.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/hhea.py#L14-L21 | def com_google_fonts_check_linegaps(ttFont):
"""Checking Vertical Metric Linegaps."""
if ttFont["hhea"].lineGap != 0:
yield WARN, Message("hhea", "hhea lineGap is not equal to 0.")
elif ttFont["OS/2"].sTypoLineGap != 0:
yield WARN, Message("OS/2", "OS/2 sTypoLineGap is not equal to 0.")
else:
yield ... | [
"def",
"com_google_fonts_check_linegaps",
"(",
"ttFont",
")",
":",
"if",
"ttFont",
"[",
"\"hhea\"",
"]",
".",
"lineGap",
"!=",
"0",
":",
"yield",
"WARN",
",",
"Message",
"(",
"\"hhea\"",
",",
"\"hhea lineGap is not equal to 0.\"",
")",
"elif",
"ttFont",
"[",
"... | Checking Vertical Metric Linegaps. | [
"Checking",
"Vertical",
"Metric",
"Linegaps",
"."
] | python | train |
inveniosoftware/invenio-access | invenio_access/cli.py | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/cli.py#L30-L35 | def lazy_result(f):
"""Decorate function to return LazyProxy."""
@wraps(f)
def decorated(ctx, param, value):
return LocalProxy(lambda: f(ctx, param, value))
return decorated | [
"def",
"lazy_result",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"return",
"LocalProxy",
"(",
"lambda",
":",
"f",
"(",
"ctx",
",",
"param",
",",
"value",
")",
")",
"retur... | Decorate function to return LazyProxy. | [
"Decorate",
"function",
"to",
"return",
"LazyProxy",
"."
] | python | train |
phfaist/pylatexenc | pylatexenc/latexwalker.py | https://github.com/phfaist/pylatexenc/blob/0c1788d1349e749501e67a6fba54d79e6e0d54f6/pylatexenc/latexwalker.py#L1284-L1293 | def get_latex_maybe_optional_arg(s, pos, **parse_flags):
"""
Attempts to parse an optional argument. Returns a tuple `(groupnode, pos, len)` if
success, otherwise returns None.
.. deprecated:: 1.0
Please use :py:meth:`LatexWalker.get_latex_maybe_optional_arg()` instead.
"""
return Latex... | [
"def",
"get_latex_maybe_optional_arg",
"(",
"s",
",",
"pos",
",",
"*",
"*",
"parse_flags",
")",
":",
"return",
"LatexWalker",
"(",
"s",
",",
"*",
"*",
"parse_flags",
")",
".",
"get_latex_maybe_optional_arg",
"(",
"pos",
"=",
"pos",
")"
] | Attempts to parse an optional argument. Returns a tuple `(groupnode, pos, len)` if
success, otherwise returns None.
.. deprecated:: 1.0
Please use :py:meth:`LatexWalker.get_latex_maybe_optional_arg()` instead. | [
"Attempts",
"to",
"parse",
"an",
"optional",
"argument",
".",
"Returns",
"a",
"tuple",
"(",
"groupnode",
"pos",
"len",
")",
"if",
"success",
"otherwise",
"returns",
"None",
"."
] | python | test |
Alignak-monitoring/alignak | alignak/http/client.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/client.py#L176-L188 | def set_proxy(self, proxy): # pragma: no cover, not with unit tests
"""Set HTTP proxy
:param proxy: proxy url
:type proxy: str
:return: None
"""
if proxy:
logger.debug('PROXY SETTING PROXY %s', proxy)
self._requests_con.proxies = {
... | [
"def",
"set_proxy",
"(",
"self",
",",
"proxy",
")",
":",
"# pragma: no cover, not with unit tests",
"if",
"proxy",
":",
"logger",
".",
"debug",
"(",
"'PROXY SETTING PROXY %s'",
",",
"proxy",
")",
"self",
".",
"_requests_con",
".",
"proxies",
"=",
"{",
"'http'",
... | Set HTTP proxy
:param proxy: proxy url
:type proxy: str
:return: None | [
"Set",
"HTTP",
"proxy"
] | python | train |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/operations.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/operations.py#L222-L225 | def _add_to_bulk(self, bulkobj):
"""Add this operation to the _Bulk instance `bulkobj`."""
bulkobj.add_update(self._filter, self._doc, False, self._upsert,
collation=self._collation) | [
"def",
"_add_to_bulk",
"(",
"self",
",",
"bulkobj",
")",
":",
"bulkobj",
".",
"add_update",
"(",
"self",
".",
"_filter",
",",
"self",
".",
"_doc",
",",
"False",
",",
"self",
".",
"_upsert",
",",
"collation",
"=",
"self",
".",
"_collation",
")"
] | Add this operation to the _Bulk instance `bulkobj`. | [
"Add",
"this",
"operation",
"to",
"the",
"_Bulk",
"instance",
"bulkobj",
"."
] | python | train |
jamieleshaw/lurklib | example.py | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/example.py#L30-L36 | def on_chanmsg(self, from_, channel, message):
""" Event handler for channel messages. """
if message == 'hello':
self.privmsg(channel, 'Hello, %s!' % from_[0])
print('%s said hello!' % from_[0])
elif message == '!quit':
self.quit('Bye!') | [
"def",
"on_chanmsg",
"(",
"self",
",",
"from_",
",",
"channel",
",",
"message",
")",
":",
"if",
"message",
"==",
"'hello'",
":",
"self",
".",
"privmsg",
"(",
"channel",
",",
"'Hello, %s!'",
"%",
"from_",
"[",
"0",
"]",
")",
"print",
"(",
"'%s said hell... | Event handler for channel messages. | [
"Event",
"handler",
"for",
"channel",
"messages",
"."
] | python | train |
saltstack/salt | salt/modules/disk.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L699-L769 | def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-... | [
"def",
"smart_attributes",
"(",
"dev",
",",
"attributes",
"=",
"None",
",",
"values",
"=",
"None",
")",
":",
"if",
"not",
"dev",
".",
"startswith",
"(",
"'/dev/'",
")",
":",
"dev",
"=",
"'/dev/'",
"+",
"dev",
"cmd",
"=",
"'smartctl --attributes {0}'",
".... | Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.... | [
"Fetch",
"SMART",
"attributes",
"Providing",
"attributes",
"will",
"deliver",
"only",
"requested",
"attributes",
"Providing",
"values",
"will",
"deliver",
"only",
"requested",
"values",
"for",
"attributes"
] | python | train |
snare/voltron | voltron/dbg.py | https://github.com/snare/voltron/blob/4ee3cbe6f7c1e38303f5dc6114c48b60217253c3/voltron/dbg.py#L165-L171 | def remove_listener(self, callback):
"""
Remove a listener.
"""
listeners = filter(lambda x: x['callback'] == callback, self.listeners)
for l in listeners:
self.listeners.remove(l) | [
"def",
"remove_listener",
"(",
"self",
",",
"callback",
")",
":",
"listeners",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"'callback'",
"]",
"==",
"callback",
",",
"self",
".",
"listeners",
")",
"for",
"l",
"in",
"listeners",
":",
"self",
".",
... | Remove a listener. | [
"Remove",
"a",
"listener",
"."
] | python | train |
census-instrumentation/opencensus-python | contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py#L134-L139 | def add_view_data(self, view_data):
""" Add view data object to be sent to server
"""
self.register_view(view_data.view)
v_name = get_view_name(self.options.namespace, view_data.view)
self.view_name_to_data_map[v_name] = view_data | [
"def",
"add_view_data",
"(",
"self",
",",
"view_data",
")",
":",
"self",
".",
"register_view",
"(",
"view_data",
".",
"view",
")",
"v_name",
"=",
"get_view_name",
"(",
"self",
".",
"options",
".",
"namespace",
",",
"view_data",
".",
"view",
")",
"self",
... | Add view data object to be sent to server | [
"Add",
"view",
"data",
"object",
"to",
"be",
"sent",
"to",
"server"
] | python | train |
codelv/enaml-native-cli | enamlnativecli/main.py | https://github.com/codelv/enaml-native-cli/blob/81d6faa7e3dd437956f661c512031e49c0d44b63/enamlnativecli/main.py#L1080-L1100 | def unlink(self, path, pkg):
""" Unlink the package in the current directory.
"""
#: Check if a custom unlinker exists to handle unlinking this package
for ep in pkg_resources.iter_entry_points(
group="enaml_native_unlinker"):
if ep.name.replace("-", '_') == p... | [
"def",
"unlink",
"(",
"self",
",",
"path",
",",
"pkg",
")",
":",
"#: Check if a custom unlinker exists to handle unlinking this package",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"group",
"=",
"\"enaml_native_unlinker\"",
")",
":",
"if",
"ep"... | Unlink the package in the current directory. | [
"Unlink",
"the",
"package",
"in",
"the",
"current",
"directory",
"."
] | python | train |
dchaplinsky/unshred | unshred/features/lines.py | https://github.com/dchaplinsky/unshred/blob/ca9cd6a1c6fb8c77d5424dd660ff5d2f3720c0f8/unshred/features/lines.py#L38-L54 | def _normalize_angle(angle, range, step):
"""Finds an angle that matches the given one modulo step.
Increments and decrements the given value with a given step.
Args:
range: a 2-tuple of min and max target values.
step: tuning step.
Returns:
Normalized value within a given ran... | [
"def",
"_normalize_angle",
"(",
"angle",
",",
"range",
",",
"step",
")",
":",
"while",
"angle",
"<=",
"range",
"[",
"0",
"]",
":",
"angle",
"+=",
"step",
"while",
"angle",
">=",
"range",
"[",
"1",
"]",
":",
"angle",
"-=",
"step",
"return",
"angle"
] | Finds an angle that matches the given one modulo step.
Increments and decrements the given value with a given step.
Args:
range: a 2-tuple of min and max target values.
step: tuning step.
Returns:
Normalized value within a given range. | [
"Finds",
"an",
"angle",
"that",
"matches",
"the",
"given",
"one",
"modulo",
"step",
"."
] | python | train |
apache/spark | python/pyspark/sql/functions.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L2393-L2419 | def schema_of_json(json, options={}):
"""
Parses a JSON string and infers its schema in DDL format.
:param json: a JSON string or a string literal containing a JSON string.
:param options: options to control parsing. accepts the same options as the JSON datasource
.. versionchanged:: 3.0
It... | [
"def",
"schema_of_json",
"(",
"json",
",",
"options",
"=",
"{",
"}",
")",
":",
"if",
"isinstance",
"(",
"json",
",",
"basestring",
")",
":",
"col",
"=",
"_create_column_from_literal",
"(",
"json",
")",
"elif",
"isinstance",
"(",
"json",
",",
"Column",
")... | Parses a JSON string and infers its schema in DDL format.
:param json: a JSON string or a string literal containing a JSON string.
:param options: options to control parsing. accepts the same options as the JSON datasource
.. versionchanged:: 3.0
It accepts `options` parameter to control schema inf... | [
"Parses",
"a",
"JSON",
"string",
"and",
"infers",
"its",
"schema",
"in",
"DDL",
"format",
"."
] | python | train |
ionelmc/python-cogen | cogen/core/proactors/kqueue_impl.py | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/kqueue_impl.py#L37-L76 | def run(self, timeout = 0):
"""
Run a proactor loop and return new socket events. Timeout is a timedelta
object, 0 if active coros or None.
kqueue timeout param is a integer number of nanoseconds (seconds/10**9).
"""
ptimeout = int(
timeout.days*86400... | [
"def",
"run",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"ptimeout",
"=",
"int",
"(",
"timeout",
".",
"days",
"*",
"86400000000000",
"+",
"timeout",
".",
"microseconds",
"*",
"1000",
"+",
"timeout",
".",
"seconds",
"*",
"1000000000",
"if",
"timeo... | Run a proactor loop and return new socket events. Timeout is a timedelta
object, 0 if active coros or None.
kqueue timeout param is a integer number of nanoseconds (seconds/10**9). | [
"Run",
"a",
"proactor",
"loop",
"and",
"return",
"new",
"socket",
"events",
".",
"Timeout",
"is",
"a",
"timedelta",
"object",
"0",
"if",
"active",
"coros",
"or",
"None",
".",
"kqueue",
"timeout",
"param",
"is",
"a",
"integer",
"number",
"of",
"nanoseconds"... | python | train |
pycontribs/pyrax | pyrax/object_storage.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L2494-L2503 | def list_containers_info(self, limit=None, marker=None):
"""Returns a list of info on Containers.
For each container, a dict containing the following keys is returned:
\code
name - the name of the container
count - the number of objects in the container
bytes... | [
"def",
"list_containers_info",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"marker",
"=",
"None",
")",
":",
"return",
"self",
".",
"_manager",
".",
"list_containers_info",
"(",
"limit",
"=",
"limit",
",",
"marker",
"=",
"marker",
")"
] | Returns a list of info on Containers.
For each container, a dict containing the following keys is returned:
\code
name - the name of the container
count - the number of objects in the container
bytes - the total bytes in the container | [
"Returns",
"a",
"list",
"of",
"info",
"on",
"Containers",
"."
] | python | train |
globocom/GloboNetworkAPI-client-python | networkapiclient/OptionVIP.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/OptionVIP.py#L387-L407 | def buscar_healthchecks(self, id_ambiente_vip):
"""Search healthcheck by environmentvip_id
:return: Dictionary with the following structure:
::
{'healthcheck_opt': [{'name': <name>, 'id': <id>},...]}
:raise InvalidParameterError: Environment VIP identifier is null and in... | [
"def",
"buscar_healthchecks",
"(",
"self",
",",
"id_ambiente_vip",
")",
":",
"url",
"=",
"'environment-vip/get/healthcheck/'",
"+",
"str",
"(",
"id_ambiente_vip",
")",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"url",
")"... | Search healthcheck by environmentvip_id
:return: Dictionary with the following structure:
::
{'healthcheck_opt': [{'name': <name>, 'id': <id>},...]}
:raise InvalidParameterError: Environment VIP identifier is null and invalid.
:raise EnvironmentVipNotFoundError: Environm... | [
"Search",
"healthcheck",
"by",
"environmentvip_id"
] | python | train |
Metatab/metapack | metapack/doc.py | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/doc.py#L101-L108 | def nonver_name(self):
"""Return the non versioned name"""
nv = self.as_version(None)
if not nv:
import re
nv = re.sub(r'-[^-]+$', '', self.name)
return nv | [
"def",
"nonver_name",
"(",
"self",
")",
":",
"nv",
"=",
"self",
".",
"as_version",
"(",
"None",
")",
"if",
"not",
"nv",
":",
"import",
"re",
"nv",
"=",
"re",
".",
"sub",
"(",
"r'-[^-]+$'",
",",
"''",
",",
"self",
".",
"name",
")",
"return",
"nv"
... | Return the non versioned name | [
"Return",
"the",
"non",
"versioned",
"name"
] | python | train |
moonso/loqusdb | loqusdb/utils/vcf.py | https://github.com/moonso/loqusdb/blob/792dcd0d461aff5adc703c49eebf58964913a513/loqusdb/utils/vcf.py#L12-L45 | def add_headers(vcf_obj, nr_cases=None, sv=False):
"""Add loqus specific information to a VCF header
Args:
vcf_obj(cyvcf2.VCF)
"""
vcf_obj.add_info_to_header(
{
'ID':"Obs",
'Number': '1',
'Type': 'Integer',
'Description': "The number of o... | [
"def",
"add_headers",
"(",
"vcf_obj",
",",
"nr_cases",
"=",
"None",
",",
"sv",
"=",
"False",
")",
":",
"vcf_obj",
".",
"add_info_to_header",
"(",
"{",
"'ID'",
":",
"\"Obs\"",
",",
"'Number'",
":",
"'1'",
",",
"'Type'",
":",
"'Integer'",
",",
"'Descriptio... | Add loqus specific information to a VCF header
Args:
vcf_obj(cyvcf2.VCF) | [
"Add",
"loqus",
"specific",
"information",
"to",
"a",
"VCF",
"header"
] | python | train |
apache/incubator-mxnet | python/mxnet/_ctypes/symbol.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/_ctypes/symbol.py#L48-L88 | def _compose(self, *args, **kwargs):
"""Compose symbol on inputs.
This call mutates the current symbol.
Parameters
----------
args:
provide positional arguments
kwargs:
provide keyword arguments
Returns
-------
the resul... | [
"def",
"_compose",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"None",
")",
"if",
"name",
":",
"name",
"=",
"c_str",
"(",
"name",
")",
"if",
"len",
"(",
"args",
")",
... | Compose symbol on inputs.
This call mutates the current symbol.
Parameters
----------
args:
provide positional arguments
kwargs:
provide keyword arguments
Returns
-------
the resulting symbol | [
"Compose",
"symbol",
"on",
"inputs",
"."
] | python | train |
jbasko/hookery | hookery/base.py | https://github.com/jbasko/hookery/blob/5638de2999ad533f83bc9a03110f85e5a0404257/hookery/base.py#L240-L263 | def unregister_handler(self, handler_or_func):
"""
Remove the handler from this hook's list of handlers.
This does not give up until the handler is found in the class hierarchy.
"""
index = -1
for i, handler in enumerate(self._direct_handlers):
if handler is h... | [
"def",
"unregister_handler",
"(",
"self",
",",
"handler_or_func",
")",
":",
"index",
"=",
"-",
"1",
"for",
"i",
",",
"handler",
"in",
"enumerate",
"(",
"self",
".",
"_direct_handlers",
")",
":",
"if",
"handler",
"is",
"handler_or_func",
"or",
"handler",
".... | Remove the handler from this hook's list of handlers.
This does not give up until the handler is found in the class hierarchy. | [
"Remove",
"the",
"handler",
"from",
"this",
"hook",
"s",
"list",
"of",
"handlers",
".",
"This",
"does",
"not",
"give",
"up",
"until",
"the",
"handler",
"is",
"found",
"in",
"the",
"class",
"hierarchy",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/jinja2/filters.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L812-L852 | def do_groupby(environment, value, attribute):
"""Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the ... | [
"def",
"do_groupby",
"(",
"environment",
",",
"value",
",",
"attribute",
")",
":",
"expr",
"=",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
")",
"return",
"[",
"_GroupTuple",
"(",
"key",
",",
"list",
"(",
"values",
")",
")",
"for",
"key",
",... | Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja... | [
"Group",
"a",
"sequence",
"of",
"objects",
"by",
"a",
"common",
"attribute",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.