id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
224,600 | lucasb-eyer/pydensecrf | pydensecrf/utils.py | create_pairwise_gaussian | def create_pairwise_gaussian(sdims, shape):
"""
Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimensio... | python | def create_pairwise_gaussian(sdims, shape):
"""
Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimensio... | [
"def",
"create_pairwise_gaussian",
"(",
"sdims",
",",
"shape",
")",
":",
"# create mesh",
"hcord_range",
"=",
"[",
"range",
"(",
"s",
")",
"for",
"s",
"in",
"shape",
"]",
"mesh",
"=",
"np",
".",
"array",
"(",
"np",
".",
"meshgrid",
"(",
"*",
"hcord_ran... | Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addP... | [
"Util",
"function",
"that",
"create",
"pairwise",
"gaussian",
"potentials",
".",
"This",
"works",
"for",
"all",
"image",
"dimensions",
".",
"For",
"the",
"2D",
"case",
"does",
"the",
"same",
"as",
"DenseCRF2D",
".",
"addPairwiseGaussian",
"."
] | 4d5343c398d75d7ebae34f51a47769084ba3a613 | https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L89-L111 |
224,601 | lucasb-eyer/pydensecrf | pydensecrf/utils.py | create_pairwise_bilateral | def create_pairwise_bilateral(sdims, schan, img, chdim=-1):
"""
Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling fa... | python | def create_pairwise_bilateral(sdims, schan, img, chdim=-1):
"""
Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling fa... | [
"def",
"create_pairwise_bilateral",
"(",
"sdims",
",",
"schan",
",",
"img",
",",
"chdim",
"=",
"-",
"1",
")",
":",
"# Put channel dim in right position",
"if",
"chdim",
"==",
"-",
"1",
":",
"# We don't have a channel, add a new axis",
"im_feat",
"=",
"img",
"[",
... | Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.ad... | [
"Util",
"function",
"that",
"create",
"pairwise",
"bilateral",
"potentials",
".",
"This",
"works",
"for",
"all",
"image",
"dimensions",
".",
"For",
"the",
"2D",
"case",
"does",
"the",
"same",
"as",
"DenseCRF2D",
".",
"addPairwiseBilateral",
"."
] | 4d5343c398d75d7ebae34f51a47769084ba3a613 | https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L114-L162 |
224,602 | deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.to_string | def to_string(self):
""" Converts the document to a string. """
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
... | python | def to_string(self):
""" Converts the document to a string. """
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
... | [
"def",
"to_string",
"(",
"self",
")",
":",
"buff",
"=",
"u\"\"",
"for",
"child",
"in",
"self",
".",
"content",
".",
"iter",
"(",
")",
":",
"if",
"child",
".",
"tag",
"in",
"[",
"self",
".",
"qn",
"(",
"'text:p'",
")",
",",
"self",
".",
"qn",
"(... | Converts the document to a string. | [
"Converts",
"the",
"document",
"to",
"a",
"string",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L19-L28 |
224,603 | deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.qn | def qn(self, namespace):
"""Connect tag prefix to longer namespace"""
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1]) | python | def qn(self, namespace):
"""Connect tag prefix to longer namespace"""
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1]) | [
"def",
"qn",
"(",
"self",
",",
"namespace",
")",
":",
"nsmap",
"=",
"{",
"'text'",
":",
"'urn:oasis:names:tc:opendocument:xmlns:text:1.0'",
",",
"}",
"spl",
"=",
"namespace",
".",
"split",
"(",
"':'",
")",
"return",
"'{{{}}}{}'",
".",
"format",
"(",
"nsmap",... | Connect tag prefix to longer namespace | [
"Connect",
"tag",
"prefix",
"to",
"longer",
"namespace"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L51-L57 |
224,604 | deanmalmgren/textract | textract/cli.py | get_parser | def get_parser():
"""Initialize the parser for the command line interface and bind the
autocompletion functionality"""
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
... | python | def get_parser():
"""Initialize the parser for the command line interface and bind the
autocompletion functionality"""
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
... | [
"def",
"get_parser",
"(",
")",
":",
"# initialize the parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"(",
"'Command line tool for extracting text from any document. '",
")",
"%",
"locals",
"(",
")",
",",
")",
"# define the command li... | Initialize the parser for the command line interface and bind the
autocompletion functionality | [
"Initialize",
"the",
"parser",
"for",
"the",
"command",
"line",
"interface",
"and",
"bind",
"the",
"autocompletion",
"functionality"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L45-L93 |
224,605 | deanmalmgren/textract | textract/cli.py | _get_available_encodings | def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__... | python | def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__... | [
"def",
"_get_available_encodings",
"(",
")",
":",
"available_encodings",
"=",
"set",
"(",
"encodings",
".",
"aliases",
".",
"aliases",
".",
"values",
"(",
")",
")",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"encodings",
".",
"__file__",
... | Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709 | [
"Get",
"a",
"list",
"of",
"the",
"available",
"encodings",
"to",
"make",
"it",
"easy",
"to",
"tab",
"-",
"complete",
"the",
"command",
"line",
"interface",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L96-L108 |
224,606 | deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdftotext | def extract_pdftotext(self, filename, **kwargs):
"""Extract text from pdfs using the pdftotext command line utility."""
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
... | python | def extract_pdftotext(self, filename, **kwargs):
"""Extract text from pdfs using the pdftotext command line utility."""
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
... | [
"def",
"extract_pdftotext",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'layout'",
"in",
"kwargs",
":",
"args",
"=",
"[",
"'pdftotext'",
",",
"'-layout'",
",",
"filename",
",",
"'-'",
"]",
"else",
":",
"args",
"=",
"[",
"'... | Extract text from pdfs using the pdftotext command line utility. | [
"Extract",
"text",
"from",
"pdfs",
"using",
"the",
"pdftotext",
"command",
"line",
"utility",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L37-L44 |
224,607 | deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdfminer | def extract_pdfminer(self, filename, **kwargs):
"""Extract text from pdfs using pdfminer."""
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout | python | def extract_pdfminer(self, filename, **kwargs):
"""Extract text from pdfs using pdfminer."""
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout | [
"def",
"extract_pdfminer",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"stdout",
",",
"_",
"=",
"self",
".",
"run",
"(",
"[",
"'pdf2txt.py'",
",",
"filename",
"]",
")",
"return",
"stdout"
] | Extract text from pdfs using pdfminer. | [
"Extract",
"text",
"from",
"pdfs",
"using",
"pdfminer",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L46-L49 |
224,608 | deanmalmgren/textract | textract/parsers/audio.py | Parser.convert_to_wav | def convert_to_wav(self, filename):
"""
Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results
"""
temp_filename = '{0}.wav'.format(self.temp_filename())
self.run(['... | python | def convert_to_wav(self, filename):
"""
Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results
"""
temp_filename = '{0}.wav'.format(self.temp_filename())
self.run(['... | [
"def",
"convert_to_wav",
"(",
"self",
",",
"filename",
")",
":",
"temp_filename",
"=",
"'{0}.wav'",
".",
"format",
"(",
"self",
".",
"temp_filename",
"(",
")",
")",
"self",
".",
"run",
"(",
"[",
"'sox'",
",",
"'-G'",
",",
"'-c'",
",",
"'1'",
",",
"fi... | Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results | [
"Uses",
"sox",
"cmdline",
"tool",
"to",
"convert",
"audio",
"file",
"to",
".",
"wav"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/audio.py#L56-L66 |
224,609 | deanmalmgren/textract | textract/parsers/html_parser.py | Parser._visible | def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | python | def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | [
"def",
"_visible",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
".",
"name",
"in",
"self",
".",
"_disallowed_names",
":",
"return",
"False",
"elif",
"re",
".",
"match",
"(",
"u'<!--.*-->'",
",",
"six",
".",
"text_type",
"(",
"element",
".",
... | Used to filter text elements that have invisible text on the page. | [
"Used",
"to",
"filter",
"text",
"elements",
"that",
"have",
"invisible",
"text",
"on",
"the",
"page",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L27-L34 |
224,610 | deanmalmgren/textract | textract/parsers/html_parser.py | Parser._find_any_text | def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
re... | python | def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
re... | [
"def",
"_find_any_text",
"(",
"self",
",",
"tag",
")",
":",
"text",
"=",
"''",
"if",
"tag",
"is",
"not",
"None",
":",
"text",
"=",
"six",
".",
"text_type",
"(",
"tag",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'(<[^>]+>)'",
",",
"''",
",",
"text... | Looks for any possible text within given tag. | [
"Looks",
"for",
"any",
"possible",
"text",
"within",
"given",
"tag",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L44-L53 |
224,611 | deanmalmgren/textract | textract/parsers/html_parser.py | Parser._join_inlines | def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup | python | def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup | [
"def",
"_join_inlines",
"(",
"self",
",",
"soup",
")",
":",
"elements",
"=",
"soup",
".",
"find_all",
"(",
"True",
")",
"for",
"elem",
"in",
"elements",
":",
"if",
"self",
".",
"_inline",
"(",
"elem",
")",
":",
"elem",
".",
"unwrap",
"(",
")",
"ret... | Unwraps inline elements defined in self._inline_tags. | [
"Unwraps",
"inline",
"elements",
"defined",
"in",
"self",
".",
"_inline_tags",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L118-L125 |
224,612 | deanmalmgren/textract | textract/parsers/utils.py | ShellParser.temp_filename | def temp_filename(self):
"""Return a unique tempfile name.
"""
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handl... | python | def temp_filename(self):
"""Return a unique tempfile name.
"""
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handl... | [
"def",
"temp_filename",
"(",
"self",
")",
":",
"# TODO: it would be nice to get this to behave more like a",
"# context so we can make sure these temporary files are",
"# removed, regardless of whether an error occurs or the",
"# program is terminated.",
"handle",
",",
"filename",
"=",
"... | Return a unique tempfile name. | [
"Return",
"a",
"unique",
"tempfile",
"name",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/utils.py#L106-L115 |
224,613 | deanmalmgren/textract | textract/parsers/__init__.py | process | def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
"""This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``.
"""
# make sure the filename exists
... | python | def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
"""This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``.
"""
# make sure the filename exists
... | [
"def",
"process",
"(",
"filename",
",",
"encoding",
"=",
"DEFAULT_ENCODING",
",",
"extension",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# make sure the filename exists",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"rai... | This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``. | [
"This",
"is",
"the",
"core",
"function",
"used",
"for",
"extracting",
"text",
".",
"It",
"routes",
"the",
"filename",
"to",
"the",
"appropriate",
"parser",
"and",
"returns",
"the",
"extracted",
"text",
"as",
"a",
"byte",
"-",
"string",
"encoded",
"with",
"... | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L31-L77 |
224,614 | deanmalmgren/textract | textract/parsers/__init__.py | _get_available_extensions | def _get_available_extensions():
"""Get a list of available file extensions to make it easy for
tab-completion and exception handling.
"""
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX ... | python | def _get_available_extensions():
"""Get a list of available file extensions to make it easy for
tab-completion and exception handling.
"""
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX ... | [
"def",
"_get_available_extensions",
"(",
")",
":",
"extensions",
"=",
"[",
"]",
"# from filenames",
"parsers_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"glob_filename",
"=",
"os",
".",
"p... | Get a list of available file extensions to make it easy for
tab-completion and exception handling. | [
"Get",
"a",
"list",
"of",
"available",
"file",
"extensions",
"to",
"make",
"it",
"easy",
"for",
"tab",
"-",
"completion",
"and",
"exception",
"handling",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L80-L102 |
224,615 | deanmalmgren/textract | setup.py | parse_requirements | def parse_requirements(requirements_filename):
"""read in the dependencies from the requirements files
"""
dependencies, dependency_links = [], []
requirements_dir = os.path.dirname(requirements_filename)
with open(requirements_filename, 'r') as stream:
for line in stream:
line =... | python | def parse_requirements(requirements_filename):
"""read in the dependencies from the requirements files
"""
dependencies, dependency_links = [], []
requirements_dir = os.path.dirname(requirements_filename)
with open(requirements_filename, 'r') as stream:
for line in stream:
line =... | [
"def",
"parse_requirements",
"(",
"requirements_filename",
")",
":",
"dependencies",
",",
"dependency_links",
"=",
"[",
"]",
",",
"[",
"]",
"requirements_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"requirements_filename",
")",
"with",
"open",
"(",
"req... | read in the dependencies from the requirements files | [
"read",
"in",
"the",
"dependencies",
"from",
"the",
"requirements",
"files"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/setup.py#L18-L37 |
224,616 | lyst/lightfm | lightfm/data.py | Dataset.build_interactions | def build_interactions(self, data):
"""
Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
... | python | def build_interactions(self, data):
"""
Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
... | [
"def",
"build_interactions",
"(",
"self",
",",
"data",
")",
":",
"interactions",
"=",
"_IncrementalCOOMatrix",
"(",
"self",
".",
"interactions_shape",
"(",
")",
",",
"np",
".",
"int32",
")",
"weights",
"=",
"_IncrementalCOOMatrix",
"(",
"self",
".",
"interacti... | Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
data: iterable of (user_id, item_id) or (user_id, it... | [
"Build",
"an",
"interaction",
"matrix",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/data.py#L292-L326 |
224,617 | lyst/lightfm | lightfm/data.py | Dataset.mapping | def mapping(self):
"""
Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries
"""
return (
self._user_id_mappin... | python | def mapping(self):
"""
Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries
"""
return (
self._user_id_mappin... | [
"def",
"mapping",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_user_id_mapping",
",",
"self",
".",
"_user_feature_mapping",
",",
"self",
".",
"_item_id_mapping",
",",
"self",
".",
"_item_feature_mapping",
",",
")"
] | Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries | [
"Return",
"the",
"constructed",
"mappings",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/data.py#L428-L445 |
224,618 | lyst/lightfm | examples/movielens/data.py | _get_movielens_path | def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip') | python | def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip') | [
"def",
"_get_movielens_path",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"'movielens.zip'",
")"
] | Get path to the movielens dataset file. | [
"Get",
"path",
"to",
"the",
"movielens",
"dataset",
"file",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L12-L18 |
224,619 | lyst/lightfm | examples/movielens/data.py | _download_movielens | def _download_movielens(dest_path):
"""
Download the dataset.
"""
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk) | python | def _download_movielens(dest_path):
"""
Download the dataset.
"""
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk) | [
"def",
"_download_movielens",
"(",
"dest_path",
")",
":",
"url",
"=",
"'http://files.grouplens.org/datasets/movielens/ml-100k.zip'",
"req",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"with",
"open",
"(",
"dest_path",
",",
"'wb'",
"... | Download the dataset. | [
"Download",
"the",
"dataset",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L21-L31 |
224,620 | lyst/lightfm | examples/movielens/data.py | _get_movie_raw_metadata | def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') | python | def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') | [
"def",
"_get_movie_raw_metadata",
"(",
")",
":",
"path",
"=",
"_get_movielens_path",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"_download_movielens",
"(",
"path",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
... | Get raw lines of the genre file. | [
"Get",
"raw",
"lines",
"of",
"the",
"genre",
"file",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L82-L93 |
224,621 | lyst/lightfm | lightfm/lightfm.py | LightFM._initialize | def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_compone... | python | def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_compone... | [
"def",
"_initialize",
"(",
"self",
",",
"no_components",
",",
"no_item_features",
",",
"no_user_features",
")",
":",
"# Initialise item features.",
"self",
".",
"item_embeddings",
"=",
"(",
"(",
"self",
".",
"random_state",
".",
"rand",
"(",
"no_item_features",
",... | Initialise internal latent representations. | [
"Initialise",
"internal",
"latent",
"representations",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L264-L295 |
224,622 | lyst/lightfm | lightfm/lightfm.py | LightFM._run_epoch | def _run_epoch(
self,
item_features,
user_features,
interactions,
sample_weight,
num_threads,
loss,
):
"""
Run an individual epoch.
"""
if loss in ("warp", "bpr", "warp-kos"):
# The CSR conversion needs to happen be... | python | def _run_epoch(
self,
item_features,
user_features,
interactions,
sample_weight,
num_threads,
loss,
):
"""
Run an individual epoch.
"""
if loss in ("warp", "bpr", "warp-kos"):
# The CSR conversion needs to happen be... | [
"def",
"_run_epoch",
"(",
"self",
",",
"item_features",
",",
"user_features",
",",
"interactions",
",",
"sample_weight",
",",
"num_threads",
",",
"loss",
",",
")",
":",
"if",
"loss",
"in",
"(",
"\"warp\"",
",",
"\"bpr\"",
",",
"\"warp-kos\"",
")",
":",
"# ... | Run an individual epoch. | [
"Run",
"an",
"individual",
"epoch",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L651-L742 |
224,623 | lyst/lightfm | lightfm/lightfm.py | LightFM.predict | def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
"""
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Argumen... | python | def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
"""
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Argumen... | [
"def",
"predict",
"(",
"self",
",",
"user_ids",
",",
"item_ids",
",",
"item_features",
"=",
"None",
",",
"user_features",
"=",
"None",
",",
"num_threads",
"=",
"1",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"not",
"isinstance",
"(",
"u... | Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array co... | [
"Compute",
"the",
"recommendation",
"score",
"for",
"user",
"-",
"item",
"pairs",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L744-L828 |
224,624 | lyst/lightfm | lightfm/lightfm.py | LightFM.get_item_representations | def get_item_representations(self, features=None):
"""
Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over fe... | python | def get_item_representations(self, features=None):
"""
Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over fe... | [
"def",
"get_item_representations",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"features",
"is",
"None",
":",
"return",
"self",
".",
"item_biases",
",",
"self",
".",
"item_embeddings",
"features",
"... | Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
... | [
"Get",
"the",
"latent",
"representations",
"for",
"items",
"given",
"model",
"and",
"features",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L947-L974 |
224,625 | lyst/lightfm | lightfm/lightfm.py | LightFM.get_user_representations | def get_user_representations(self, features=None):
"""
Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over fe... | python | def get_user_representations(self, features=None):
"""
Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over fe... | [
"def",
"get_user_representations",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"features",
"is",
"None",
":",
"return",
"self",
".",
"user_biases",
",",
"self",
".",
"user_embeddings",
"features",
"... | Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
An identity matrix will be used if not supplied.
... | [
"Get",
"the",
"latent",
"representations",
"for",
"users",
"given",
"model",
"and",
"features",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L976-L1003 |
224,626 | quantopian/empyrical | empyrical/stats.py | _adjust_returns | def _adjust_returns(returns, adjustment_factor):
"""
Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series o... | python | def _adjust_returns(returns, adjustment_factor):
"""
Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series o... | [
"def",
"_adjust_returns",
"(",
"returns",
",",
"adjustment_factor",
")",
":",
"if",
"isinstance",
"(",
"adjustment_factor",
",",
"(",
"float",
",",
"int",
")",
")",
"and",
"adjustment_factor",
"==",
"0",
":",
"return",
"returns",
"return",
"returns",
"-",
"a... | Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series or np.ndarray or float or int
Returns
-------
adj... | [
"Returns",
"the",
"returns",
"series",
"adjusted",
"by",
"adjustment_factor",
".",
"Optimizes",
"for",
"the",
"case",
"of",
"adjustment_factor",
"being",
"0",
"by",
"returning",
"returns",
"itself",
"not",
"a",
"copy!"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L127-L143 |
224,627 | quantopian/empyrical | empyrical/stats.py | annualization_factor | def annualization_factor(period, annualization):
"""
Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annua... | python | def annualization_factor(period, annualization):
"""
Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annua... | [
"def",
"annualization_factor",
"(",
"period",
",",
"annualization",
")",
":",
"if",
"annualization",
"is",
"None",
":",
"try",
":",
"factor",
"=",
"ANNUALIZATION_FACTORS",
"[",
"period",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Period canno... | Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
... | [
"Return",
"annualization",
"factor",
"from",
"period",
"entered",
"or",
"if",
"a",
"custom",
"value",
"is",
"passed",
"in",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L146-L183 |
224,628 | quantopian/empyrical | empyrical/stats.py | simple_returns | def simple_returns(prices):
"""
Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-li... | python | def simple_returns(prices):
"""
Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-li... | [
"def",
"simple_returns",
"(",
"prices",
")",
":",
"if",
"isinstance",
"(",
"prices",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"out",
"=",
"prices",
".",
"pct_change",
"(",
")",
".",
"iloc",
"[",
"1",
":",
"]",
"e... | Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-like
Returns of assets in wide-for... | [
"Compute",
"simple",
"returns",
"from",
"a",
"timeseries",
"of",
"prices",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L186-L209 |
224,629 | quantopian/empyrical | empyrical/stats.py | cum_returns | def cum_returns(returns, starting_value=0, out=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Ex... | python | def cum_returns(returns, starting_value=0, out=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Ex... | [
"def",
"cum_returns",
"(",
"returns",
",",
"starting_value",
"=",
"0",
",",
"out",
"=",
"None",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"returns",
".",
"copy",
"(",
")",
"nanmask",
"=",
"np",
".",
"isnan",
"(",
"returns... | Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17... | [
"Compute",
"cumulative",
"returns",
"from",
"simple",
"returns",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L212-L270 |
224,630 | quantopian/empyrical | empyrical/stats.py | cum_returns_final | def cum_returns_final(returns, starting_value=0):
"""
Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
... | python | def cum_returns_final(returns, starting_value=0):
"""
Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
... | [
"def",
"cum_returns_final",
"(",
"returns",
",",
"starting_value",
"=",
"0",
")",
":",
"if",
"len",
"(",
"returns",
")",
"==",
"0",
":",
"return",
"np",
".",
"nan",
"if",
"isinstance",
"(",
"returns",
",",
"pd",
".",
"DataFrame",
")",
":",
"result",
... | Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
Returns
-------
total_returns : pd.Series, np.ndarr... | [
"Compute",
"total",
"returns",
"from",
"simple",
"returns",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L273-L306 |
224,631 | quantopian/empyrical | empyrical/stats.py | aggregate_returns | def aggregate_returns(returns, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'wee... | python | def aggregate_returns(returns, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'wee... | [
"def",
"aggregate_returns",
"(",
"returns",
",",
"convert_to",
")",
":",
"def",
"cumulate_returns",
"(",
"x",
")",
":",
"return",
"cum_returns",
"(",
"x",
")",
".",
"iloc",
"[",
"-",
"1",
"]",
"if",
"convert_to",
"==",
"WEEKLY",
":",
"grouping",
"=",
"... | Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
... | [
"Aggregates",
"returns",
"by",
"week",
"month",
"or",
"year",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L309-L340 |
224,632 | quantopian/empyrical | empyrical/stats.py | max_drawdown | def max_drawdown(returns, out=None):
"""
Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optiona... | python | def max_drawdown(returns, out=None):
"""
Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optiona... | [
"def",
"max_drawdown",
"(",
"returns",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"returns",
".",
"shape",
"[",
"1",
":",
"]",
")",
"returns_1d",
... | Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optional
Array to use as output buffer.
... | [
"Determines",
"the",
"maximum",
"drawdown",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L343-L393 |
224,633 | quantopian/empyrical | empyrical/stats.py | annual_return | def annual_return(returns, period=DAILY, annualization=None):
"""
Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- ... | python | def annual_return(returns, period=DAILY, annualization=None):
"""
Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- ... | [
"def",
"annual_return",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"np",
".",
"nan",
"ann_factor",
"=",
"annualization_factor",
"(",
"period",
",",
... | Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period :... | [
"Determines",
"the",
"mean",
"annual",
"growth",
"rate",
"of",
"returns",
".",
"This",
"is",
"equivilent",
"to",
"the",
"compound",
"annual",
"growth",
"rate",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L399-L438 |
224,634 | quantopian/empyrical | empyrical/stats.py | annual_volatility | def annual_volatility(returns,
period=DAILY,
alpha=2.0,
annualization=None,
out=None):
"""
Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic... | python | def annual_volatility(returns,
period=DAILY,
alpha=2.0,
annualization=None,
out=None):
"""
Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic... | [
"def",
"annual_volatility",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"alpha",
"=",
"2.0",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"... | Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns... | [
"Determines",
"the",
"annual",
"volatility",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L478-L531 |
224,635 | quantopian/empyrical | empyrical/stats.py | calmar_ratio | def calmar_ratio(returns, period=DAILY, annualization=None):
"""
Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum... | python | def calmar_ratio(returns, period=DAILY, annualization=None):
"""
Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum... | [
"def",
"calmar_ratio",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
")",
":",
"max_dd",
"=",
"max_drawdown",
"(",
"returns",
"=",
"returns",
")",
"if",
"max_dd",
"<",
"0",
":",
"temp",
"=",
"annual_return",
"(",
"return... | Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of ... | [
"Determines",
"the",
"Calmar",
"ratio",
"or",
"drawdown",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L539-L587 |
224,636 | quantopian/empyrical | empyrical/stats.py | omega_ratio | def omega_ratio(returns, risk_free=0.0, required_return=0.0,
annualization=APPROX_BDAYS_PER_YEAR):
"""Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in... | python | def omega_ratio(returns, risk_free=0.0, required_return=0.0,
annualization=APPROX_BDAYS_PER_YEAR):
"""Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in... | [
"def",
"omega_ratio",
"(",
"returns",
",",
"risk_free",
"=",
"0.0",
",",
"required_return",
"=",
"0.0",
",",
"annualization",
"=",
"APPROX_BDAYS_PER_YEAR",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"2",
":",
"return",
"np",
".",
"nan",
"if",
"annu... | Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period
... | [
"Determines",
"the",
"Omega",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L590-L640 |
224,637 | quantopian/empyrical | empyrical/stats.py | sharpe_ratio | def sharpe_ratio(returns,
risk_free=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncu... | python | def sharpe_ratio(returns,
risk_free=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncu... | [
"def",
"sharpe_ratio",
"(",
"returns",
",",
"risk_free",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",... | Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period... | [
"Determines",
"the",
"Sharpe",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L643-L712 |
224,638 | quantopian/empyrical | empyrical/stats.py | sortino_ratio | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.n... | python | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.n... | [
"def",
"sortino_ratio",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
",",
"_downside_risk",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
... | Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable re... | [
"Determines",
"the",
"Sortino",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L718-L796 |
224,639 | quantopian/empyrical | empyrical/stats.py | downside_risk | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
... | python | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
... | [
"def",
"downside_risk",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",... | Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum accep... | [
"Determines",
"the",
"downside",
"deviation",
"below",
"a",
"threshold"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L802-L879 |
224,640 | quantopian/empyrical | empyrical/stats.py | excess_sharpe | def excess_sharpe(returns, factor_returns, out=None):
"""
Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_retu... | python | def excess_sharpe(returns, factor_returns, out=None):
"""
Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_retu... | [
"def",
"excess_sharpe",
"(",
"returns",
",",
"factor_returns",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"returns",
".",
"shape",
"[",
"1",
":",
... | Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns ag... | [
"Determines",
"the",
"Excess",
"Sharpe",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L885-L931 |
224,641 | quantopian/empyrical | empyrical/stats.py | _to_pandas | def _to_pandas(ob):
"""Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data.
"""
if isinstanc... | python | def _to_pandas(ob):
"""Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data.
"""
if isinstanc... | [
"def",
"_to_pandas",
"(",
"ob",
")",
":",
"if",
"isinstance",
"(",
"ob",
",",
"(",
"pd",
".",
"Series",
",",
"pd",
".",
"DataFrame",
")",
")",
":",
"return",
"ob",
"if",
"ob",
".",
"ndim",
"==",
"1",
":",
"return",
"pd",
".",
"Series",
"(",
"ob... | Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data. | [
"Convert",
"an",
"array",
"-",
"like",
"to",
"a",
"pandas",
"object",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L937-L960 |
224,642 | quantopian/empyrical | empyrical/stats.py | _aligned_series | def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : it... | python | def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : it... | [
"def",
"_aligned_series",
"(",
"*",
"many_series",
")",
":",
"head",
"=",
"many_series",
"[",
"0",
"]",
"tail",
"=",
"many_series",
"[",
"1",
":",
"]",
"n",
"=",
"len",
"(",
"head",
")",
"if",
"(",
"isinstance",
"(",
"head",
",",
"np",
".",
"ndarra... | Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series... | [
"Return",
"a",
"new",
"list",
"of",
"series",
"containing",
"the",
"data",
"in",
"the",
"input",
"series",
"but",
"with",
"their",
"indices",
"aligned",
".",
"NaNs",
"will",
"be",
"filled",
"in",
"for",
"missing",
"values",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L963-L992 |
224,643 | quantopian/empyrical | empyrical/stats.py | roll_alpha_beta | def roll_alpha_beta(returns, factor_returns, window=10, **kwargs):
"""
Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
... | python | def roll_alpha_beta(returns, factor_returns, window=10, **kwargs):
"""
Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
... | [
"def",
"roll_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"window",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"returns",
",",
"factor_returns",
"=",
"_aligned_series",
"(",
"returns",
",",
"factor_returns",
")",
"return",
"roll_alpha_beta_aligned... | Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
window : int
Size of the rolling window in terms of the periodicity o... | [
"Computes",
"alpha",
"and",
"beta",
"over",
"a",
"rolling",
"window",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1049-L1074 |
224,644 | quantopian/empyrical | empyrical/stats.py | stability_of_timeseries | def stability_of_timeseries(returns):
"""Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
... | python | def stability_of_timeseries(returns):
"""Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
... | [
"def",
"stability_of_timeseries",
"(",
"returns",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"2",
":",
"return",
"np",
".",
"nan",
"returns",
"=",
"np",
".",
"asanyarray",
"(",
"returns",
")",
"returns",
"=",
"returns",
"[",
"~",
"np",
".",
"is... | Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical... | [
"Determines",
"R",
"-",
"squared",
"of",
"a",
"linear",
"fit",
"to",
"the",
"cumulative",
"log",
"returns",
".",
"Computes",
"an",
"ordinary",
"least",
"squares",
"linear",
"fit",
"and",
"returns",
"R",
"-",
"squared",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1454-L1481 |
224,645 | quantopian/empyrical | empyrical/stats.py | capture | def capture(returns, factor_returns, period=DAILY):
"""
Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray... | python | def capture(returns, factor_returns, period=DAILY):
"""
Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray... | [
"def",
"capture",
"(",
"returns",
",",
"factor_returns",
",",
"period",
"=",
"DAILY",
")",
":",
"return",
"(",
"annual_return",
"(",
"returns",
",",
"period",
"=",
"period",
")",
"/",
"annual_return",
"(",
"factor_returns",
",",
"period",
"=",
"period",
")... | Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
... | [
"Compute",
"capture",
"ratio",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1514-L1546 |
224,646 | quantopian/empyrical | empyrical/stats.py | up_capture | def up_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_re... | python | def up_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_re... | [
"def",
"up_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"capture",
",",
"*",
"*",
"kwargs",
")"
] | Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
No... | [
"Compute",
"the",
"capture",
"ratio",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"positive"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1549-L1580 |
224,647 | quantopian/empyrical | empyrical/stats.py | down_capture | def down_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_... | python | def down_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_... | [
"def",
"down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"capture",
",",
"*",
"*",
"kwargs",
")"
] | Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
No... | [
"Compute",
"the",
"capture",
"ratio",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"negative"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1583-L1614 |
224,648 | quantopian/empyrical | empyrical/stats.py | up_down_capture | def up_down_capture(returns, factor_returns, **kwargs):
"""
Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_re... | python | def up_down_capture(returns, factor_returns, **kwargs):
"""
Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_re... | [
"def",
"up_down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"up_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
"/",
"down_capture",
"(",
"returns",
",",
"factor_returns",
... | Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the... | [
"Computes",
"the",
"ratio",
"of",
"up_capture",
"to",
"down_capture",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1617-L1645 |
224,649 | quantopian/empyrical | empyrical/stats.py | up_alpha_beta | def up_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta.
"""
return up(returns, fac... | python | def up_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta.
"""
return up(returns, fac... | [
"def",
"up_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"alpha_beta_aligned",
",",
"*",
"*",
"kwargs",
")"
] | Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta. | [
"Computes",
"alpha",
"and",
"beta",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"positive",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1648-L1663 |
224,650 | quantopian/empyrical | empyrical/stats.py | down_alpha_beta | def down_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float
"""
return down(returns, factor_return... | python | def down_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float
"""
return down(returns, factor_return... | [
"def",
"down_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"alpha_beta_aligned",
",",
"*",
"*",
"kwargs",
")"
] | Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float | [
"Computes",
"alpha",
"and",
"beta",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"negative",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1666-L1679 |
224,651 | quantopian/empyrical | empyrical/utils.py | roll | def roll(*args, **kwargs):
"""
Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optiona... | python | def roll(*args, **kwargs):
"""
Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optiona... | [
"def",
"roll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"window",
"=",
"kwargs",
".",
"pop",
"(",
"'window'",
")",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"raise",
"Va... | Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark re... | [
"Calculates",
"a",
"given",
"statistic",
"across",
"a",
"rolling",
"time",
"period",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L78-L118 |
224,652 | quantopian/empyrical | empyrical/utils.py | up | def up(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_retu... | python | def up(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_retu... | [
"def",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"returns",
"=",
"returns",
"[",
"factor_returns",
">",
"0",
"]",
"factor_returns",
"=",
"factor_returns",
"[... | Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
... | [
"Calculates",
"a",
"given",
"statistic",
"filtering",
"only",
"positive",
"factor",
"return",
"periods",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L121-L144 |
224,653 | quantopian/empyrical | empyrical/utils.py | down | def down(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_re... | python | def down(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_re... | [
"def",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"returns",
"=",
"returns",
"[",
"factor_returns",
"<",
"0",
"]",
"factor_returns",
"=",
"factor_returns",
... | Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
... | [
"Calculates",
"a",
"given",
"statistic",
"filtering",
"only",
"negative",
"factor",
"return",
"periods",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L147-L170 |
224,654 | quantopian/empyrical | empyrical/utils.py | get_treasury_yield | def get_treasury_yield(start=None, end=None, period='3MO'):
"""
Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
... | python | def get_treasury_yield(start=None, end=None, period='3MO'):
"""
Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
... | [
"def",
"get_treasury_yield",
"(",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"period",
"=",
"'3MO'",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"'1/1/1970'",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"_1_bday_ago",
"(",
")",... | Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
period : {'1MO', '3MO', '6MO', 1'... | [
"Load",
"treasury",
"yields",
"from",
"FRED",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L379-L409 |
224,655 | quantopian/empyrical | empyrical/utils.py | default_returns_func | def default_returns_func(symbol, start=None, end=None):
"""
Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earli... | python | def default_returns_func(symbol, start=None, end=None):
"""
Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earli... | [
"def",
"default_returns_func",
"(",
"symbol",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"'1/1/1970'",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"_1_bday_ago",
"(",
")",
"start",
"=... | Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to ... | [
"Gets",
"returns",
"for",
"a",
"symbol",
".",
"Queries",
"Yahoo",
"Finance",
".",
"Attempts",
"to",
"cache",
"SPY",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L452-L495 |
224,656 | quantopian/empyrical | empyrical/perf_attrib.py | perf_attrib | def perf_attrib(returns,
positions,
factor_returns,
factor_loadings):
"""
Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., c... | python | def perf_attrib(returns,
positions,
factor_returns,
factor_loadings):
"""
Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., c... | [
"def",
"perf_attrib",
"(",
"returns",
",",
"positions",
",",
"factor_returns",
",",
"factor_loadings",
")",
":",
"risk_exposures_portfolio",
"=",
"compute_exposures",
"(",
"positions",
",",
"factor_loadings",
")",
"perf_attrib_by_factor",
"=",
"risk_exposures_portfolio",
... | Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., contributed to total returns, as
well as the daily exposure to each of the risk factors. The returns that
can be attributed... | [
"Attributes",
"the",
"performance",
"of",
"a",
"returns",
"stream",
"to",
"a",
"set",
"of",
"risk",
"factors",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L4-L97 |
224,657 | quantopian/empyrical | empyrical/perf_attrib.py | compute_exposures | def compute_exposures(positions, factor_loadings):
"""
Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.41758... | python | def compute_exposures(positions, factor_loadings):
"""
Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.41758... | [
"def",
"compute_exposures",
"(",
"positions",
",",
"factor_loadings",
")",
":",
"risk_exposures",
"=",
"factor_loadings",
".",
"multiply",
"(",
"positions",
",",
"axis",
"=",
"'rows'",
")",
"return",
"risk_exposures",
".",
"groupby",
"(",
"level",
"=",
"'dt'",
... | Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
... | [
"Compute",
"daily",
"risk",
"factor",
"exposures",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L100-L141 |
224,658 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.has_pending | def has_pending(self):
"""Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.workqueue:
return True
f... | python | def has_pending(self):
"""Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.workqueue:
return True
f... | [
"def",
"has_pending",
"(",
"self",
")",
":",
"if",
"self",
".",
"workqueue",
":",
"return",
"True",
"for",
"assigned_unit",
"in",
"self",
".",
"assigned_work",
".",
"values",
"(",
")",
":",
"if",
"self",
".",
"_pending_of",
"(",
"assigned_unit",
")",
">"... | Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active". | [
"Return",
"True",
"if",
"there",
"are",
"pending",
"test",
"items",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L133-L147 |
224,659 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.add_node | def add_node(self, node):
"""Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node.
"""
assert node not in self.assigned_work
... | python | def add_node(self, node):
"""Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node.
"""
assert node not in self.assigned_work
... | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"assert",
"node",
"not",
"in",
"self",
".",
"assigned_work",
"self",
".",
"assigned_work",
"[",
"node",
"]",
"=",
"OrderedDict",
"(",
")"
] | Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node. | [
"Add",
"a",
"new",
"node",
"to",
"the",
"scheduler",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L149-L158 |
224,660 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.remove_node | def remove_node(self, node):
"""Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfini... | python | def remove_node(self, node):
"""Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfini... | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"workload",
"=",
"self",
".",
"assigned_work",
".",
"pop",
"(",
"node",
")",
"if",
"not",
"self",
".",
"_pending_of",
"(",
"workload",
")",
":",
"return",
"None",
"# The node crashed, identify test th... | Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfinished``.
- ``DSession.worker_erro... | [
"Remove",
"a",
"node",
"from",
"the",
"scheduler",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L160-L199 |
224,661 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.add_node_collection | def add_node_collection(self, node, collection):
"""Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``.
"""
# Check that add_node() was called on ... | python | def add_node_collection(self, node, collection):
"""Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``.
"""
# Check that add_node() was called on ... | [
"def",
"add_node_collection",
"(",
"self",
",",
"node",
",",
"collection",
")",
":",
"# Check that add_node() was called on the node before",
"assert",
"node",
"in",
"self",
".",
"assigned_work",
"# A new node has been added later, perhaps an original one died.",
"if",
"self",
... | Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``. | [
"Add",
"the",
"collected",
"test",
"items",
"from",
"a",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L201-L231 |
224,662 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._assign_work_unit | def _assign_work_unit(self, node):
"""Assign a work unit to a node."""
assert self.workqueue
# Grab a unit of work
scope, work_unit = self.workqueue.popitem(last=False)
# Keep track of the assigned work
assigned_to_node = self.assigned_work.setdefault(node, default=Orde... | python | def _assign_work_unit(self, node):
"""Assign a work unit to a node."""
assert self.workqueue
# Grab a unit of work
scope, work_unit = self.workqueue.popitem(last=False)
# Keep track of the assigned work
assigned_to_node = self.assigned_work.setdefault(node, default=Orde... | [
"def",
"_assign_work_unit",
"(",
"self",
",",
"node",
")",
":",
"assert",
"self",
".",
"workqueue",
"# Grab a unit of work",
"scope",
",",
"work_unit",
"=",
"self",
".",
"workqueue",
".",
"popitem",
"(",
"last",
"=",
"False",
")",
"# Keep track of the assigned w... | Assign a work unit to a node. | [
"Assign",
"a",
"work",
"unit",
"to",
"a",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L246-L265 |
224,663 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._pending_of | def _pending_of(self, workload):
"""Return the number of pending tests in a workload."""
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | python | def _pending_of(self, workload):
"""Return the number of pending tests in a workload."""
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | [
"def",
"_pending_of",
"(",
"self",
",",
"workload",
")",
":",
"pending",
"=",
"sum",
"(",
"list",
"(",
"scope",
".",
"values",
"(",
")",
")",
".",
"count",
"(",
"False",
")",
"for",
"scope",
"in",
"workload",
".",
"values",
"(",
")",
")",
"return",... | Return the number of pending tests in a workload. | [
"Return",
"the",
"number",
"of",
"pending",
"tests",
"in",
"a",
"workload",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L291-L294 |
224,664 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._reschedule | def _reschedule(self, node):
"""Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests.
"""
# Do not add more work to a node shutting down
if node.shutting_down:
... | python | def _reschedule(self, node):
"""Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests.
"""
# Do not add more work to a node shutting down
if node.shutting_down:
... | [
"def",
"_reschedule",
"(",
"self",
",",
"node",
")",
":",
"# Do not add more work to a node shutting down",
"if",
"node",
".",
"shutting_down",
":",
"return",
"# Check that more work is available",
"if",
"not",
"self",
".",
"workqueue",
":",
"node",
".",
"shutdown",
... | Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests. | [
"Maybe",
"schedule",
"new",
"items",
"on",
"the",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L296-L320 |
224,665 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.schedule | def schedule(self):
"""Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collect... | python | def schedule(self):
"""Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collect... | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"# Initial distribution already happened, reschedule on all nodes",
"if",
"self",
".",
"collection",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",... | Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collection_is_completed`` is True, thi... | [
"Initiate",
"distribution",
"of",
"the",
"test",
"collection",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L322-L380 |
224,666 | pytest-dev/pytest-xdist | xdist/scheduler/each.py | EachScheduling.schedule | def schedule(self):
"""Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those... | python | def schedule(self):
"""Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those... | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"for",
"node",
",",
"pending",
"in",
"self",
".",
"node2pending",
".",
"items",
"(",
")",
":",
"if",
"node",
"in",
"self",
".",
"_started",
":",
"continue",
"if",... | Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those tests. | [
"Schedule",
"the",
"test",
"items",
"on",
"the",
"nodes"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/each.py#L114-L132 |
224,667 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.has_pending | def has_pending(self):
"""Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.pending:
return True
for p... | python | def has_pending(self):
"""Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.pending:
return True
for p... | [
"def",
"has_pending",
"(",
"self",
")",
":",
"if",
"self",
".",
"pending",
":",
"return",
"True",
"for",
"pending",
"in",
"self",
".",
"node2pending",
".",
"values",
"(",
")",
":",
"if",
"pending",
":",
"return",
"True",
"return",
"False"
] | Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active". | [
"Return",
"True",
"if",
"there",
"are",
"pending",
"test",
"items"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L96-L108 |
224,668 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.check_schedule | def check_schedule(self, node, duration=0):
"""Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influen... | python | def check_schedule(self, node, duration=0):
"""Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influen... | [
"def",
"check_schedule",
"(",
"self",
",",
"node",
",",
"duration",
"=",
"0",
")",
":",
"if",
"node",
".",
"shutting_down",
":",
"return",
"if",
"self",
".",
"pending",
":",
"# how many nodes do we have?",
"num_nodes",
"=",
"len",
"(",
"self",
".",
"node2p... | Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influence how many tests the node is assigned. | [
"Maybe",
"schedule",
"new",
"items",
"on",
"the",
"node"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L154-L184 |
224,669 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.remove_node | def remove_node(self, node):
"""Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
... | python | def remove_node(self, node):
"""Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
... | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"pending",
"=",
"self",
".",
"node2pending",
".",
"pop",
"(",
"node",
")",
"if",
"not",
"pending",
":",
"return",
"# The node crashed, reassing pending items",
"crashitem",
"=",
"self",
".",
"collection... | Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
``DSession.worker_errordown`` hooks.
... | [
"Remove",
"a",
"node",
"from",
"the",
"scheduler"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L186-L208 |
224,670 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.schedule | def schedule(self):
"""Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
Thi... | python | def schedule(self):
"""Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
Thi... | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"# Initial distribution already happened, reschedule on all nodes",
"if",
"self",
".",
"collection",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",... | Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
This is called by the ``DSession.w... | [
"Initiate",
"distribution",
"of",
"the",
"test",
"collection"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L210-L254 |
224,671 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling._check_nodes_have_same_collection | def _check_nodes_have_same_collection(self):
"""Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook.
"""
node_collecti... | python | def _check_nodes_have_same_collection(self):
"""Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook.
"""
node_collecti... | [
"def",
"_check_nodes_have_same_collection",
"(",
"self",
")",
":",
"node_collection_items",
"=",
"list",
"(",
"self",
".",
"node2collection",
".",
"items",
"(",
")",
")",
"first_node",
",",
"col",
"=",
"node_collection_items",
"[",
"0",
"]",
"same_collection",
"... | Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook. | [
"Return",
"True",
"if",
"all",
"nodes",
"have",
"collected",
"the",
"same",
"items",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L263-L286 |
224,672 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.loop_once | def loop_once(self):
"""Process one callback from one of the workers."""
while 1:
if not self._active_nodes:
# If everything has died stop looping
self.triggershutdown()
raise RuntimeError("Unexpectedly no active workers available")
... | python | def loop_once(self):
"""Process one callback from one of the workers."""
while 1:
if not self._active_nodes:
# If everything has died stop looping
self.triggershutdown()
raise RuntimeError("Unexpectedly no active workers available")
... | [
"def",
"loop_once",
"(",
"self",
")",
":",
"while",
"1",
":",
"if",
"not",
"self",
".",
"_active_nodes",
":",
"# If everything has died stop looping",
"self",
".",
"triggershutdown",
"(",
")",
"raise",
"RuntimeError",
"(",
"\"Unexpectedly no active workers available\"... | Process one callback from one of the workers. | [
"Process",
"one",
"callback",
"from",
"one",
"of",
"the",
"workers",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L121-L140 |
224,673 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_workerready | def worker_workerready(self, node, workerinfo):
"""Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input.
"""
node.workerinfo = workerinfo
node.workerinfo["id"] = node.gateway.id
node.wo... | python | def worker_workerready(self, node, workerinfo):
"""Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input.
"""
node.workerinfo = workerinfo
node.workerinfo["id"] = node.gateway.id
node.wo... | [
"def",
"worker_workerready",
"(",
"self",
",",
"node",
",",
"workerinfo",
")",
":",
"node",
".",
"workerinfo",
"=",
"workerinfo",
"node",
".",
"workerinfo",
"[",
"\"id\"",
"]",
"=",
"node",
".",
"gateway",
".",
"id",
"node",
".",
"workerinfo",
"[",
"\"sp... | Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input. | [
"Emitted",
"when",
"a",
"node",
"first",
"starts",
"up",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L146-L163 |
224,674 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_workerfinished | def worker_workerfinished(self, node):
"""Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered.
"""
self.config.hook.pytest_t... | python | def worker_workerfinished(self, node):
"""Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered.
"""
self.config.hook.pytest_t... | [
"def",
"worker_workerfinished",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_testnodedown",
"(",
"node",
"=",
"node",
",",
"error",
"=",
"None",
")",
"if",
"node",
".",
"workeroutput",
"[",
"\"exitstatus\"",
"]",
"... | Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered. | [
"Emitted",
"when",
"node",
"executes",
"its",
"pytest_sessionfinish",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L165-L181 |
224,675 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_errordown | def worker_errordown(self, node, error):
"""Emitted by the WorkerController when a node dies."""
self.config.hook.pytest_testnodedown(node=node, error=error)
try:
crashitem = self.sched.remove_node(node)
except KeyError:
pass
else:
if crashitem... | python | def worker_errordown(self, node, error):
"""Emitted by the WorkerController when a node dies."""
self.config.hook.pytest_testnodedown(node=node, error=error)
try:
crashitem = self.sched.remove_node(node)
except KeyError:
pass
else:
if crashitem... | [
"def",
"worker_errordown",
"(",
"self",
",",
"node",
",",
"error",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_testnodedown",
"(",
"node",
"=",
"node",
",",
"error",
"=",
"error",
")",
"try",
":",
"crashitem",
"=",
"self",
".",
"sched",
... | Emitted by the WorkerController when a node dies. | [
"Emitted",
"by",
"the",
"WorkerController",
"when",
"a",
"node",
"dies",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L183-L208 |
224,676 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_collectionfinish | def worker_collectionfinish(self, node, ids):
"""worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler t... | python | def worker_collectionfinish(self, node, ids):
"""worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler t... | [
"def",
"worker_collectionfinish",
"(",
"self",
",",
"node",
",",
"ids",
")",
":",
"if",
"self",
".",
"shuttingdown",
":",
"return",
"self",
".",
"config",
".",
"hook",
".",
"pytest_xdist_node_collection_finished",
"(",
"node",
"=",
"node",
",",
"ids",
"=",
... | worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler to schedule the collected items. When initiating
... | [
"worker",
"has",
"finished",
"test",
"collection",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L210-L236 |
224,677 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_logstart | def worker_logstart(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logstart hook."""
self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location) | python | def worker_logstart(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logstart hook."""
self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location) | [
"def",
"worker_logstart",
"(",
"self",
",",
"node",
",",
"nodeid",
",",
"location",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_runtest_logstart",
"(",
"nodeid",
"=",
"nodeid",
",",
"location",
"=",
"location",
")"
] | Emitted when a node calls the pytest_runtest_logstart hook. | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_runtest_logstart",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L238-L240 |
224,678 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_logfinish | def worker_logfinish(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logfinish hook."""
self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location) | python | def worker_logfinish(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logfinish hook."""
self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location) | [
"def",
"worker_logfinish",
"(",
"self",
",",
"node",
",",
"nodeid",
",",
"location",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_runtest_logfinish",
"(",
"nodeid",
"=",
"nodeid",
",",
"location",
"=",
"location",
")"
] | Emitted when a node calls the pytest_runtest_logfinish hook. | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_runtest_logfinish",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L242-L244 |
224,679 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_collectreport | def worker_collectreport(self, node, rep):
"""Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330).
"""
assert not rep.passed
... | python | def worker_collectreport(self, node, rep):
"""Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330).
"""
assert not rep.passed
... | [
"def",
"worker_collectreport",
"(",
"self",
",",
"node",
",",
"rep",
")",
":",
"assert",
"not",
"rep",
".",
"passed",
"self",
".",
"_failed_worker_collectreport",
"(",
"node",
",",
"rep",
")"
] | Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330). | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_collectreport",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L260-L267 |
224,680 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession._clone_node | def _clone_node(self, node):
"""Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and ... | python | def _clone_node(self, node):
"""Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and ... | [
"def",
"_clone_node",
"(",
"self",
",",
"node",
")",
":",
"spec",
"=",
"node",
".",
"gateway",
".",
"spec",
"spec",
".",
"id",
"=",
"None",
"self",
".",
"nodemanager",
".",
"group",
".",
"allocate_id",
"(",
"spec",
")",
"node",
"=",
"self",
".",
"n... | Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and do work soon. | [
"Return",
"new",
"node",
"based",
"on",
"an",
"existing",
"one",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L279-L292 |
224,681 | pytest-dev/pytest-xdist | xdist/workermanage.py | NodeManager.rsync_roots | def rsync_roots(self, gateway):
"""Rsync the set of roots to the node's gateway cwd."""
if self.roots:
for root in self.roots:
self.rsync(gateway, root, **self.rsyncoptions) | python | def rsync_roots(self, gateway):
"""Rsync the set of roots to the node's gateway cwd."""
if self.roots:
for root in self.roots:
self.rsync(gateway, root, **self.rsyncoptions) | [
"def",
"rsync_roots",
"(",
"self",
",",
"gateway",
")",
":",
"if",
"self",
".",
"roots",
":",
"for",
"root",
"in",
"self",
".",
"roots",
":",
"self",
".",
"rsync",
"(",
"gateway",
",",
"root",
",",
"*",
"*",
"self",
".",
"rsyncoptions",
")"
] | Rsync the set of roots to the node's gateway cwd. | [
"Rsync",
"the",
"set",
"of",
"roots",
"to",
"the",
"node",
"s",
"gateway",
"cwd",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L53-L57 |
224,682 | pytest-dev/pytest-xdist | xdist/workermanage.py | NodeManager._getrsyncoptions | def _getrsyncoptions(self):
"""Get options to be passed for rsync."""
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.config.getini("rsyncignore")
return {"ignores": ignores, "verbose": self.config.option.verbose} | python | def _getrsyncoptions(self):
"""Get options to be passed for rsync."""
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.config.getini("rsyncignore")
return {"ignores": ignores, "verbose": self.config.option.verbose} | [
"def",
"_getrsyncoptions",
"(",
"self",
")",
":",
"ignores",
"=",
"list",
"(",
"self",
".",
"DEFAULT_IGNORES",
")",
"ignores",
"+=",
"self",
".",
"config",
".",
"option",
".",
"rsyncignore",
"ignores",
"+=",
"self",
".",
"config",
".",
"getini",
"(",
"\"... | Get options to be passed for rsync. | [
"Get",
"options",
"to",
"be",
"passed",
"for",
"rsync",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L109-L115 |
224,683 | pytest-dev/pytest-xdist | xdist/workermanage.py | WorkerController.sendcommand | def sendcommand(self, name, **kwargs):
""" send a named parametrized command to the other side. """
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | python | def sendcommand(self, name, **kwargs):
""" send a named parametrized command to the other side. """
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | [
"def",
"sendcommand",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"\"sending command %s(**%s)\"",
"%",
"(",
"name",
",",
"kwargs",
")",
")",
"self",
".",
"channel",
".",
"send",
"(",
"(",
"name",
",",
"kwargs... | send a named parametrized command to the other side. | [
"send",
"a",
"named",
"parametrized",
"command",
"to",
"the",
"other",
"side",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L284-L287 |
224,684 | pytest-dev/pytest-xdist | xdist/workermanage.py | WorkerController.process_from_remote | def process_from_remote(self, eventcall): # noqa too complex
""" this gets called for each object we receive from
the other side and if the channel closes.
Note that channel callbacks run in the receiver
thread of execnet gateways - we need to
avoid raising exce... | python | def process_from_remote(self, eventcall): # noqa too complex
""" this gets called for each object we receive from
the other side and if the channel closes.
Note that channel callbacks run in the receiver
thread of execnet gateways - we need to
avoid raising exce... | [
"def",
"process_from_remote",
"(",
"self",
",",
"eventcall",
")",
":",
"# noqa too complex",
"try",
":",
"if",
"eventcall",
"==",
"self",
".",
"ENDMARK",
":",
"err",
"=",
"self",
".",
"channel",
".",
"_getremoteerror",
"(",
")",
"if",
"not",
"self",
".",
... | this gets called for each object we receive from
the other side and if the channel closes.
Note that channel callbacks run in the receiver
thread of execnet gateways - we need to
avoid raising exceptions or doing heavy work. | [
"this",
"gets",
"called",
"for",
"each",
"object",
"we",
"receive",
"from",
"the",
"other",
"side",
"and",
"if",
"the",
"channel",
"closes",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L293-L367 |
224,685 | pytest-dev/pytest-xdist | xdist/report.py | report_collection_diff | def report_collection_diff(from_collection, to_collection, from_id, to_id):
"""Report the collected test difference between two nodes.
:returns: detailed message describing the difference between the given
collections, or None if they are equal.
"""
if from_collection == to_collection:
retu... | python | def report_collection_diff(from_collection, to_collection, from_id, to_id):
"""Report the collected test difference between two nodes.
:returns: detailed message describing the difference between the given
collections, or None if they are equal.
"""
if from_collection == to_collection:
retu... | [
"def",
"report_collection_diff",
"(",
"from_collection",
",",
"to_collection",
",",
"from_id",
",",
"to_id",
")",
":",
"if",
"from_collection",
"==",
"to_collection",
":",
"return",
"None",
"diff",
"=",
"unified_diff",
"(",
"from_collection",
",",
"to_collection",
... | Report the collected test difference between two nodes.
:returns: detailed message describing the difference between the given
collections, or None if they are equal. | [
"Report",
"the",
"collected",
"test",
"difference",
"between",
"two",
"nodes",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/report.py#L5-L21 |
224,686 | ivelum/djangoql | djangoql/queryset.py | apply_search | def apply_search(queryset, search, schema=None):
"""
Applies search written in DjangoQL mini-language to given queryset
"""
ast = DjangoQLParser().parse(search)
schema = schema or DjangoQLSchema
schema_instance = schema(queryset.model)
schema_instance.validate(ast)
return queryset.filter... | python | def apply_search(queryset, search, schema=None):
"""
Applies search written in DjangoQL mini-language to given queryset
"""
ast = DjangoQLParser().parse(search)
schema = schema or DjangoQLSchema
schema_instance = schema(queryset.model)
schema_instance.validate(ast)
return queryset.filter... | [
"def",
"apply_search",
"(",
"queryset",
",",
"search",
",",
"schema",
"=",
"None",
")",
":",
"ast",
"=",
"DjangoQLParser",
"(",
")",
".",
"parse",
"(",
"search",
")",
"schema",
"=",
"schema",
"or",
"DjangoQLSchema",
"schema_instance",
"=",
"schema",
"(",
... | Applies search written in DjangoQL mini-language to given queryset | [
"Applies",
"search",
"written",
"in",
"DjangoQL",
"mini",
"-",
"language",
"to",
"given",
"queryset"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/queryset.py#L32-L40 |
224,687 | ivelum/djangoql | djangoql/schema.py | DjangoQLField.get_options | def get_options(self):
"""
Override this method to provide custom suggestion options
"""
choices = self._field_choices()
if choices:
return [c[1] for c in choices]
else:
return self.model.objects.\
order_by(self.name).\
... | python | def get_options(self):
"""
Override this method to provide custom suggestion options
"""
choices = self._field_choices()
if choices:
return [c[1] for c in choices]
else:
return self.model.objects.\
order_by(self.name).\
... | [
"def",
"get_options",
"(",
"self",
")",
":",
"choices",
"=",
"self",
".",
"_field_choices",
"(",
")",
"if",
"choices",
":",
"return",
"[",
"c",
"[",
"1",
"]",
"for",
"c",
"in",
"choices",
"]",
"else",
":",
"return",
"self",
".",
"model",
".",
"obje... | Override this method to provide custom suggestion options | [
"Override",
"this",
"method",
"to",
"provide",
"custom",
"suggestion",
"options"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L55-L65 |
224,688 | ivelum/djangoql | djangoql/schema.py | DjangoQLField.get_lookup_value | def get_lookup_value(self, value):
"""
Override this method to convert displayed values to lookup values
"""
choices = self._field_choices()
if choices:
if isinstance(value, list):
return [c[0] for c in choices if c[1] in value]
else:
... | python | def get_lookup_value(self, value):
"""
Override this method to convert displayed values to lookup values
"""
choices = self._field_choices()
if choices:
if isinstance(value, list):
return [c[0] for c in choices if c[1] in value]
else:
... | [
"def",
"get_lookup_value",
"(",
"self",
",",
"value",
")",
":",
"choices",
"=",
"self",
".",
"_field_choices",
"(",
")",
"if",
"choices",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"c",
"[",
"0",
"]",
"for",
"c",
"... | Override this method to convert displayed values to lookup values | [
"Override",
"this",
"method",
"to",
"convert",
"displayed",
"values",
"to",
"lookup",
"values"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L73-L85 |
224,689 | ivelum/djangoql | djangoql/schema.py | DjangoQLField.get_operator | def get_operator(self, operator):
"""
Get a comparison suffix to be used in Django ORM & inversion flag for it
:param operator: string, DjangoQL comparison operator
:return: (suffix, invert) - a tuple with 2 values:
suffix - suffix to be used in ORM query, for example '__gt'... | python | def get_operator(self, operator):
"""
Get a comparison suffix to be used in Django ORM & inversion flag for it
:param operator: string, DjangoQL comparison operator
:return: (suffix, invert) - a tuple with 2 values:
suffix - suffix to be used in ORM query, for example '__gt'... | [
"def",
"get_operator",
"(",
"self",
",",
"operator",
")",
":",
"op",
"=",
"{",
"'='",
":",
"''",
",",
"'>'",
":",
"'__gt'",
",",
"'>='",
":",
"'__gte'",
",",
"'<'",
":",
"'__lt'",
",",
"'<='",
":",
"'__lte'",
",",
"'~'",
":",
"'__icontains'",
",",
... | Get a comparison suffix to be used in Django ORM & inversion flag for it
:param operator: string, DjangoQL comparison operator
:return: (suffix, invert) - a tuple with 2 values:
suffix - suffix to be used in ORM query, for example '__gt' for '>'
invert - boolean, True if this co... | [
"Get",
"a",
"comparison",
"suffix",
"to",
"be",
"used",
"in",
"Django",
"ORM",
"&",
"inversion",
"flag",
"for",
"it"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L87-L112 |
224,690 | ivelum/djangoql | djangoql/schema.py | DjangoQLSchema.introspect | def introspect(self, model, exclude=()):
"""
Start with given model and recursively walk through its relationships.
Returns a dict with all model labels and their fields found.
"""
result = {}
open_set = deque([model])
closed_set = list(exclude)
while op... | python | def introspect(self, model, exclude=()):
"""
Start with given model and recursively walk through its relationships.
Returns a dict with all model labels and their fields found.
"""
result = {}
open_set = deque([model])
closed_set = list(exclude)
while op... | [
"def",
"introspect",
"(",
"self",
",",
"model",
",",
"exclude",
"=",
"(",
")",
")",
":",
"result",
"=",
"{",
"}",
"open_set",
"=",
"deque",
"(",
"[",
"model",
"]",
")",
"closed_set",
"=",
"list",
"(",
"exclude",
")",
"while",
"open_set",
":",
"mode... | Start with given model and recursively walk through its relationships.
Returns a dict with all model labels and their fields found. | [
"Start",
"with",
"given",
"model",
"and",
"recursively",
"walk",
"through",
"its",
"relationships",
"."
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L332-L365 |
224,691 | ivelum/djangoql | djangoql/schema.py | DjangoQLSchema.get_fields | def get_fields(self, model):
"""
By default, returns all field names of a given model.
Override this method to limit field options. You can either return a
plain list of field names from it, like ['id', 'name'], or call
.super() and exclude unwanted fields from its result.
... | python | def get_fields(self, model):
"""
By default, returns all field names of a given model.
Override this method to limit field options. You can either return a
plain list of field names from it, like ['id', 'name'], or call
.super() and exclude unwanted fields from its result.
... | [
"def",
"get_fields",
"(",
"self",
",",
"model",
")",
":",
"return",
"sorted",
"(",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"model",
".",
"_meta",
".",
"get_fields",
"(",
")",
"if",
"f",
".",
"name",
"!=",
"'password'",
"]",
")"
] | By default, returns all field names of a given model.
Override this method to limit field options. You can either return a
plain list of field names from it, like ['id', 'name'], or call
.super() and exclude unwanted fields from its result. | [
"By",
"default",
"returns",
"all",
"field",
"names",
"of",
"a",
"given",
"model",
"."
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L367-L377 |
224,692 | ivelum/djangoql | djangoql/schema.py | DjangoQLSchema.validate | def validate(self, node):
"""
Validate DjangoQL AST tree vs. current schema
"""
assert isinstance(node, Node)
if isinstance(node.operator, Logical):
self.validate(node.left)
self.validate(node.right)
return
assert isinstance(node.left, ... | python | def validate(self, node):
"""
Validate DjangoQL AST tree vs. current schema
"""
assert isinstance(node, Node)
if isinstance(node.operator, Logical):
self.validate(node.left)
self.validate(node.right)
return
assert isinstance(node.left, ... | [
"def",
"validate",
"(",
"self",
",",
"node",
")",
":",
"assert",
"isinstance",
"(",
"node",
",",
"Node",
")",
"if",
"isinstance",
"(",
"node",
".",
"operator",
",",
"Logical",
")",
":",
"self",
".",
"validate",
"(",
"node",
".",
"left",
")",
"self",
... | Validate DjangoQL AST tree vs. current schema | [
"Validate",
"DjangoQL",
"AST",
"tree",
"vs",
".",
"current",
"schema"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L454-L479 |
224,693 | ivelum/djangoql | djangoql/lexer.py | DjangoQLLexer.find_column | def find_column(self, t):
"""
Returns token position in current text, starting from 1
"""
cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators)
if cr == -1:
return t.lexpos + 1
return t.lexpos - cr | python | def find_column(self, t):
"""
Returns token position in current text, starting from 1
"""
cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators)
if cr == -1:
return t.lexpos + 1
return t.lexpos - cr | [
"def",
"find_column",
"(",
"self",
",",
"t",
")",
":",
"cr",
"=",
"max",
"(",
"self",
".",
"text",
".",
"rfind",
"(",
"l",
",",
"0",
",",
"t",
".",
"lexpos",
")",
"for",
"l",
"in",
"self",
".",
"line_terminators",
")",
"if",
"cr",
"==",
"-",
... | Returns token position in current text, starting from 1 | [
"Returns",
"token",
"position",
"in",
"current",
"text",
"starting",
"from",
"1"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/lexer.py#L40-L47 |
224,694 | aiogram/aiogram | aiogram/dispatcher/filters/filters.py | execute_filter | async def execute_filter(filter_: FilterObj, args):
"""
Helper for executing filter
:param filter_:
:param args:
:return:
"""
if filter_.is_async:
return await filter_.filter(*args, **filter_.kwargs)
else:
return filter_.filter(*args, **filter_.kwargs) | python | async def execute_filter(filter_: FilterObj, args):
"""
Helper for executing filter
:param filter_:
:param args:
:return:
"""
if filter_.is_async:
return await filter_.filter(*args, **filter_.kwargs)
else:
return filter_.filter(*args, **filter_.kwargs) | [
"async",
"def",
"execute_filter",
"(",
"filter_",
":",
"FilterObj",
",",
"args",
")",
":",
"if",
"filter_",
".",
"is_async",
":",
"return",
"await",
"filter_",
".",
"filter",
"(",
"*",
"args",
",",
"*",
"*",
"filter_",
".",
"kwargs",
")",
"else",
":",
... | Helper for executing filter
:param filter_:
:param args:
:return: | [
"Helper",
"for",
"executing",
"filter"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L47-L58 |
224,695 | aiogram/aiogram | aiogram/dispatcher/filters/filters.py | check_filters | async def check_filters(filters: typing.Iterable[FilterObj], args):
"""
Check list of filters
:param filters:
:param args:
:return:
"""
data = {}
if filters is not None:
for filter_ in filters:
f = await execute_filter(filter_, args)
if not f:
... | python | async def check_filters(filters: typing.Iterable[FilterObj], args):
"""
Check list of filters
:param filters:
:param args:
:return:
"""
data = {}
if filters is not None:
for filter_ in filters:
f = await execute_filter(filter_, args)
if not f:
... | [
"async",
"def",
"check_filters",
"(",
"filters",
":",
"typing",
".",
"Iterable",
"[",
"FilterObj",
"]",
",",
"args",
")",
":",
"data",
"=",
"{",
"}",
"if",
"filters",
"is",
"not",
"None",
":",
"for",
"filter_",
"in",
"filters",
":",
"f",
"=",
"await"... | Check list of filters
:param filters:
:param args:
:return: | [
"Check",
"list",
"of",
"filters"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L61-L77 |
224,696 | aiogram/aiogram | aiogram/dispatcher/filters/filters.py | AbstractFilter.validate | def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]:
"""
Validate and parse config.
This method will be called by the filters factory when you bind this filter.
Must be overridden.
:param full_config: dict with arguments... | python | def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]:
"""
Validate and parse config.
This method will be called by the filters factory when you bind this filter.
Must be overridden.
:param full_config: dict with arguments... | [
"def",
"validate",
"(",
"cls",
",",
"full_config",
":",
"typing",
".",
"Dict",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
")",
"->",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Dict",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
"]",
":",
"pa... | Validate and parse config.
This method will be called by the filters factory when you bind this filter.
Must be overridden.
:param full_config: dict with arguments passed to handler registrar
:return: Current filter config | [
"Validate",
"and",
"parse",
"config",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L136-L146 |
224,697 | aiogram/aiogram | aiogram/dispatcher/filters/filters.py | AndFilter.check | async def check(self, *args):
"""
All filters must return a positive result
:param args:
:return:
"""
data = {}
for target in self.targets:
result = await target(*args)
if not result:
return False
if isinstance(... | python | async def check(self, *args):
"""
All filters must return a positive result
:param args:
:return:
"""
data = {}
for target in self.targets:
result = await target(*args)
if not result:
return False
if isinstance(... | [
"async",
"def",
"check",
"(",
"self",
",",
"*",
"args",
")",
":",
"data",
"=",
"{",
"}",
"for",
"target",
"in",
"self",
".",
"targets",
":",
"result",
"=",
"await",
"target",
"(",
"*",
"args",
")",
"if",
"not",
"result",
":",
"return",
"False",
"... | All filters must return a positive result
:param args:
:return: | [
"All",
"filters",
"must",
"return",
"a",
"positive",
"result"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L247-L263 |
224,698 | aiogram/aiogram | examples/broadcast_example.py | send_message | async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return:
"""
try:
await bot.send_message(user_id, text, disable_notification=disable_notification)
... | python | async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return:
"""
try:
await bot.send_message(user_id, text, disable_notification=disable_notification)
... | [
"async",
"def",
"send_message",
"(",
"user_id",
":",
"int",
",",
"text",
":",
"str",
",",
"disable_notification",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"try",
":",
"await",
"bot",
".",
"send_message",
"(",
"user_id",
",",
"text",
",",
"dis... | Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return: | [
"Safe",
"messages",
"sender"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/broadcast_example.py#L26-L52 |
224,699 | aiogram/aiogram | aiogram/types/message.py | Message.get_full_command | def get_full_command(self):
"""
Split command and args
:return: tuple of (command, args)
"""
if self.is_command():
command, _, args = self.text.partition(' ')
return command, args | python | def get_full_command(self):
"""
Split command and args
:return: tuple of (command, args)
"""
if self.is_command():
command, _, args = self.text.partition(' ')
return command, args | [
"def",
"get_full_command",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_command",
"(",
")",
":",
"command",
",",
"_",
",",
"args",
"=",
"self",
".",
"text",
".",
"partition",
"(",
"' '",
")",
"return",
"command",
",",
"args"
] | Split command and args
:return: tuple of (command, args) | [
"Split",
"command",
"and",
"args"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L156-L164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.