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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
buildinspace/peru | peru/async_exit_stack.py | AsyncExitStack.push_async_callback | def push_async_callback(self, callback, *args, **kwds):
"""Registers an arbitrary coroutine function and arguments.
Cannot suppress exceptions.
"""
_exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds)
# We changed the signature, so using @wraps is not appropria... | python | def push_async_callback(self, callback, *args, **kwds):
"""Registers an arbitrary coroutine function and arguments.
Cannot suppress exceptions.
"""
_exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds)
# We changed the signature, so using @wraps is not appropria... | [
"def",
"push_async_callback",
"(",
"self",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"_exit_wrapper",
"=",
"self",
".",
"_create_async_cb_wrapper",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"# We changed the s... | Registers an arbitrary coroutine function and arguments.
Cannot suppress exceptions. | [
"Registers",
"an",
"arbitrary",
"coroutine",
"function",
"and",
"arguments",
".",
"Cannot",
"suppress",
"exceptions",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/async_exit_stack.py#L144-L154 | train |
buildinspace/peru | peru/runtime.py | Runtime | async def Runtime(args, env):
'This is the async constructor for the _Runtime class.'
r = _Runtime(args, env)
await r._init_cache()
return r | python | async def Runtime(args, env):
'This is the async constructor for the _Runtime class.'
r = _Runtime(args, env)
await r._init_cache()
return r | [
"async",
"def",
"Runtime",
"(",
"args",
",",
"env",
")",
":",
"r",
"=",
"_Runtime",
"(",
"args",
",",
"env",
")",
"await",
"r",
".",
"_init_cache",
"(",
")",
"return",
"r"
] | This is the async constructor for the _Runtime class. | [
"This",
"is",
"the",
"async",
"constructor",
"for",
"the",
"_Runtime",
"class",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/runtime.py#L16-L20 | train |
buildinspace/peru | peru/runtime.py | find_project_file | def find_project_file(start_dir, basename):
'''Walk up the directory tree until we find a file of the given name.'''
prefix = os.path.abspath(start_dir)
while True:
candidate = os.path.join(prefix, basename)
if os.path.isfile(candidate):
return candidate
if os.path.exists... | python | def find_project_file(start_dir, basename):
'''Walk up the directory tree until we find a file of the given name.'''
prefix = os.path.abspath(start_dir)
while True:
candidate = os.path.join(prefix, basename)
if os.path.isfile(candidate):
return candidate
if os.path.exists... | [
"def",
"find_project_file",
"(",
"start_dir",
",",
"basename",
")",
":",
"prefix",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"start_dir",
")",
"while",
"True",
":",
"candidate",
"=",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"basename",
")... | Walk up the directory tree until we find a file of the given name. | [
"Walk",
"up",
"the",
"directory",
"tree",
"until",
"we",
"find",
"a",
"file",
"of",
"the",
"given",
"name",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/runtime.py#L150-L164 | train |
buildinspace/peru | peru/cache.py | delete_if_error | def delete_if_error(path):
'''If any exception is raised inside the context, delete the file at the
given path, and allow the exception to continue.'''
try:
yield
except Exception:
if os.path.exists(path):
os.remove(path)
raise | python | def delete_if_error(path):
'''If any exception is raised inside the context, delete the file at the
given path, and allow the exception to continue.'''
try:
yield
except Exception:
if os.path.exists(path):
os.remove(path)
raise | [
"def",
"delete_if_error",
"(",
"path",
")",
":",
"try",
":",
"yield",
"except",
"Exception",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"remove",
"(",
"path",
")",
"raise"
] | If any exception is raised inside the context, delete the file at the
given path, and allow the exception to continue. | [
"If",
"any",
"exception",
"is",
"raised",
"inside",
"the",
"context",
"delete",
"the",
"file",
"at",
"the",
"given",
"path",
"and",
"allow",
"the",
"exception",
"to",
"continue",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/cache.py#L516-L524 | train |
buildinspace/peru | peru/cache.py | _format_file_lines | def _format_file_lines(files):
'''Given a list of filenames that we're about to print, limit it to a
reasonable number of lines.'''
LINES_TO_SHOW = 10
if len(files) <= LINES_TO_SHOW:
lines = '\n'.join(files)
else:
lines = ('\n'.join(files[:LINES_TO_SHOW - 1]) + '\n...{} total'.format... | python | def _format_file_lines(files):
'''Given a list of filenames that we're about to print, limit it to a
reasonable number of lines.'''
LINES_TO_SHOW = 10
if len(files) <= LINES_TO_SHOW:
lines = '\n'.join(files)
else:
lines = ('\n'.join(files[:LINES_TO_SHOW - 1]) + '\n...{} total'.format... | [
"def",
"_format_file_lines",
"(",
"files",
")",
":",
"LINES_TO_SHOW",
"=",
"10",
"if",
"len",
"(",
"files",
")",
"<=",
"LINES_TO_SHOW",
":",
"lines",
"=",
"'\\n'",
".",
"join",
"(",
"files",
")",
"else",
":",
"lines",
"=",
"(",
"'\\n'",
".",
"join",
... | Given a list of filenames that we're about to print, limit it to a
reasonable number of lines. | [
"Given",
"a",
"list",
"of",
"filenames",
"that",
"we",
"re",
"about",
"to",
"print",
"limit",
"it",
"to",
"a",
"reasonable",
"number",
"of",
"lines",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/cache.py#L527-L536 | train |
buildinspace/peru | peru/cache.py | GitSession.git_env | def git_env(self):
'Set the index file and prevent git from reading global configs.'
env = dict(os.environ)
for var in ["HOME", "XDG_CONFIG_HOME"]:
env.pop(var, None)
env["GIT_CONFIG_NOSYSTEM"] = "true"
# Weirdly, GIT_INDEX_FILE is interpreted relative to the work tre... | python | def git_env(self):
'Set the index file and prevent git from reading global configs.'
env = dict(os.environ)
for var in ["HOME", "XDG_CONFIG_HOME"]:
env.pop(var, None)
env["GIT_CONFIG_NOSYSTEM"] = "true"
# Weirdly, GIT_INDEX_FILE is interpreted relative to the work tre... | [
"def",
"git_env",
"(",
"self",
")",
":",
"env",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"for",
"var",
"in",
"[",
"\"HOME\"",
",",
"\"XDG_CONFIG_HOME\"",
"]",
":",
"env",
".",
"pop",
"(",
"var",
",",
"None",
")",
"env",
"[",
"\"GIT_CONFIG_NOSYSTE... | Set the index file and prevent git from reading global configs. | [
"Set",
"the",
"index",
"file",
"and",
"prevent",
"git",
"from",
"reading",
"global",
"configs",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/cache.py#L79-L88 | train |
unitedstates/python-us | us/states.py | load_states | def load_states():
""" Load state data from pickle file distributed with this package.
Creates lists of states, territories, and combined states and
territories. Also adds state abbreviation attribute access
to the package: us.states.MD
"""
from pkg_resources import resource_stream... | python | def load_states():
""" Load state data from pickle file distributed with this package.
Creates lists of states, territories, and combined states and
territories. Also adds state abbreviation attribute access
to the package: us.states.MD
"""
from pkg_resources import resource_stream... | [
"def",
"load_states",
"(",
")",
":",
"from",
"pkg_resources",
"import",
"resource_stream",
"# load state data from pickle file",
"with",
"resource_stream",
"(",
"__name__",
",",
"'states.pkl'",
")",
"as",
"pklfile",
":",
"for",
"s",
"in",
"pickle",
".",
"load",
"(... | Load state data from pickle file distributed with this package.
Creates lists of states, territories, and combined states and
territories. Also adds state abbreviation attribute access
to the package: us.states.MD | [
"Load",
"state",
"data",
"from",
"pickle",
"file",
"distributed",
"with",
"this",
"package",
"."
] | 15165f47a0508bef3737d07d033eaf4b782fb039 | https://github.com/unitedstates/python-us/blob/15165f47a0508bef3737d07d033eaf4b782fb039/us/states.py#L59-L92 | train |
unitedstates/python-us | us/states.py | lookup | def lookup(val, field=None, use_cache=True):
""" Semi-fuzzy state lookup. This method will make a best effort
attempt at finding the state based on the lookup value provided.
* two digits will search for FIPS code
* two letters will search for state abbreviation
* anything els... | python | def lookup(val, field=None, use_cache=True):
""" Semi-fuzzy state lookup. This method will make a best effort
attempt at finding the state based on the lookup value provided.
* two digits will search for FIPS code
* two letters will search for state abbreviation
* anything els... | [
"def",
"lookup",
"(",
"val",
",",
"field",
"=",
"None",
",",
"use_cache",
"=",
"True",
")",
":",
"import",
"jellyfish",
"if",
"field",
"is",
"None",
":",
"if",
"FIPS_RE",
".",
"match",
"(",
"val",
")",
":",
"field",
"=",
"'fips'",
"elif",
"ABBR_RE",
... | Semi-fuzzy state lookup. This method will make a best effort
attempt at finding the state based on the lookup value provided.
* two digits will search for FIPS code
* two letters will search for state abbreviation
* anything else will try to match the metaphone of state names
... | [
"Semi",
"-",
"fuzzy",
"state",
"lookup",
".",
"This",
"method",
"will",
"make",
"a",
"best",
"effort",
"attempt",
"at",
"finding",
"the",
"state",
"based",
"on",
"the",
"lookup",
"value",
"provided",
"."
] | 15165f47a0508bef3737d07d033eaf4b782fb039 | https://github.com/unitedstates/python-us/blob/15165f47a0508bef3737d07d033eaf4b782fb039/us/states.py#L95-L134 | train |
venthur/gscholar | gscholar/gscholar.py | query | def query(searchstr, outformat=FORMAT_BIBTEX, allresults=False):
"""Query google scholar.
This method queries google scholar and returns a list of citations.
Parameters
----------
searchstr : str
the query
outformat : int, optional
the output format of the citations. Default is... | python | def query(searchstr, outformat=FORMAT_BIBTEX, allresults=False):
"""Query google scholar.
This method queries google scholar and returns a list of citations.
Parameters
----------
searchstr : str
the query
outformat : int, optional
the output format of the citations. Default is... | [
"def",
"query",
"(",
"searchstr",
",",
"outformat",
"=",
"FORMAT_BIBTEX",
",",
"allresults",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Query: {sstring}\"",
".",
"format",
"(",
"sstring",
"=",
"searchstr",
")",
")",
"searchstr",
"=",
"'/scholar?... | Query google scholar.
This method queries google scholar and returns a list of citations.
Parameters
----------
searchstr : str
the query
outformat : int, optional
the output format of the citations. Default is bibtex.
allresults : bool, optional
return all results or o... | [
"Query",
"google",
"scholar",
"."
] | f2f830c4009a4e9a393a81675d5ad88b9b2d87b9 | https://github.com/venthur/gscholar/blob/f2f830c4009a4e9a393a81675d5ad88b9b2d87b9/gscholar/gscholar.py#L43-L86 | train |
venthur/gscholar | gscholar/gscholar.py | get_links | def get_links(html, outformat):
"""Return a list of reference links from the html.
Parameters
----------
html : str
outformat : int
the output format of the citations
Returns
-------
List[str]
the links to the references
"""
if outformat == FORMAT_BIBTEX:
... | python | def get_links(html, outformat):
"""Return a list of reference links from the html.
Parameters
----------
html : str
outformat : int
the output format of the citations
Returns
-------
List[str]
the links to the references
"""
if outformat == FORMAT_BIBTEX:
... | [
"def",
"get_links",
"(",
"html",
",",
"outformat",
")",
":",
"if",
"outformat",
"==",
"FORMAT_BIBTEX",
":",
"refre",
"=",
"re",
".",
"compile",
"(",
"r'<a href=\"https://scholar.googleusercontent.com(/scholar\\.bib\\?[^\"]*)'",
")",
"elif",
"outformat",
"==",
"FORMAT_... | Return a list of reference links from the html.
Parameters
----------
html : str
outformat : int
the output format of the citations
Returns
-------
List[str]
the links to the references | [
"Return",
"a",
"list",
"of",
"reference",
"links",
"from",
"the",
"html",
"."
] | f2f830c4009a4e9a393a81675d5ad88b9b2d87b9 | https://github.com/venthur/gscholar/blob/f2f830c4009a4e9a393a81675d5ad88b9b2d87b9/gscholar/gscholar.py#L89-L116 | train |
venthur/gscholar | gscholar/gscholar.py | convert_pdf_to_txt | def convert_pdf_to_txt(pdf, startpage=None):
"""Convert a pdf file to text and return the text.
This method requires pdftotext to be installed.
Parameters
----------
pdf : str
path to pdf file
startpage : int, optional
the first page we try to convert
Returns
-------
... | python | def convert_pdf_to_txt(pdf, startpage=None):
"""Convert a pdf file to text and return the text.
This method requires pdftotext to be installed.
Parameters
----------
pdf : str
path to pdf file
startpage : int, optional
the first page we try to convert
Returns
-------
... | [
"def",
"convert_pdf_to_txt",
"(",
"pdf",
",",
"startpage",
"=",
"None",
")",
":",
"if",
"startpage",
"is",
"not",
"None",
":",
"startpageargs",
"=",
"[",
"'-f'",
",",
"str",
"(",
"startpage",
")",
"]",
"else",
":",
"startpageargs",
"=",
"[",
"]",
"stdo... | Convert a pdf file to text and return the text.
This method requires pdftotext to be installed.
Parameters
----------
pdf : str
path to pdf file
startpage : int, optional
the first page we try to convert
Returns
-------
str
the converted text | [
"Convert",
"a",
"pdf",
"file",
"to",
"text",
"and",
"return",
"the",
"text",
"."
] | f2f830c4009a4e9a393a81675d5ad88b9b2d87b9 | https://github.com/venthur/gscholar/blob/f2f830c4009a4e9a393a81675d5ad88b9b2d87b9/gscholar/gscholar.py#L119-L146 | train |
venthur/gscholar | gscholar/gscholar.py | pdflookup | def pdflookup(pdf, allresults, outformat, startpage=None):
"""Look a pdf up on google scholar and return bibtex items.
Paramters
---------
pdf : str
path to the pdf file
allresults : bool
return all results or only the first (i.e. best one)
outformat : int
the output for... | python | def pdflookup(pdf, allresults, outformat, startpage=None):
"""Look a pdf up on google scholar and return bibtex items.
Paramters
---------
pdf : str
path to the pdf file
allresults : bool
return all results or only the first (i.e. best one)
outformat : int
the output for... | [
"def",
"pdflookup",
"(",
"pdf",
",",
"allresults",
",",
"outformat",
",",
"startpage",
"=",
"None",
")",
":",
"txt",
"=",
"convert_pdf_to_txt",
"(",
"pdf",
",",
"startpage",
")",
"# remove all non alphanumeric characters",
"txt",
"=",
"re",
".",
"sub",
"(",
... | Look a pdf up on google scholar and return bibtex items.
Paramters
---------
pdf : str
path to the pdf file
allresults : bool
return all results or only the first (i.e. best one)
outformat : int
the output format of the citations
startpage : int
first page to sta... | [
"Look",
"a",
"pdf",
"up",
"on",
"google",
"scholar",
"and",
"return",
"bibtex",
"items",
"."
] | f2f830c4009a4e9a393a81675d5ad88b9b2d87b9 | https://github.com/venthur/gscholar/blob/f2f830c4009a4e9a393a81675d5ad88b9b2d87b9/gscholar/gscholar.py#L149-L175 | train |
venthur/gscholar | gscholar/gscholar.py | _get_bib_element | def _get_bib_element(bibitem, element):
"""Return element from bibitem or None.
Paramteters
-----------
bibitem :
element :
Returns
-------
"""
lst = [i.strip() for i in bibitem.split("\n")]
for i in lst:
if i.startswith(element):
value = i.split("=", 1)[-1... | python | def _get_bib_element(bibitem, element):
"""Return element from bibitem or None.
Paramteters
-----------
bibitem :
element :
Returns
-------
"""
lst = [i.strip() for i in bibitem.split("\n")]
for i in lst:
if i.startswith(element):
value = i.split("=", 1)[-1... | [
"def",
"_get_bib_element",
"(",
"bibitem",
",",
"element",
")",
":",
"lst",
"=",
"[",
"i",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"bibitem",
".",
"split",
"(",
"\"\\n\"",
")",
"]",
"for",
"i",
"in",
"lst",
":",
"if",
"i",
".",
"startswith",
"(... | Return element from bibitem or None.
Paramteters
-----------
bibitem :
element :
Returns
------- | [
"Return",
"element",
"from",
"bibitem",
"or",
"None",
"."
] | f2f830c4009a4e9a393a81675d5ad88b9b2d87b9 | https://github.com/venthur/gscholar/blob/f2f830c4009a4e9a393a81675d5ad88b9b2d87b9/gscholar/gscholar.py#L178-L200 | train |
venthur/gscholar | gscholar/gscholar.py | rename_file | def rename_file(pdf, bibitem):
"""Attempt to rename pdf according to bibitem.
"""
year = _get_bib_element(bibitem, "year")
author = _get_bib_element(bibitem, "author")
if author:
author = author.split(",")[0]
title = _get_bib_element(bibitem, "title")
l = [i for i in (year, author, ... | python | def rename_file(pdf, bibitem):
"""Attempt to rename pdf according to bibitem.
"""
year = _get_bib_element(bibitem, "year")
author = _get_bib_element(bibitem, "author")
if author:
author = author.split(",")[0]
title = _get_bib_element(bibitem, "title")
l = [i for i in (year, author, ... | [
"def",
"rename_file",
"(",
"pdf",
",",
"bibitem",
")",
":",
"year",
"=",
"_get_bib_element",
"(",
"bibitem",
",",
"\"year\"",
")",
"author",
"=",
"_get_bib_element",
"(",
"bibitem",
",",
"\"author\"",
")",
"if",
"author",
":",
"author",
"=",
"author",
".",... | Attempt to rename pdf according to bibitem. | [
"Attempt",
"to",
"rename",
"pdf",
"according",
"to",
"bibitem",
"."
] | f2f830c4009a4e9a393a81675d5ad88b9b2d87b9 | https://github.com/venthur/gscholar/blob/f2f830c4009a4e9a393a81675d5ad88b9b2d87b9/gscholar/gscholar.py#L203-L216 | train |
greedo/python-xbrl | xbrl/xbrl.py | soup_maker | def soup_maker(fh):
""" Takes a file handler returns BeautifulSoup"""
try:
from bs4 import BeautifulSoup
soup = BeautifulSoup(fh, "lxml")
for tag in soup.find_all():
tag.name = tag.name.lower()
except ImportError:
from BeautifulSoup import BeautifulStoneSoup
... | python | def soup_maker(fh):
""" Takes a file handler returns BeautifulSoup"""
try:
from bs4 import BeautifulSoup
soup = BeautifulSoup(fh, "lxml")
for tag in soup.find_all():
tag.name = tag.name.lower()
except ImportError:
from BeautifulSoup import BeautifulStoneSoup
... | [
"def",
"soup_maker",
"(",
"fh",
")",
":",
"try",
":",
"from",
"bs4",
"import",
"BeautifulSoup",
"soup",
"=",
"BeautifulSoup",
"(",
"fh",
",",
"\"lxml\"",
")",
"for",
"tag",
"in",
"soup",
".",
"find_all",
"(",
")",
":",
"tag",
".",
"name",
"=",
"tag",... | Takes a file handler returns BeautifulSoup | [
"Takes",
"a",
"file",
"handler",
"returns",
"BeautifulSoup"
] | e6baa4de61333f7fcead758a1072c21943563b49 | https://github.com/greedo/python-xbrl/blob/e6baa4de61333f7fcead758a1072c21943563b49/xbrl/xbrl.py#L22-L32 | train |
greedo/python-xbrl | xbrl/xbrl.py | XBRLParser.parse | def parse(self, file_handle):
"""
parse is the main entry point for an XBRLParser. It takes a file
handle.
"""
xbrl_obj = XBRL()
# if no file handle was given create our own
if not hasattr(file_handle, 'read'):
file_handler = open(file_handle)
... | python | def parse(self, file_handle):
"""
parse is the main entry point for an XBRLParser. It takes a file
handle.
"""
xbrl_obj = XBRL()
# if no file handle was given create our own
if not hasattr(file_handle, 'read'):
file_handler = open(file_handle)
... | [
"def",
"parse",
"(",
"self",
",",
"file_handle",
")",
":",
"xbrl_obj",
"=",
"XBRL",
"(",
")",
"# if no file handle was given create our own",
"if",
"not",
"hasattr",
"(",
"file_handle",
",",
"'read'",
")",
":",
"file_handler",
"=",
"open",
"(",
"file_handle",
... | parse is the main entry point for an XBRLParser. It takes a file
handle. | [
"parse",
"is",
"the",
"main",
"entry",
"point",
"for",
"an",
"XBRLParser",
".",
"It",
"takes",
"a",
"file",
"handle",
"."
] | e6baa4de61333f7fcead758a1072c21943563b49 | https://github.com/greedo/python-xbrl/blob/e6baa4de61333f7fcead758a1072c21943563b49/xbrl/xbrl.py#L54-L86 | train |
greedo/python-xbrl | xbrl/xbrl.py | XBRLParser.parseDEI | def parseDEI(self,
xbrl,
ignore_errors=0):
"""
Parse DEI from our XBRL soup and return a DEI object.
"""
dei_obj = DEI()
if ignore_errors == 2:
logging.basicConfig(filename='/tmp/xbrl.log',
level=logging.ERROR,
... | python | def parseDEI(self,
xbrl,
ignore_errors=0):
"""
Parse DEI from our XBRL soup and return a DEI object.
"""
dei_obj = DEI()
if ignore_errors == 2:
logging.basicConfig(filename='/tmp/xbrl.log',
level=logging.ERROR,
... | [
"def",
"parseDEI",
"(",
"self",
",",
"xbrl",
",",
"ignore_errors",
"=",
"0",
")",
":",
"dei_obj",
"=",
"DEI",
"(",
")",
"if",
"ignore_errors",
"==",
"2",
":",
"logging",
".",
"basicConfig",
"(",
"filename",
"=",
"'/tmp/xbrl.log'",
",",
"level",
"=",
"l... | Parse DEI from our XBRL soup and return a DEI object. | [
"Parse",
"DEI",
"from",
"our",
"XBRL",
"soup",
"and",
"return",
"a",
"DEI",
"object",
"."
] | e6baa4de61333f7fcead758a1072c21943563b49 | https://github.com/greedo/python-xbrl/blob/e6baa4de61333f7fcead758a1072c21943563b49/xbrl/xbrl.py#L585-L633 | train |
greedo/python-xbrl | xbrl/xbrl.py | XBRLParser.parseCustom | def parseCustom(self,
xbrl,
ignore_errors=0):
"""
Parse company custom entities from XBRL and return an Custom object.
"""
custom_obj = Custom()
custom_data = xbrl.find_all(re.compile('^((?!(us-gaap|dei|xbrll|xbrldi)).)*:\s*',
... | python | def parseCustom(self,
xbrl,
ignore_errors=0):
"""
Parse company custom entities from XBRL and return an Custom object.
"""
custom_obj = Custom()
custom_data = xbrl.find_all(re.compile('^((?!(us-gaap|dei|xbrll|xbrldi)).)*:\s*',
... | [
"def",
"parseCustom",
"(",
"self",
",",
"xbrl",
",",
"ignore_errors",
"=",
"0",
")",
":",
"custom_obj",
"=",
"Custom",
"(",
")",
"custom_data",
"=",
"xbrl",
".",
"find_all",
"(",
"re",
".",
"compile",
"(",
"'^((?!(us-gaap|dei|xbrll|xbrldi)).)*:\\s*'",
",",
"... | Parse company custom entities from XBRL and return an Custom object. | [
"Parse",
"company",
"custom",
"entities",
"from",
"XBRL",
"and",
"return",
"an",
"Custom",
"object",
"."
] | e6baa4de61333f7fcead758a1072c21943563b49 | https://github.com/greedo/python-xbrl/blob/e6baa4de61333f7fcead758a1072c21943563b49/xbrl/xbrl.py#L636-L652 | train |
greedo/python-xbrl | xbrl/xbrl.py | XBRLParser.trim_decimals | def trim_decimals(s, precision=-3):
"""
Convert from scientific notation using precision
"""
encoded = s.encode('ascii', 'ignore')
str_val = ""
if six.PY3:
str_val = str(encoded, encoding='ascii', errors='ignore')[:precision]
else:
# If pre... | python | def trim_decimals(s, precision=-3):
"""
Convert from scientific notation using precision
"""
encoded = s.encode('ascii', 'ignore')
str_val = ""
if six.PY3:
str_val = str(encoded, encoding='ascii', errors='ignore')[:precision]
else:
# If pre... | [
"def",
"trim_decimals",
"(",
"s",
",",
"precision",
"=",
"-",
"3",
")",
":",
"encoded",
"=",
"s",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"str_val",
"=",
"\"\"",
"if",
"six",
".",
"PY3",
":",
"str_val",
"=",
"str",
"(",
"encoded",
",",... | Convert from scientific notation using precision | [
"Convert",
"from",
"scientific",
"notation",
"using",
"precision"
] | e6baa4de61333f7fcead758a1072c21943563b49 | https://github.com/greedo/python-xbrl/blob/e6baa4de61333f7fcead758a1072c21943563b49/xbrl/xbrl.py#L655-L672 | train |
greedo/python-xbrl | xbrl/xbrl.py | XBRLParser.data_processing | def data_processing(self,
elements,
xbrl,
ignore_errors,
logger,
context_ids=[],
**kwargs):
"""
Process a XBRL tag object and extract the correct value as
... | python | def data_processing(self,
elements,
xbrl,
ignore_errors,
logger,
context_ids=[],
**kwargs):
"""
Process a XBRL tag object and extract the correct value as
... | [
"def",
"data_processing",
"(",
"self",
",",
"elements",
",",
"xbrl",
",",
"ignore_errors",
",",
"logger",
",",
"context_ids",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"kwargs",
".",
"get",
"(",
"'options'",
",",
"{",
"'type'",
... | Process a XBRL tag object and extract the correct value as
stated by the context. | [
"Process",
"a",
"XBRL",
"tag",
"object",
"and",
"extract",
"the",
"correct",
"value",
"as",
"stated",
"by",
"the",
"context",
"."
] | e6baa4de61333f7fcead758a1072c21943563b49 | https://github.com/greedo/python-xbrl/blob/e6baa4de61333f7fcead758a1072c21943563b49/xbrl/xbrl.py#L686-L739 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/managers.py | PreferencesManager.by_name | def by_name(self):
"""Return a dictionary with preferences identifiers and values, but without the section name in the identifier"""
return {key.split(preferences_settings.SECTION_KEY_SEPARATOR)[-1]: value for key, value in self.all().items()} | python | def by_name(self):
"""Return a dictionary with preferences identifiers and values, but without the section name in the identifier"""
return {key.split(preferences_settings.SECTION_KEY_SEPARATOR)[-1]: value for key, value in self.all().items()} | [
"def",
"by_name",
"(",
"self",
")",
":",
"return",
"{",
"key",
".",
"split",
"(",
"preferences_settings",
".",
"SECTION_KEY_SEPARATOR",
")",
"[",
"-",
"1",
"]",
":",
"value",
"for",
"key",
",",
"value",
"in",
"self",
".",
"all",
"(",
")",
".",
"items... | Return a dictionary with preferences identifiers and values, but without the section name in the identifier | [
"Return",
"a",
"dictionary",
"with",
"preferences",
"identifiers",
"and",
"values",
"but",
"without",
"the",
"section",
"name",
"in",
"the",
"identifier"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/managers.py#L47-L49 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/managers.py | PreferencesManager.get_cache_key | def get_cache_key(self, section, name):
"""Return the cache key corresponding to a given preference"""
if not self.instance:
return 'dynamic_preferences_{0}_{1}_{2}'.format(self.model.__name__, section, name)
return 'dynamic_preferences_{0}_{1}_{2}_{3}'.format(self.model.__name__, se... | python | def get_cache_key(self, section, name):
"""Return the cache key corresponding to a given preference"""
if not self.instance:
return 'dynamic_preferences_{0}_{1}_{2}'.format(self.model.__name__, section, name)
return 'dynamic_preferences_{0}_{1}_{2}_{3}'.format(self.model.__name__, se... | [
"def",
"get_cache_key",
"(",
"self",
",",
"section",
",",
"name",
")",
":",
"if",
"not",
"self",
".",
"instance",
":",
"return",
"'dynamic_preferences_{0}_{1}_{2}'",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"section",
",",
"name",
")... | Return the cache key corresponding to a given preference | [
"Return",
"the",
"cache",
"key",
"corresponding",
"to",
"a",
"given",
"preference"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/managers.py#L54-L58 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/managers.py | PreferencesManager.from_cache | def from_cache(self, section, name):
"""Return a preference raw_value from cache"""
cached_value = self.cache.get(
self.get_cache_key(section, name), CachedValueNotFound)
if cached_value is CachedValueNotFound:
raise CachedValueNotFound
if cached_value == prefer... | python | def from_cache(self, section, name):
"""Return a preference raw_value from cache"""
cached_value = self.cache.get(
self.get_cache_key(section, name), CachedValueNotFound)
if cached_value is CachedValueNotFound:
raise CachedValueNotFound
if cached_value == prefer... | [
"def",
"from_cache",
"(",
"self",
",",
"section",
",",
"name",
")",
":",
"cached_value",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"self",
".",
"get_cache_key",
"(",
"section",
",",
"name",
")",
",",
"CachedValueNotFound",
")",
"if",
"cached_value",
"i... | Return a preference raw_value from cache | [
"Return",
"a",
"preference",
"raw_value",
"from",
"cache"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/managers.py#L60-L71 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/managers.py | PreferencesManager.many_from_cache | def many_from_cache(self, preferences):
"""
Return cached value for given preferences
missing preferences will be skipped
"""
keys = {
p: self.get_cache_key(p.section.name, p.name)
for p in preferences
}
cached = self.cache.get_many(list(ke... | python | def many_from_cache(self, preferences):
"""
Return cached value for given preferences
missing preferences will be skipped
"""
keys = {
p: self.get_cache_key(p.section.name, p.name)
for p in preferences
}
cached = self.cache.get_many(list(ke... | [
"def",
"many_from_cache",
"(",
"self",
",",
"preferences",
")",
":",
"keys",
"=",
"{",
"p",
":",
"self",
".",
"get_cache_key",
"(",
"p",
".",
"section",
".",
"name",
",",
"p",
".",
"name",
")",
"for",
"p",
"in",
"preferences",
"}",
"cached",
"=",
"... | Return cached value for given preferences
missing preferences will be skipped | [
"Return",
"cached",
"value",
"for",
"given",
"preferences",
"missing",
"preferences",
"will",
"be",
"skipped"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/managers.py#L73-L95 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/managers.py | PreferencesManager.all | def all(self):
"""Return a dictionary containing all preferences by section
Loaded from cache or from db in case of cold cache
"""
if not preferences_settings.ENABLE_CACHE:
return self.load_from_db()
preferences = self.registry.preferences()
# first we hit t... | python | def all(self):
"""Return a dictionary containing all preferences by section
Loaded from cache or from db in case of cold cache
"""
if not preferences_settings.ENABLE_CACHE:
return self.load_from_db()
preferences = self.registry.preferences()
# first we hit t... | [
"def",
"all",
"(",
"self",
")",
":",
"if",
"not",
"preferences_settings",
".",
"ENABLE_CACHE",
":",
"return",
"self",
".",
"load_from_db",
"(",
")",
"preferences",
"=",
"self",
".",
"registry",
".",
"preferences",
"(",
")",
"# first we hit the cache once for all... | Return a dictionary containing all preferences by section
Loaded from cache or from db in case of cold cache | [
"Return",
"a",
"dictionary",
"containing",
"all",
"preferences",
"by",
"section",
"Loaded",
"from",
"cache",
"or",
"from",
"db",
"in",
"case",
"of",
"cold",
"cache"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/managers.py#L182-L200 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/managers.py | PreferencesManager.load_from_db | def load_from_db(self, cache=False):
"""Return a dictionary of preferences by section directly from DB"""
a = {}
db_prefs = {p.preference.identifier(): p for p in self.queryset}
for preference in self.registry.preferences():
try:
db_pref = db_prefs[preference.... | python | def load_from_db(self, cache=False):
"""Return a dictionary of preferences by section directly from DB"""
a = {}
db_prefs = {p.preference.identifier(): p for p in self.queryset}
for preference in self.registry.preferences():
try:
db_pref = db_prefs[preference.... | [
"def",
"load_from_db",
"(",
"self",
",",
"cache",
"=",
"False",
")",
":",
"a",
"=",
"{",
"}",
"db_prefs",
"=",
"{",
"p",
".",
"preference",
".",
"identifier",
"(",
")",
":",
"p",
"for",
"p",
"in",
"self",
".",
"queryset",
"}",
"for",
"preference",
... | Return a dictionary of preferences by section directly from DB | [
"Return",
"a",
"dictionary",
"of",
"preferences",
"by",
"section",
"directly",
"from",
"DB"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/managers.py#L202-L221 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/api/serializers.py | PreferenceSerializer.validate_value | def validate_value(self, value):
"""
We call validation from the underlying form field
"""
field = self.instance.preference.setup_field()
value = field.to_python(value)
field.validate(value)
field.run_validators(value)
return value | python | def validate_value(self, value):
"""
We call validation from the underlying form field
"""
field = self.instance.preference.setup_field()
value = field.to_python(value)
field.validate(value)
field.run_validators(value)
return value | [
"def",
"validate_value",
"(",
"self",
",",
"value",
")",
":",
"field",
"=",
"self",
".",
"instance",
".",
"preference",
".",
"setup_field",
"(",
")",
"value",
"=",
"field",
".",
"to_python",
"(",
"value",
")",
"field",
".",
"validate",
"(",
"value",
")... | We call validation from the underlying form field | [
"We",
"call",
"validation",
"from",
"the",
"underlying",
"form",
"field"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/api/serializers.py#L58-L66 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/serializers.py | StringSerializer.to_python | def to_python(cls, value, **kwargs):
"""String deserialisation just return the value as a string"""
if not value:
return ''
try:
return str(value)
except:
pass
try:
return value.encode('utf-8')
except:
pass
... | python | def to_python(cls, value, **kwargs):
"""String deserialisation just return the value as a string"""
if not value:
return ''
try:
return str(value)
except:
pass
try:
return value.encode('utf-8')
except:
pass
... | [
"def",
"to_python",
"(",
"cls",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
":",
"return",
"''",
"try",
":",
"return",
"str",
"(",
"value",
")",
"except",
":",
"pass",
"try",
":",
"return",
"value",
".",
"encode",
"(",
... | String deserialisation just return the value as a string | [
"String",
"deserialisation",
"just",
"return",
"the",
"value",
"as",
"a",
"string"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/serializers.py#L191-L203 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/registries.py | PreferenceModelsRegistry.get_by_instance | def get_by_instance(self, instance):
"""Return a preference registry using a model instance"""
# we iterate throught registered preference models in order to get the instance class
# and check if instance is and instance of this class
for model, registry in self.items():
try:... | python | def get_by_instance(self, instance):
"""Return a preference registry using a model instance"""
# we iterate throught registered preference models in order to get the instance class
# and check if instance is and instance of this class
for model, registry in self.items():
try:... | [
"def",
"get_by_instance",
"(",
"self",
",",
"instance",
")",
":",
"# we iterate throught registered preference models in order to get the instance class",
"# and check if instance is and instance of this class",
"for",
"model",
",",
"registry",
"in",
"self",
".",
"items",
"(",
... | Return a preference registry using a model instance | [
"Return",
"a",
"preference",
"registry",
"using",
"a",
"model",
"instance"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/registries.py#L60-L72 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/registries.py | PreferenceRegistry.register | def register(self, preference_class):
"""
Store the given preference class in the registry.
:param preference_class: a :py:class:`prefs.Preference` subclass
"""
preference = preference_class(registry=self)
self.section_objects[preference.section.name] = preference.sectio... | python | def register(self, preference_class):
"""
Store the given preference class in the registry.
:param preference_class: a :py:class:`prefs.Preference` subclass
"""
preference = preference_class(registry=self)
self.section_objects[preference.section.name] = preference.sectio... | [
"def",
"register",
"(",
"self",
",",
"preference_class",
")",
":",
"preference",
"=",
"preference_class",
"(",
"registry",
"=",
"self",
")",
"self",
".",
"section_objects",
"[",
"preference",
".",
"section",
".",
"name",
"]",
"=",
"preference",
".",
"section... | Store the given preference class in the registry.
:param preference_class: a :py:class:`prefs.Preference` subclass | [
"Store",
"the",
"given",
"preference",
"class",
"in",
"the",
"registry",
"."
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/registries.py#L105-L121 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/registries.py | PreferenceRegistry.get | def get(self, name, section=None, fallback=False):
"""
Returns a previously registered preference
:param section: The section name under which the preference is registered
:type section: str.
:param name: The name of the preference. You can use dotted notation 'section.name' if ... | python | def get(self, name, section=None, fallback=False):
"""
Returns a previously registered preference
:param section: The section name under which the preference is registered
:type section: str.
:param name: The name of the preference. You can use dotted notation 'section.name' if ... | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"section",
"=",
"None",
",",
"fallback",
"=",
"False",
")",
":",
"# try dotted notation",
"try",
":",
"_section",
",",
"name",
"=",
"name",
".",
"split",
"(",
"preferences_settings",
".",
"SECTION_KEY_SEPARATOR",
... | Returns a previously registered preference
:param section: The section name under which the preference is registered
:type section: str.
:param name: The name of the preference. You can use dotted notation 'section.name' if you want to avoid providing section param
:type name: str.
... | [
"Returns",
"a",
"previously",
"registered",
"preference"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/registries.py#L146-L175 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/registries.py | PreferenceRegistry.manager | def manager(self, **kwargs):
"""Return a preference manager that can be used to retrieve preference values"""
return PreferencesManager(registry=self, model=self.preference_model, **kwargs) | python | def manager(self, **kwargs):
"""Return a preference manager that can be used to retrieve preference values"""
return PreferencesManager(registry=self, model=self.preference_model, **kwargs) | [
"def",
"manager",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"PreferencesManager",
"(",
"registry",
"=",
"self",
",",
"model",
"=",
"self",
".",
"preference_model",
",",
"*",
"*",
"kwargs",
")"
] | Return a preference manager that can be used to retrieve preference values | [
"Return",
"a",
"preference",
"manager",
"that",
"can",
"be",
"used",
"to",
"retrieve",
"preference",
"values"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/registries.py#L186-L188 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/registries.py | PreferenceRegistry.preferences | def preferences(self, section=None):
"""
Return a list of all registered preferences
or a list of preferences registered for a given section
:param section: The section name under which the preference is registered
:type section: str.
:return: a list of :py:class:`prefs.... | python | def preferences(self, section=None):
"""
Return a list of all registered preferences
or a list of preferences registered for a given section
:param section: The section name under which the preference is registered
:type section: str.
:return: a list of :py:class:`prefs.... | [
"def",
"preferences",
"(",
"self",
",",
"section",
"=",
"None",
")",
":",
"if",
"section",
"is",
"None",
":",
"return",
"[",
"self",
"[",
"section",
"]",
"[",
"name",
"]",
"for",
"section",
"in",
"self",
"for",
"name",
"in",
"self",
"[",
"section",
... | Return a list of all registered preferences
or a list of preferences registered for a given section
:param section: The section name under which the preference is registered
:type section: str.
:return: a list of :py:class:`prefs.BasePreference` instances | [
"Return",
"a",
"list",
"of",
"all",
"registered",
"preferences",
"or",
"a",
"list",
"of",
"preferences",
"registered",
"for",
"a",
"given",
"section"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/registries.py#L198-L211 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/api/viewsets.py | PreferenceViewSet.get_queryset | def get_queryset(self):
"""
We just ensure preferences are actually populated before fetching
from db
"""
self.init_preferences()
queryset = super(PreferenceViewSet, self).get_queryset()
section = self.request.query_params.get('section')
if section:
... | python | def get_queryset(self):
"""
We just ensure preferences are actually populated before fetching
from db
"""
self.init_preferences()
queryset = super(PreferenceViewSet, self).get_queryset()
section = self.request.query_params.get('section')
if section:
... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"self",
".",
"init_preferences",
"(",
")",
"queryset",
"=",
"super",
"(",
"PreferenceViewSet",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"section",
"=",
"self",
".",
"request",
".",
"query_params",
".",
... | We just ensure preferences are actually populated before fetching
from db | [
"We",
"just",
"ensure",
"preferences",
"are",
"actually",
"populated",
"before",
"fetching",
"from",
"db"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/api/viewsets.py#L30-L42 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/api/viewsets.py | PreferenceViewSet.bulk | def bulk(self, request, *args, **kwargs):
"""
Update multiple preferences at once
this is a long method because we ensure everything is valid
before actually persisting the changes
"""
manager = self.get_manager()
errors = {}
preferences = []
payl... | python | def bulk(self, request, *args, **kwargs):
"""
Update multiple preferences at once
this is a long method because we ensure everything is valid
before actually persisting the changes
"""
manager = self.get_manager()
errors = {}
preferences = []
payl... | [
"def",
"bulk",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"manager",
"=",
"self",
".",
"get_manager",
"(",
")",
"errors",
"=",
"{",
"}",
"preferences",
"=",
"[",
"]",
"payload",
"=",
"request",
".",
"data",
... | Update multiple preferences at once
this is a long method because we ensure everything is valid
before actually persisting the changes | [
"Update",
"multiple",
"preferences",
"at",
"once"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/api/viewsets.py#L82-L144 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/models.py | BasePreferenceModel.set_value | def set_value(self, value):
"""
Save serialized self.value to self.raw_value
"""
self.raw_value = self.preference.serializer.serialize(value) | python | def set_value(self, value):
"""
Save serialized self.value to self.raw_value
"""
self.raw_value = self.preference.serializer.serialize(value) | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"raw_value",
"=",
"self",
".",
"preference",
".",
"serializer",
".",
"serialize",
"(",
"value",
")"
] | Save serialized self.value to self.raw_value | [
"Save",
"serialized",
"self",
".",
"value",
"to",
"self",
".",
"raw_value"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/models.py#L49-L53 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/management/commands/checkpreferences.py | delete_preferences | def delete_preferences(queryset):
"""
Delete preferences objects if they are not present in registry. Return a list of deleted objects
"""
deleted = []
# Iterate through preferences. If an error is raised when accessing preference object, just delete it
for p in queryset:
try:
... | python | def delete_preferences(queryset):
"""
Delete preferences objects if they are not present in registry. Return a list of deleted objects
"""
deleted = []
# Iterate through preferences. If an error is raised when accessing preference object, just delete it
for p in queryset:
try:
... | [
"def",
"delete_preferences",
"(",
"queryset",
")",
":",
"deleted",
"=",
"[",
"]",
"# Iterate through preferences. If an error is raised when accessing preference object, just delete it",
"for",
"p",
"in",
"queryset",
":",
"try",
":",
"pref",
"=",
"p",
".",
"registry",
"... | Delete preferences objects if they are not present in registry. Return a list of deleted objects | [
"Delete",
"preferences",
"objects",
"if",
"they",
"are",
"not",
"present",
"in",
"registry",
".",
"Return",
"a",
"list",
"of",
"deleted",
"objects"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/management/commands/checkpreferences.py#L10-L24 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/types.py | create_deletion_handler | def create_deletion_handler(preference):
"""
Will generate a dynamic handler to purge related preference
on instance deletion
"""
def delete_related_preferences(sender, instance, *args, **kwargs):
queryset = preference.registry.preference_model.objects\
... | python | def create_deletion_handler(preference):
"""
Will generate a dynamic handler to purge related preference
on instance deletion
"""
def delete_related_preferences(sender, instance, *args, **kwargs):
queryset = preference.registry.preference_model.objects\
... | [
"def",
"create_deletion_handler",
"(",
"preference",
")",
":",
"def",
"delete_related_preferences",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"preference",
".",
"registry",
".",
"preference_model",
".... | Will generate a dynamic handler to purge related preference
on instance deletion | [
"Will",
"generate",
"a",
"dynamic",
"handler",
"to",
"purge",
"related",
"preference",
"on",
"instance",
"deletion"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/types.py#L250-L262 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/types.py | BasePreferenceType.get_field_kwargs | def get_field_kwargs(self):
"""
Return a dict of arguments to use as parameters for the field
class instianciation.
This will use :py:attr:`field_kwargs` as a starter,
and use sensible defaults for a few attributes:
- :py:attr:`instance.verbose_name` for the field label... | python | def get_field_kwargs(self):
"""
Return a dict of arguments to use as parameters for the field
class instianciation.
This will use :py:attr:`field_kwargs` as a starter,
and use sensible defaults for a few attributes:
- :py:attr:`instance.verbose_name` for the field label... | [
"def",
"get_field_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"self",
".",
"field_kwargs",
".",
"copy",
"(",
")",
"kwargs",
".",
"setdefault",
"(",
"'label'",
",",
"self",
".",
"get",
"(",
"'verbose_name'",
")",
")",
"kwargs",
".",
"setdefault",
"(",
... | Return a dict of arguments to use as parameters for the field
class instianciation.
This will use :py:attr:`field_kwargs` as a starter,
and use sensible defaults for a few attributes:
- :py:attr:`instance.verbose_name` for the field label
- :py:attr:`instance.help_text` for the... | [
"Return",
"a",
"dict",
"of",
"arguments",
"to",
"use",
"as",
"parameters",
"for",
"the",
"field",
"class",
"instianciation",
"."
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/types.py#L84-L106 | train |
EliotBerriot/django-dynamic-preferences | dynamic_preferences/types.py | BasePreferenceType.get_api_field_data | def get_api_field_data(self):
"""
Field data to serialize for use on front-end side, for example
will include choices available for a choice field
"""
field = self.setup_field()
d = {
'class': field.__class__.__name__,
'widget': {
'... | python | def get_api_field_data(self):
"""
Field data to serialize for use on front-end side, for example
will include choices available for a choice field
"""
field = self.setup_field()
d = {
'class': field.__class__.__name__,
'widget': {
'... | [
"def",
"get_api_field_data",
"(",
"self",
")",
":",
"field",
"=",
"self",
".",
"setup_field",
"(",
")",
"d",
"=",
"{",
"'class'",
":",
"field",
".",
"__class__",
".",
"__name__",
",",
"'widget'",
":",
"{",
"'class'",
":",
"field",
".",
"widget",
".",
... | Field data to serialize for use on front-end side, for example
will include choices available for a choice field | [
"Field",
"data",
"to",
"serialize",
"for",
"use",
"on",
"front",
"-",
"end",
"side",
"for",
"example",
"will",
"include",
"choices",
"available",
"for",
"a",
"choice",
"field"
] | 12eab4f17b960290525b215d954d1b5fb91199df | https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/types.py#L120-L140 | train |
Woile/commitizen | commitizen/factory.py | commiter_factory | def commiter_factory(config: dict) -> BaseCommitizen:
"""Return the correct commitizen existing in the registry."""
name: str = config["name"]
try:
_cz = registry[name](config)
except KeyError:
msg_error = (
"The commiter has not been found in the system.\n\n"
f"T... | python | def commiter_factory(config: dict) -> BaseCommitizen:
"""Return the correct commitizen existing in the registry."""
name: str = config["name"]
try:
_cz = registry[name](config)
except KeyError:
msg_error = (
"The commiter has not been found in the system.\n\n"
f"T... | [
"def",
"commiter_factory",
"(",
"config",
":",
"dict",
")",
"->",
"BaseCommitizen",
":",
"name",
":",
"str",
"=",
"config",
"[",
"\"name\"",
"]",
"try",
":",
"_cz",
"=",
"registry",
"[",
"name",
"]",
"(",
"config",
")",
"except",
"KeyError",
":",
"msg_... | Return the correct commitizen existing in the registry. | [
"Return",
"the",
"correct",
"commitizen",
"existing",
"in",
"the",
"registry",
"."
] | bc54b9a4b6ad281620179a1ed417c01addde55f6 | https://github.com/Woile/commitizen/blob/bc54b9a4b6ad281620179a1ed417c01addde55f6/commitizen/factory.py#L8-L21 | train |
Woile/commitizen | commitizen/bump.py | generate_version | def generate_version(
current_version: str, increment: str, prerelease: Optional[str] = None
) -> Version:
"""Based on the given increment a proper semver will be generated.
For now the rules and versioning scheme is based on
python's PEP 0440.
More info: https://www.python.org/dev/peps/pep-0440/
... | python | def generate_version(
current_version: str, increment: str, prerelease: Optional[str] = None
) -> Version:
"""Based on the given increment a proper semver will be generated.
For now the rules and versioning scheme is based on
python's PEP 0440.
More info: https://www.python.org/dev/peps/pep-0440/
... | [
"def",
"generate_version",
"(",
"current_version",
":",
"str",
",",
"increment",
":",
"str",
",",
"prerelease",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Version",
":",
"pre_version",
"=",
"prerelease_generator",
"(",
"current_version",
",",
... | Based on the given increment a proper semver will be generated.
For now the rules and versioning scheme is based on
python's PEP 0440.
More info: https://www.python.org/dev/peps/pep-0440/
Example:
PATCH 1.0.0 -> 1.0.1
MINOR 1.0.0 -> 1.1.0
MAJOR 1.0.0 -> 2.0.0 | [
"Based",
"on",
"the",
"given",
"increment",
"a",
"proper",
"semver",
"will",
"be",
"generated",
"."
] | bc54b9a4b6ad281620179a1ed417c01addde55f6 | https://github.com/Woile/commitizen/blob/bc54b9a4b6ad281620179a1ed417c01addde55f6/commitizen/bump.py#L94-L112 | train |
Woile/commitizen | commitizen/bump.py | update_version_in_files | def update_version_in_files(current_version: str, new_version: str, files: list):
"""Change old version to the new one in every file given.
Note that this version is not the tag formatted one.
So for example, your tag could look like `v1.0.0` while your version in
the package like `1.0.0`.
"""
... | python | def update_version_in_files(current_version: str, new_version: str, files: list):
"""Change old version to the new one in every file given.
Note that this version is not the tag formatted one.
So for example, your tag could look like `v1.0.0` while your version in
the package like `1.0.0`.
"""
... | [
"def",
"update_version_in_files",
"(",
"current_version",
":",
"str",
",",
"new_version",
":",
"str",
",",
"files",
":",
"list",
")",
":",
"for",
"filepath",
"in",
"files",
":",
"# Read in the file",
"with",
"open",
"(",
"filepath",
",",
"\"r\"",
")",
"as",
... | Change old version to the new one in every file given.
Note that this version is not the tag formatted one.
So for example, your tag could look like `v1.0.0` while your version in
the package like `1.0.0`. | [
"Change",
"old",
"version",
"to",
"the",
"new",
"one",
"in",
"every",
"file",
"given",
"."
] | bc54b9a4b6ad281620179a1ed417c01addde55f6 | https://github.com/Woile/commitizen/blob/bc54b9a4b6ad281620179a1ed417c01addde55f6/commitizen/bump.py#L115-L132 | train |
Woile/commitizen | commitizen/bump.py | create_tag | def create_tag(version: Union[Version, str], tag_format: Optional[str] = None):
"""The tag and the software version might be different.
That's why this function exists.
Example:
| tag | version (PEP 0440) |
| --- | ------- |
| v0.9.0 | 0.9.0 |
| ver1.0.0 | 1.0.0 |
| ver1.0.0.a0 | 1.0.... | python | def create_tag(version: Union[Version, str], tag_format: Optional[str] = None):
"""The tag and the software version might be different.
That's why this function exists.
Example:
| tag | version (PEP 0440) |
| --- | ------- |
| v0.9.0 | 0.9.0 |
| ver1.0.0 | 1.0.0 |
| ver1.0.0.a0 | 1.0.... | [
"def",
"create_tag",
"(",
"version",
":",
"Union",
"[",
"Version",
",",
"str",
"]",
",",
"tag_format",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"version",
",",
"str",
")",
":",
"version",
"=",
"Version",
"(",
... | The tag and the software version might be different.
That's why this function exists.
Example:
| tag | version (PEP 0440) |
| --- | ------- |
| v0.9.0 | 0.9.0 |
| ver1.0.0 | 1.0.0 |
| ver1.0.0.a0 | 1.0.0a0 | | [
"The",
"tag",
"and",
"the",
"software",
"version",
"might",
"be",
"different",
"."
] | bc54b9a4b6ad281620179a1ed417c01addde55f6 | https://github.com/Woile/commitizen/blob/bc54b9a4b6ad281620179a1ed417c01addde55f6/commitizen/bump.py#L135-L163 | train |
Woile/commitizen | commitizen/config.py | read_pyproject_conf | def read_pyproject_conf(data: str) -> dict:
"""We expect to have a section in pyproject looking like
```
[tool.commitizen]
name = "cz_conventional_commits"
```
"""
doc = parse(data)
try:
return doc["tool"]["commitizen"]
except exceptions.NonExistentKey:
return {} | python | def read_pyproject_conf(data: str) -> dict:
"""We expect to have a section in pyproject looking like
```
[tool.commitizen]
name = "cz_conventional_commits"
```
"""
doc = parse(data)
try:
return doc["tool"]["commitizen"]
except exceptions.NonExistentKey:
return {} | [
"def",
"read_pyproject_conf",
"(",
"data",
":",
"str",
")",
"->",
"dict",
":",
"doc",
"=",
"parse",
"(",
"data",
")",
"try",
":",
"return",
"doc",
"[",
"\"tool\"",
"]",
"[",
"\"commitizen\"",
"]",
"except",
"exceptions",
".",
"NonExistentKey",
":",
"retu... | We expect to have a section in pyproject looking like
```
[tool.commitizen]
name = "cz_conventional_commits"
``` | [
"We",
"expect",
"to",
"have",
"a",
"section",
"in",
"pyproject",
"looking",
"like"
] | bc54b9a4b6ad281620179a1ed417c01addde55f6 | https://github.com/Woile/commitizen/blob/bc54b9a4b6ad281620179a1ed417c01addde55f6/commitizen/config.py#L39-L51 | train |
Woile/commitizen | commitizen/config.py | read_raw_parser_conf | def read_raw_parser_conf(data: str) -> dict:
"""We expect to have a section like this
```
[commitizen]
name = cz_jira
files = [
"commitizen/__version__.py",
"pyproject.toml"
] # this tab at the end is important
```
"""
config = configparser.ConfigParser(allow_no... | python | def read_raw_parser_conf(data: str) -> dict:
"""We expect to have a section like this
```
[commitizen]
name = cz_jira
files = [
"commitizen/__version__.py",
"pyproject.toml"
] # this tab at the end is important
```
"""
config = configparser.ConfigParser(allow_no... | [
"def",
"read_raw_parser_conf",
"(",
"data",
":",
"str",
")",
"->",
"dict",
":",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"config",
".",
"read_string",
"(",
"data",
")",
"try",
":",
"_data",
":",
"dict",
... | We expect to have a section like this
```
[commitizen]
name = cz_jira
files = [
"commitizen/__version__.py",
"pyproject.toml"
] # this tab at the end is important
``` | [
"We",
"expect",
"to",
"have",
"a",
"section",
"like",
"this"
] | bc54b9a4b6ad281620179a1ed417c01addde55f6 | https://github.com/Woile/commitizen/blob/bc54b9a4b6ad281620179a1ed417c01addde55f6/commitizen/config.py#L54-L78 | train |
Woile/commitizen | commitizen/config.py | set_key | def set_key(key: str, value: str) -> dict:
"""Set or update a key in the conf.
For now only strings are supported.
We use to update the version number.
"""
if not _conf.path:
return {}
if "toml" in _conf.path:
with open(_conf.path, "r") as f:
parser = parse(f.read()... | python | def set_key(key: str, value: str) -> dict:
"""Set or update a key in the conf.
For now only strings are supported.
We use to update the version number.
"""
if not _conf.path:
return {}
if "toml" in _conf.path:
with open(_conf.path, "r") as f:
parser = parse(f.read()... | [
"def",
"set_key",
"(",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"dict",
":",
"if",
"not",
"_conf",
".",
"path",
":",
"return",
"{",
"}",
"if",
"\"toml\"",
"in",
"_conf",
".",
"path",
":",
"with",
"open",
"(",
"_conf",
".",
"path",
... | Set or update a key in the conf.
For now only strings are supported.
We use to update the version number. | [
"Set",
"or",
"update",
"a",
"key",
"in",
"the",
"conf",
"."
] | bc54b9a4b6ad281620179a1ed417c01addde55f6 | https://github.com/Woile/commitizen/blob/bc54b9a4b6ad281620179a1ed417c01addde55f6/commitizen/config.py#L130-L152 | train |
pysathq/pysat | pysat/_fileio.py | FileObject.close | def close(self):
"""
Close a file pointer.
"""
if self.fp:
self.fp.close()
self.fp = None
if self.fp_extra:
self.fp_extra.close()
self.fp_extra = None
self.ctype = None | python | def close(self):
"""
Close a file pointer.
"""
if self.fp:
self.fp.close()
self.fp = None
if self.fp_extra:
self.fp_extra.close()
self.fp_extra = None
self.ctype = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"fp",
":",
"self",
".",
"fp",
".",
"close",
"(",
")",
"self",
".",
"fp",
"=",
"None",
"if",
"self",
".",
"fp_extra",
":",
"self",
".",
"fp_extra",
".",
"close",
"(",
")",
"self",
".",
... | Close a file pointer. | [
"Close",
"a",
"file",
"pointer",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/_fileio.py#L147-L160 | train |
pysathq/pysat | pysat/_fileio.py | FileObject.get_compression_type | def get_compression_type(self, file_name):
"""
Determine compression type for a given file using its extension.
:param file_name: a given file name
:type file_name: str
"""
ext = os.path.splitext(file_name)[1]
if ext == '.gz':
self.ctype... | python | def get_compression_type(self, file_name):
"""
Determine compression type for a given file using its extension.
:param file_name: a given file name
:type file_name: str
"""
ext = os.path.splitext(file_name)[1]
if ext == '.gz':
self.ctype... | [
"def",
"get_compression_type",
"(",
"self",
",",
"file_name",
")",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"[",
"1",
"]",
"if",
"ext",
"==",
"'.gz'",
":",
"self",
".",
"ctype",
"=",
"'gzip'",
"elif",
"ext",
"==",
... | Determine compression type for a given file using its extension.
:param file_name: a given file name
:type file_name: str | [
"Determine",
"compression",
"type",
"for",
"a",
"given",
"file",
"using",
"its",
"extension",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/_fileio.py#L162-L179 | train |
pysathq/pysat | solvers/prepare.py | do | def do(to_install):
"""
Prepare all solvers specified in the command line.
"""
for solver in to_install:
print('preparing {0}'.format(solver))
download_archive(sources[solver])
extract_archive(sources[solver][-1], solver)
adapt_files(solver)
patch_solver(sol... | python | def do(to_install):
"""
Prepare all solvers specified in the command line.
"""
for solver in to_install:
print('preparing {0}'.format(solver))
download_archive(sources[solver])
extract_archive(sources[solver][-1], solver)
adapt_files(solver)
patch_solver(sol... | [
"def",
"do",
"(",
"to_install",
")",
":",
"for",
"solver",
"in",
"to_install",
":",
"print",
"(",
"'preparing {0}'",
".",
"format",
"(",
"solver",
")",
")",
"download_archive",
"(",
"sources",
"[",
"solver",
"]",
")",
"extract_archive",
"(",
"sources",
"["... | Prepare all solvers specified in the command line. | [
"Prepare",
"all",
"solvers",
"specified",
"in",
"the",
"command",
"line",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/solvers/prepare.py#L272-L284 | train |
pysathq/pysat | solvers/prepare.py | adapt_files | def adapt_files(solver):
"""
Rename and remove files whenever necessary.
"""
print("adapting {0}'s files".format(solver))
root = os.path.join('solvers', solver)
for arch in to_extract[solver]:
arch = os.path.join(root, arch)
extract_archive(arch, solver, put_inside=True)
... | python | def adapt_files(solver):
"""
Rename and remove files whenever necessary.
"""
print("adapting {0}'s files".format(solver))
root = os.path.join('solvers', solver)
for arch in to_extract[solver]:
arch = os.path.join(root, arch)
extract_archive(arch, solver, put_inside=True)
... | [
"def",
"adapt_files",
"(",
"solver",
")",
":",
"print",
"(",
"\"adapting {0}'s files\"",
".",
"format",
"(",
"solver",
")",
")",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'solvers'",
",",
"solver",
")",
"for",
"arch",
"in",
"to_extract",
"[",
... | Rename and remove files whenever necessary. | [
"Rename",
"and",
"remove",
"files",
"whenever",
"necessary",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/solvers/prepare.py#L380-L402 | train |
pysathq/pysat | examples/mcsls.py | MCSls._map_extlit | def _map_extlit(self, l):
"""
Map an external variable to an internal one if necessary.
This method is used when new clauses are added to the formula
incrementally, which may result in introducing new variables
clashing with the previously used *clause selectors*... | python | def _map_extlit(self, l):
"""
Map an external variable to an internal one if necessary.
This method is used when new clauses are added to the formula
incrementally, which may result in introducing new variables
clashing with the previously used *clause selectors*... | [
"def",
"_map_extlit",
"(",
"self",
",",
"l",
")",
":",
"v",
"=",
"abs",
"(",
"l",
")",
"if",
"v",
"in",
"self",
".",
"vmap",
".",
"e2i",
":",
"return",
"int",
"(",
"copysign",
"(",
"self",
".",
"vmap",
".",
"e2i",
"[",
"v",
"]",
",",
"l",
"... | Map an external variable to an internal one if necessary.
This method is used when new clauses are added to the formula
incrementally, which may result in introducing new variables
clashing with the previously used *clause selectors*. The method
makes sure no clash occur... | [
"Map",
"an",
"external",
"variable",
"to",
"an",
"internal",
"one",
"if",
"necessary",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/mcsls.py#L409-L439 | train |
pysathq/pysat | examples/hitman.py | Hitman.init | def init(self, bootstrap_with):
"""
This method serves for initializing the hitting set solver with a
given list of sets to hit. Concretely, the hitting set problem is
encoded into partial MaxSAT as outlined above, which is then fed
either to a MaxSAT solver or an... | python | def init(self, bootstrap_with):
"""
This method serves for initializing the hitting set solver with a
given list of sets to hit. Concretely, the hitting set problem is
encoded into partial MaxSAT as outlined above, which is then fed
either to a MaxSAT solver or an... | [
"def",
"init",
"(",
"self",
",",
"bootstrap_with",
")",
":",
"# formula encoding the sets to hit",
"formula",
"=",
"WCNF",
"(",
")",
"# hard clauses",
"for",
"to_hit",
"in",
"bootstrap_with",
":",
"to_hit",
"=",
"list",
"(",
"map",
"(",
"lambda",
"obj",
":",
... | This method serves for initializing the hitting set solver with a
given list of sets to hit. Concretely, the hitting set problem is
encoded into partial MaxSAT as outlined above, which is then fed
either to a MaxSAT solver or an MCS enumerator.
:param bootstrap_with: inp... | [
"This",
"method",
"serves",
"for",
"initializing",
"the",
"hitting",
"set",
"solver",
"with",
"a",
"given",
"list",
"of",
"sets",
"to",
"hit",
".",
"Concretely",
"the",
"hitting",
"set",
"problem",
"is",
"encoded",
"into",
"partial",
"MaxSAT",
"as",
"outline... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/hitman.py#L254-L285 | train |
pysathq/pysat | examples/hitman.py | Hitman.get | def get(self):
"""
This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain.
:rtype: list(ob... | python | def get(self):
"""
This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain.
:rtype: list(ob... | [
"def",
"get",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"oracle",
".",
"compute",
"(",
")",
"if",
"model",
":",
"if",
"self",
".",
"htype",
"==",
"'rc2'",
":",
"# extracting a hitting set",
"self",
".",
"hset",
"=",
"filter",
"(",
"lambda",
"... | This method computes and returns a hitting set. The hitting set is
obtained using the underlying oracle operating the MaxSAT problem
formulation. The computed solution is mapped back to objects of the
problem domain.
:rtype: list(obj) | [
"This",
"method",
"computes",
"and",
"returns",
"a",
"hitting",
"set",
".",
"The",
"hitting",
"set",
"is",
"obtained",
"using",
"the",
"underlying",
"oracle",
"operating",
"the",
"MaxSAT",
"problem",
"formulation",
".",
"The",
"computed",
"solution",
"is",
"ma... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/hitman.py#L296-L315 | train |
pysathq/pysat | examples/hitman.py | Hitman.hit | def hit(self, to_hit):
"""
This method adds a new set to hit to the hitting set solver. This
is done by translating the input iterable of objects into a list of
Boolean variables in the MaxSAT problem formulation.
:param to_hit: a new set to hit
:type... | python | def hit(self, to_hit):
"""
This method adds a new set to hit to the hitting set solver. This
is done by translating the input iterable of objects into a list of
Boolean variables in the MaxSAT problem formulation.
:param to_hit: a new set to hit
:type... | [
"def",
"hit",
"(",
"self",
",",
"to_hit",
")",
":",
"# translating objects to variables",
"to_hit",
"=",
"list",
"(",
"map",
"(",
"lambda",
"obj",
":",
"self",
".",
"idpool",
".",
"id",
"(",
"obj",
")",
",",
"to_hit",
")",
")",
"# a soft clause should be a... | This method adds a new set to hit to the hitting set solver. This
is done by translating the input iterable of objects into a list of
Boolean variables in the MaxSAT problem formulation.
:param to_hit: a new set to hit
:type to_hit: iterable(obj) | [
"This",
"method",
"adds",
"a",
"new",
"set",
"to",
"hit",
"to",
"the",
"hitting",
"set",
"solver",
".",
"This",
"is",
"done",
"by",
"translating",
"the",
"input",
"iterable",
"of",
"objects",
"into",
"a",
"list",
"of",
"Boolean",
"variables",
"in",
"the"... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/hitman.py#L317-L338 | train |
pysathq/pysat | examples/hitman.py | Hitman.block | def block(self, to_block):
"""
The method serves for imposing a constraint forbidding the hitting
set solver to compute a given hitting set. Each set to block is
encoded as a hard clause in the MaxSAT problem formulation, which
is then added to the underlying orac... | python | def block(self, to_block):
"""
The method serves for imposing a constraint forbidding the hitting
set solver to compute a given hitting set. Each set to block is
encoded as a hard clause in the MaxSAT problem formulation, which
is then added to the underlying orac... | [
"def",
"block",
"(",
"self",
",",
"to_block",
")",
":",
"# translating objects to variables",
"to_block",
"=",
"list",
"(",
"map",
"(",
"lambda",
"obj",
":",
"self",
".",
"idpool",
".",
"id",
"(",
"obj",
")",
",",
"to_block",
")",
")",
"# a soft clause sho... | The method serves for imposing a constraint forbidding the hitting
set solver to compute a given hitting set. Each set to block is
encoded as a hard clause in the MaxSAT problem formulation, which
is then added to the underlying oracle.
:param to_block: a set to block
... | [
"The",
"method",
"serves",
"for",
"imposing",
"a",
"constraint",
"forbidding",
"the",
"hitting",
"set",
"solver",
"to",
"compute",
"a",
"given",
"hitting",
"set",
".",
"Each",
"set",
"to",
"block",
"is",
"encoded",
"as",
"a",
"hard",
"clause",
"in",
"the",... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/hitman.py#L340-L362 | train |
pysathq/pysat | examples/musx.py | MUSX._compute | def _compute(self, approx):
"""
Deletion-based MUS extraction. Given an over-approximation of an
MUS, i.e. an unsatisfiable core previously returned by a SAT
oracle, the method represents a loop, which at each iteration
removes a clause from the core and checks wh... | python | def _compute(self, approx):
"""
Deletion-based MUS extraction. Given an over-approximation of an
MUS, i.e. an unsatisfiable core previously returned by a SAT
oracle, the method represents a loop, which at each iteration
removes a clause from the core and checks wh... | [
"def",
"_compute",
"(",
"self",
",",
"approx",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"approx",
")",
":",
"to_test",
"=",
"approx",
"[",
":",
"i",
"]",
"+",
"approx",
"[",
"(",
"i",
"+",
"1",
")",
":",
"]",
"sel",
",",
"cli... | Deletion-based MUS extraction. Given an over-approximation of an
MUS, i.e. an unsatisfiable core previously returned by a SAT
oracle, the method represents a loop, which at each iteration
removes a clause from the core and checks whether the remaining
clauses of the appro... | [
"Deletion",
"-",
"based",
"MUS",
"extraction",
".",
"Given",
"an",
"over",
"-",
"approximation",
"of",
"an",
"MUS",
"i",
".",
"e",
".",
"an",
"unsatisfiable",
"core",
"previously",
"returned",
"by",
"a",
"SAT",
"oracle",
"the",
"method",
"represents",
"a",... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/musx.py#L204-L250 | train |
pysathq/pysat | setup.py | build.run | def run(self):
"""
Download, patch and compile SAT solvers before building.
"""
# download and compile solvers
prepare.do(to_install)
# now, do standard build
distutils.command.build.build.run(self) | python | def run(self):
"""
Download, patch and compile SAT solvers before building.
"""
# download and compile solvers
prepare.do(to_install)
# now, do standard build
distutils.command.build.build.run(self) | [
"def",
"run",
"(",
"self",
")",
":",
"# download and compile solvers",
"prepare",
".",
"do",
"(",
"to_install",
")",
"# now, do standard build",
"distutils",
".",
"command",
".",
"build",
".",
"build",
".",
"run",
"(",
"self",
")"
] | Download, patch and compile SAT solvers before building. | [
"Download",
"patch",
"and",
"compile",
"SAT",
"solvers",
"before",
"building",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/setup.py#L61-L70 | train |
pysathq/pysat | pysat/solvers.py | Solver.add_clause | def add_clause(self, clause, no_return=True):
"""
This method is used to add a single clause to the solver. An
optional argument ``no_return`` controls whether or not to check
the formula's satisfiability after adding the new clause.
:param clause: an iterable ov... | python | def add_clause(self, clause, no_return=True):
"""
This method is used to add a single clause to the solver. An
optional argument ``no_return`` controls whether or not to check
the formula's satisfiability after adding the new clause.
:param clause: an iterable ov... | [
"def",
"add_clause",
"(",
"self",
",",
"clause",
",",
"no_return",
"=",
"True",
")",
":",
"if",
"self",
".",
"solver",
":",
"res",
"=",
"self",
".",
"solver",
".",
"add_clause",
"(",
"clause",
",",
"no_return",
")",
"if",
"not",
"no_return",
":",
"re... | This method is used to add a single clause to the solver. An
optional argument ``no_return`` controls whether or not to check
the formula's satisfiability after adding the new clause.
:param clause: an iterable over literals.
:param no_return: check solver's internal for... | [
"This",
"method",
"is",
"used",
"to",
"add",
"a",
"single",
"clause",
"to",
"the",
"solver",
".",
"An",
"optional",
"argument",
"no_return",
"controls",
"whether",
"or",
"not",
"to",
"check",
"the",
"formula",
"s",
"satisfiability",
"after",
"adding",
"the",... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L825-L856 | train |
pysathq/pysat | pysat/solvers.py | Solver.append_formula | def append_formula(self, formula, no_return=True):
"""
This method can be used to add a given list of clauses into the
solver.
:param formula: a list of clauses.
:param no_return: check solver's internal formula and return the
result, if set to ``... | python | def append_formula(self, formula, no_return=True):
"""
This method can be used to add a given list of clauses into the
solver.
:param formula: a list of clauses.
:param no_return: check solver's internal formula and return the
result, if set to ``... | [
"def",
"append_formula",
"(",
"self",
",",
"formula",
",",
"no_return",
"=",
"True",
")",
":",
"if",
"self",
".",
"solver",
":",
"res",
"=",
"self",
".",
"solver",
".",
"append_formula",
"(",
"formula",
",",
"no_return",
")",
"if",
"not",
"no_return",
... | This method can be used to add a given list of clauses into the
solver.
:param formula: a list of clauses.
:param no_return: check solver's internal formula and return the
result, if set to ``False``.
:type formula: iterable(iterable(int))
:t... | [
"This",
"method",
"can",
"be",
"used",
"to",
"add",
"a",
"given",
"list",
"of",
"clauses",
"into",
"the",
"solver",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L896-L924 | train |
pysathq/pysat | pysat/solvers.py | Glucose4.enum_models | def enum_models(self, assumptions=[]):
"""
Iterate over models of the internal formula.
"""
if self.glucose:
done = False
while not done:
if self.use_timer:
start_time = time.clock()
self.status = pysolvers... | python | def enum_models(self, assumptions=[]):
"""
Iterate over models of the internal formula.
"""
if self.glucose:
done = False
while not done:
if self.use_timer:
start_time = time.clock()
self.status = pysolvers... | [
"def",
"enum_models",
"(",
"self",
",",
"assumptions",
"=",
"[",
"]",
")",
":",
"if",
"self",
".",
"glucose",
":",
"done",
"=",
"False",
"while",
"not",
"done",
":",
"if",
"self",
".",
"use_timer",
":",
"start_time",
"=",
"time",
".",
"clock",
"(",
... | Iterate over models of the internal formula. | [
"Iterate",
"over",
"models",
"of",
"the",
"internal",
"formula",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1453-L1476 | train |
pysathq/pysat | pysat/solvers.py | MapleChrono.propagate | def propagate(self, assumptions=[], phase_saving=0):
"""
Propagate a given set of assumption literals.
"""
if self.maplesat:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
def_sigint_handler = signal... | python | def propagate(self, assumptions=[], phase_saving=0):
"""
Propagate a given set of assumption literals.
"""
if self.maplesat:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
def_sigint_handler = signal... | [
"def",
"propagate",
"(",
"self",
",",
"assumptions",
"=",
"[",
"]",
",",
"phase_saving",
"=",
"0",
")",
":",
"if",
"self",
".",
"maplesat",
":",
"if",
"self",
".",
"use_timer",
":",
"start_time",
"=",
"time",
".",
"clock",
"(",
")",
"# saving default S... | Propagate a given set of assumption literals. | [
"Propagate",
"a",
"given",
"set",
"of",
"assumption",
"literals",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1892-L1913 | train |
pysathq/pysat | pysat/solvers.py | MapleChrono.get_proof | def get_proof(self):
"""
Get a proof produced while deciding the formula.
"""
if self.maplesat and self.prfile:
self.prfile.seek(0)
return [line.rstrip() for line in self.prfile.readlines()] | python | def get_proof(self):
"""
Get a proof produced while deciding the formula.
"""
if self.maplesat and self.prfile:
self.prfile.seek(0)
return [line.rstrip() for line in self.prfile.readlines()] | [
"def",
"get_proof",
"(",
"self",
")",
":",
"if",
"self",
".",
"maplesat",
"and",
"self",
".",
"prfile",
":",
"self",
".",
"prfile",
".",
"seek",
"(",
"0",
")",
"return",
"[",
"line",
".",
"rstrip",
"(",
")",
"for",
"line",
"in",
"self",
".",
"prf... | Get a proof produced while deciding the formula. | [
"Get",
"a",
"proof",
"produced",
"while",
"deciding",
"the",
"formula",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1949-L1956 | train |
pysathq/pysat | pysat/solvers.py | Minicard.add_atmost | def add_atmost(self, lits, k, no_return=True):
"""
Add a new atmost constraint to solver's internal formula.
"""
if self.minicard:
res = pysolvers.minicard_add_am(self.minicard, lits, k)
if res == False:
self.status = False
if no... | python | def add_atmost(self, lits, k, no_return=True):
"""
Add a new atmost constraint to solver's internal formula.
"""
if self.minicard:
res = pysolvers.minicard_add_am(self.minicard, lits, k)
if res == False:
self.status = False
if no... | [
"def",
"add_atmost",
"(",
"self",
",",
"lits",
",",
"k",
",",
"no_return",
"=",
"True",
")",
":",
"if",
"self",
".",
"minicard",
":",
"res",
"=",
"pysolvers",
".",
"minicard_add_am",
"(",
"self",
".",
"minicard",
",",
"lits",
",",
"k",
")",
"if",
"... | Add a new atmost constraint to solver's internal formula. | [
"Add",
"a",
"new",
"atmost",
"constraint",
"to",
"solver",
"s",
"internal",
"formula",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L2885-L2897 | train |
pysathq/pysat | pysat/formula.py | IDPool.id | def id(self, obj):
"""
The method is to be used to assign an integer variable ID for a
given new object. If the object already has an ID, no new ID is
created and the old one is returned instead.
An object can be anything. In some cases it is convenient to use
... | python | def id(self, obj):
"""
The method is to be used to assign an integer variable ID for a
given new object. If the object already has an ID, no new ID is
created and the old one is returned instead.
An object can be anything. In some cases it is convenient to use
... | [
"def",
"id",
"(",
"self",
",",
"obj",
")",
":",
"vid",
"=",
"self",
".",
"obj2id",
"[",
"obj",
"]",
"if",
"vid",
"not",
"in",
"self",
".",
"id2obj",
":",
"self",
".",
"id2obj",
"[",
"vid",
"]",
"=",
"obj",
"return",
"vid"
] | The method is to be used to assign an integer variable ID for a
given new object. If the object already has an ID, no new ID is
created and the old one is returned instead.
An object can be anything. In some cases it is convenient to use
string variable names.
... | [
"The",
"method",
"is",
"to",
"be",
"used",
"to",
"assign",
"an",
"integer",
"variable",
"ID",
"for",
"a",
"given",
"new",
"object",
".",
"If",
"the",
"object",
"already",
"has",
"an",
"ID",
"no",
"new",
"ID",
"is",
"created",
"and",
"the",
"old",
"on... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L264-L311 | train |
pysathq/pysat | pysat/formula.py | IDPool._next | def _next(self):
"""
Get next variable ID. Skip occupied intervals if any.
"""
self.top += 1
while self._occupied and self.top >= self._occupied[0][0]:
if self.top <= self._occupied[0][1]:
self.top = self._occupied[0][1] + 1
self._oc... | python | def _next(self):
"""
Get next variable ID. Skip occupied intervals if any.
"""
self.top += 1
while self._occupied and self.top >= self._occupied[0][0]:
if self.top <= self._occupied[0][1]:
self.top = self._occupied[0][1] + 1
self._oc... | [
"def",
"_next",
"(",
"self",
")",
":",
"self",
".",
"top",
"+=",
"1",
"while",
"self",
".",
"_occupied",
"and",
"self",
".",
"top",
">=",
"self",
".",
"_occupied",
"[",
"0",
"]",
"[",
"0",
"]",
":",
"if",
"self",
".",
"top",
"<=",
"self",
".",
... | Get next variable ID. Skip occupied intervals if any. | [
"Get",
"next",
"variable",
"ID",
".",
"Skip",
"occupied",
"intervals",
"if",
"any",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L351-L364 | train |
pysathq/pysat | pysat/formula.py | CNF.from_file | def from_file(self, fname, comment_lead=['c'], compressed_with='use_ext'):
"""
Read a CNF formula from a file in the DIMACS format. A file name is
expected as an argument. A default argument is ``comment_lead`` for
parsing comment lines. A given file can be compressed by eith... | python | def from_file(self, fname, comment_lead=['c'], compressed_with='use_ext'):
"""
Read a CNF formula from a file in the DIMACS format. A file name is
expected as an argument. A default argument is ``comment_lead`` for
parsing comment lines. A given file can be compressed by eith... | [
"def",
"from_file",
"(",
"self",
",",
"fname",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
",",
"compressed_with",
"=",
"'use_ext'",
")",
":",
"with",
"FileObject",
"(",
"fname",
",",
"mode",
"=",
"'r'",
",",
"compression",
"=",
"compressed_with",
")",
"a... | Read a CNF formula from a file in the DIMACS format. A file name is
expected as an argument. A default argument is ``comment_lead`` for
parsing comment lines. A given file can be compressed by either
gzip, bzip2, or lzma.
:param fname: name of a file to parse.
... | [
"Read",
"a",
"CNF",
"formula",
"from",
"a",
"file",
"in",
"the",
"DIMACS",
"format",
".",
"A",
"file",
"name",
"is",
"expected",
"as",
"an",
"argument",
".",
"A",
"default",
"argument",
"is",
"comment_lead",
"for",
"parsing",
"comment",
"lines",
".",
"A"... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L409-L443 | train |
pysathq/pysat | pysat/formula.py | CNF.from_fp | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a CNF formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:p... | python | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a CNF formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:p... | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"clauses",
"=",
"[",
"]",
"self",
".",
"comments",
"=",
"[",
"]",
"comment_lead",
"=",
"tuple",
"(",
... | Read a CNF formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:param file_pointer: a file pointer to read the formula from.
:para... | [
"Read",
"a",
"CNF",
"formula",
"from",
"a",
"file",
"pointer",
".",
"A",
"file",
"pointer",
"should",
"be",
"specified",
"as",
"an",
"argument",
".",
"The",
"only",
"default",
"argument",
"is",
"comment_lead",
"which",
"can",
"be",
"used",
"for",
"parsing"... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L445-L484 | train |
pysathq/pysat | pysat/formula.py | CNF.from_clauses | def from_clauses(self, clauses):
"""
This methods copies a list of clauses into a CNF object.
:param clauses: a list of clauses.
:type clauses: list(list(int))
Example:
.. code-block:: python
>>> from pysat.formula import CNF
... | python | def from_clauses(self, clauses):
"""
This methods copies a list of clauses into a CNF object.
:param clauses: a list of clauses.
:type clauses: list(list(int))
Example:
.. code-block:: python
>>> from pysat.formula import CNF
... | [
"def",
"from_clauses",
"(",
"self",
",",
"clauses",
")",
":",
"self",
".",
"clauses",
"=",
"copy",
".",
"deepcopy",
"(",
"clauses",
")",
"for",
"cl",
"in",
"self",
".",
"clauses",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")"... | This methods copies a list of clauses into a CNF object.
:param clauses: a list of clauses.
:type clauses: list(list(int))
Example:
.. code-block:: python
>>> from pysat.formula import CNF
>>> cnf = CNF(from_clauses=[[-1, 2], [1, -2], [... | [
"This",
"methods",
"copies",
"a",
"list",
"of",
"clauses",
"into",
"a",
"CNF",
"object",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L518-L540 | train |
pysathq/pysat | pysat/formula.py | CNF.to_fp | def to_fp(self, file_pointer, comments=None):
"""
The method can be used to save a CNF formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
... | python | def to_fp(self, file_pointer, comments=None):
"""
The method can be used to save a CNF formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
... | [
"def",
"to_fp",
"(",
"self",
",",
"file_pointer",
",",
"comments",
"=",
"None",
")",
":",
"# saving formula's internal comments",
"for",
"c",
"in",
"self",
".",
"comments",
":",
"print",
"(",
"c",
",",
"file",
"=",
"file_pointer",
")",
"# saving externally spe... | The method can be used to save a CNF formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
:param fname: a file name where to store the formula.
:par... | [
"The",
"method",
"can",
"be",
"used",
"to",
"save",
"a",
"CNF",
"formula",
"into",
"a",
"file",
"pointer",
".",
"The",
"file",
"pointer",
"is",
"expected",
"as",
"an",
"argument",
".",
"Additionally",
"supplementary",
"comment",
"lines",
"can",
"be",
"spec... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L606-L643 | train |
pysathq/pysat | pysat/formula.py | CNF.append | def append(self, clause):
"""
Add one more clause to CNF formula. This method additionally
updates the number of variables, i.e. variable ``self.nv``, used in
the formula.
:param clause: a new clause to add.
:type clause: list(int)
.. cod... | python | def append(self, clause):
"""
Add one more clause to CNF formula. This method additionally
updates the number of variables, i.e. variable ``self.nv``, used in
the formula.
:param clause: a new clause to add.
:type clause: list(int)
.. cod... | [
"def",
"append",
"(",
"self",
",",
"clause",
")",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"clause",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"self",
".",
"clauses",
".",
"append",
"(",
"clause"... | Add one more clause to CNF formula. This method additionally
updates the number of variables, i.e. variable ``self.nv``, used in
the formula.
:param clause: a new clause to add.
:type clause: list(int)
.. code-block:: python
>>> from pysat.f... | [
"Add",
"one",
"more",
"clause",
"to",
"CNF",
"formula",
".",
"This",
"method",
"additionally",
"updates",
"the",
"number",
"of",
"variables",
"i",
".",
"e",
".",
"variable",
"self",
".",
"nv",
"used",
"in",
"the",
"formula",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L645-L664 | train |
pysathq/pysat | pysat/formula.py | WCNF.from_fp | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a WCNF formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:... | python | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a WCNF formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:... | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"hard",
"=",
"[",
"]",
"self",
".",
"soft",
"=",
"[",
"]",
"self",
".",
"wght",
"=",
"[",
"]",
... | Read a WCNF formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:param file_pointer: a file pointer to read the formula from.
:par... | [
"Read",
"a",
"WCNF",
"formula",
"from",
"a",
"file",
"pointer",
".",
"A",
"file",
"pointer",
"should",
"be",
"specified",
"as",
"an",
"argument",
".",
"The",
"only",
"default",
"argument",
"is",
"comment_lead",
"which",
"can",
"be",
"used",
"for",
"parsing... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L863-L912 | train |
pysathq/pysat | pysat/formula.py | WCNF.to_fp | def to_fp(self, file_pointer, comments=None):
"""
The method can be used to save a WCNF formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
... | python | def to_fp(self, file_pointer, comments=None):
"""
The method can be used to save a WCNF formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
... | [
"def",
"to_fp",
"(",
"self",
",",
"file_pointer",
",",
"comments",
"=",
"None",
")",
":",
"# saving formula's internal comments",
"for",
"c",
"in",
"self",
".",
"comments",
":",
"print",
"(",
"c",
",",
"file",
"=",
"file_pointer",
")",
"# saving externally spe... | The method can be used to save a WCNF formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
:param fname: a file name where to store the formula.
:pa... | [
"The",
"method",
"can",
"be",
"used",
"to",
"save",
"a",
"WCNF",
"formula",
"into",
"a",
"file",
"pointer",
".",
"The",
"file",
"pointer",
"is",
"expected",
"as",
"an",
"argument",
".",
"Additionally",
"supplementary",
"comment",
"lines",
"can",
"be",
"spe... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1024-L1066 | train |
pysathq/pysat | pysat/formula.py | WCNF.append | def append(self, clause, weight=None):
"""
Add one more clause to WCNF formula. This method additionally
updates the number of variables, i.e. variable ``self.nv``, used in
the formula.
The clause can be hard or soft depending on the ``weight``
argume... | python | def append(self, clause, weight=None):
"""
Add one more clause to WCNF formula. This method additionally
updates the number of variables, i.e. variable ``self.nv``, used in
the formula.
The clause can be hard or soft depending on the ``weight``
argume... | [
"def",
"append",
"(",
"self",
",",
"clause",
",",
"weight",
"=",
"None",
")",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"clause",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"if",
"weight",
":",
"... | Add one more clause to WCNF formula. This method additionally
updates the number of variables, i.e. variable ``self.nv``, used in
the formula.
The clause can be hard or soft depending on the ``weight``
argument. If no weight is set, the clause is considered to be hard.
... | [
"Add",
"one",
"more",
"clause",
"to",
"WCNF",
"formula",
".",
"This",
"method",
"additionally",
"updates",
"the",
"number",
"of",
"variables",
"i",
".",
"e",
".",
"variable",
"self",
".",
"nv",
"used",
"in",
"the",
"formula",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1068-L1104 | train |
pysathq/pysat | pysat/formula.py | CNFPlus.from_fp | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a CNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:... | python | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a CNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:... | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"clauses",
"=",
"[",
"]",
"self",
".",
"atmosts",
"=",
"[",
"]",
"self",
".",
"comments",
"=",
"[",... | Read a CNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:param file_pointer: a file pointer to read the formula from.
:par... | [
"Read",
"a",
"CNF",
"+",
"formula",
"from",
"a",
"file",
"pointer",
".",
"A",
"file",
"pointer",
"should",
"be",
"specified",
"as",
"an",
"argument",
".",
"The",
"only",
"default",
"argument",
"is",
"comment_lead",
"which",
"can",
"be",
"used",
"for",
"p... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1239-L1291 | train |
pysathq/pysat | pysat/formula.py | CNFPlus.to_fp | def to_fp(self, file_pointer, comments=None):
"""
The method can be used to save a CNF+ formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
... | python | def to_fp(self, file_pointer, comments=None):
"""
The method can be used to save a CNF+ formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
... | [
"def",
"to_fp",
"(",
"self",
",",
"file_pointer",
",",
"comments",
"=",
"None",
")",
":",
"# saving formula's internal comments",
"for",
"c",
"in",
"self",
".",
"comments",
":",
"print",
"(",
"c",
",",
"file",
"=",
"file_pointer",
")",
"# saving externally spe... | The method can be used to save a CNF+ formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
:param fname: a file name where to store the formula.
:pa... | [
"The",
"method",
"can",
"be",
"used",
"to",
"save",
"a",
"CNF",
"+",
"formula",
"into",
"a",
"file",
"pointer",
".",
"The",
"file",
"pointer",
"is",
"expected",
"as",
"an",
"argument",
".",
"Additionally",
"supplementary",
"comment",
"lines",
"can",
"be",
... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1293-L1335 | train |
pysathq/pysat | pysat/formula.py | CNFPlus.append | def append(self, clause, is_atmost=False):
"""
Add a single clause or a single AtMostK constraint to CNF+ formula.
This method additionally updates the number of variables, i.e.
variable ``self.nv``, used in the formula.
If the clause is an AtMostK constraint, th... | python | def append(self, clause, is_atmost=False):
"""
Add a single clause or a single AtMostK constraint to CNF+ formula.
This method additionally updates the number of variables, i.e.
variable ``self.nv``, used in the formula.
If the clause is an AtMostK constraint, th... | [
"def",
"append",
"(",
"self",
",",
"clause",
",",
"is_atmost",
"=",
"False",
")",
":",
"if",
"not",
"is_atmost",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"clause",
"]",
"+",
"[",
"self",
".",
"nv",
... | Add a single clause or a single AtMostK constraint to CNF+ formula.
This method additionally updates the number of variables, i.e.
variable ``self.nv``, used in the formula.
If the clause is an AtMostK constraint, this should be set with the
use of the additional default... | [
"Add",
"a",
"single",
"clause",
"or",
"a",
"single",
"AtMostK",
"constraint",
"to",
"CNF",
"+",
"formula",
".",
"This",
"method",
"additionally",
"updates",
"the",
"number",
"of",
"variables",
"i",
".",
"e",
".",
"variable",
"self",
".",
"nv",
"used",
"i... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1337-L1370 | train |
pysathq/pysat | pysat/formula.py | WCNFPlus.from_fp | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a WCNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
... | python | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a WCNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
... | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"hard",
"=",
"[",
"]",
"self",
".",
"atms",
"=",
"[",
"]",
"self",
".",
"soft",
"=",
"[",
"]",
... | Read a WCNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:param file_pointer: a file pointer to read the formula from.
:pa... | [
"Read",
"a",
"WCNF",
"+",
"formula",
"from",
"a",
"file",
"pointer",
".",
"A",
"file",
"pointer",
"should",
"be",
"specified",
"as",
"an",
"argument",
".",
"The",
"only",
"default",
"argument",
"is",
"comment_lead",
"which",
"can",
"be",
"used",
"for",
"... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1438-L1500 | train |
pysathq/pysat | pysat/formula.py | WCNFPlus.append | def append(self, clause, weight=None, is_atmost=False):
"""
Add a single clause or a single AtMostK constraint to WCNF+
formula. This method additionally updates the number of variables,
i.e. variable ``self.nv``, used in the formula.
If the clause is an AtMostK... | python | def append(self, clause, weight=None, is_atmost=False):
"""
Add a single clause or a single AtMostK constraint to WCNF+
formula. This method additionally updates the number of variables,
i.e. variable ``self.nv``, used in the formula.
If the clause is an AtMostK... | [
"def",
"append",
"(",
"self",
",",
"clause",
",",
"weight",
"=",
"None",
",",
"is_atmost",
"=",
"False",
")",
":",
"if",
"not",
"is_atmost",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"clause",
"]",
"+... | Add a single clause or a single AtMostK constraint to WCNF+
formula. This method additionally updates the number of variables,
i.e. variable ``self.nv``, used in the formula.
If the clause is an AtMostK constraint, this should be set with the
use of the additional defau... | [
"Add",
"a",
"single",
"clause",
"or",
"a",
"single",
"AtMostK",
"constraint",
"to",
"WCNF",
"+",
"formula",
".",
"This",
"method",
"additionally",
"updates",
"the",
"number",
"of",
"variables",
"i",
".",
"e",
".",
"variable",
"self",
".",
"nv",
"used",
"... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1552-L1602 | train |
pysathq/pysat | examples/fm.py | FM.delete | def delete(self):
"""
Explicit destructor of the internal SAT oracle.
"""
if self.oracle:
self.time += self.oracle.time_accum() # keep SAT solving time
self.oracle.delete()
self.oracle = None | python | def delete(self):
"""
Explicit destructor of the internal SAT oracle.
"""
if self.oracle:
self.time += self.oracle.time_accum() # keep SAT solving time
self.oracle.delete()
self.oracle = None | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"oracle",
":",
"self",
".",
"time",
"+=",
"self",
".",
"oracle",
".",
"time_accum",
"(",
")",
"# keep SAT solving time",
"self",
".",
"oracle",
".",
"delete",
"(",
")",
"self",
".",
"oracle",
... | Explicit destructor of the internal SAT oracle. | [
"Explicit",
"destructor",
"of",
"the",
"internal",
"SAT",
"oracle",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/fm.py#L216-L225 | train |
pysathq/pysat | examples/fm.py | FM.split_core | def split_core(self, minw):
"""
Split clauses in the core whenever necessary.
Given a list of soft clauses in an unsatisfiable core, the method
is used for splitting clauses whose weights are greater than the
minimum weight of the core, i.e. the ``minw`` value co... | python | def split_core(self, minw):
"""
Split clauses in the core whenever necessary.
Given a list of soft clauses in an unsatisfiable core, the method
is used for splitting clauses whose weights are greater than the
minimum weight of the core, i.e. the ``minw`` value co... | [
"def",
"split_core",
"(",
"self",
",",
"minw",
")",
":",
"for",
"clid",
"in",
"self",
".",
"core",
":",
"sel",
"=",
"self",
".",
"sels",
"[",
"clid",
"]",
"if",
"self",
".",
"wght",
"[",
"clid",
"]",
">",
"minw",
":",
"self",
".",
"topv",
"+=",... | Split clauses in the core whenever necessary.
Given a list of soft clauses in an unsatisfiable core, the method
is used for splitting clauses whose weights are greater than the
minimum weight of the core, i.e. the ``minw`` value computed in
:func:`treat_core`. Each claus... | [
"Split",
"clauses",
"in",
"the",
"core",
"whenever",
"necessary",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/fm.py#L325-L363 | train |
pysathq/pysat | examples/fm.py | FM.relax_core | def relax_core(self):
"""
Relax and bound the core.
After unsatisfiable core splitting, this method is called. If the
core contains only one clause, i.e. this clause cannot be satisfied
together with the hard clauses of the formula, the formula gets
a... | python | def relax_core(self):
"""
Relax and bound the core.
After unsatisfiable core splitting, this method is called. If the
core contains only one clause, i.e. this clause cannot be satisfied
together with the hard clauses of the formula, the formula gets
a... | [
"def",
"relax_core",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"core",
")",
">",
"1",
":",
"# relaxing",
"rels",
"=",
"[",
"]",
"for",
"clid",
"in",
"self",
".",
"core",
":",
"self",
".",
"topv",
"+=",
"1",
"rels",
".",
"append",
"(... | Relax and bound the core.
After unsatisfiable core splitting, this method is called. If the
core contains only one clause, i.e. this clause cannot be satisfied
together with the hard clauses of the formula, the formula gets
augmented with the negation of the clause (see
... | [
"Relax",
"and",
"bound",
"the",
"core",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/fm.py#L365-L408 | train |
pysathq/pysat | examples/lsu.py | parse_options | def parse_options():
"""
Parses command-line options.
"""
try:
opts, args = getopt.getopt(sys.argv[1:], 'hms:v', ['help', 'model', 'solver=', 'verbose'])
except getopt.GetoptError as err:
sys.stderr.write(str(err).capitalize())
print_usage()
sys.exit(1)
solv... | python | def parse_options():
"""
Parses command-line options.
"""
try:
opts, args = getopt.getopt(sys.argv[1:], 'hms:v', ['help', 'model', 'solver=', 'verbose'])
except getopt.GetoptError as err:
sys.stderr.write(str(err).capitalize())
print_usage()
sys.exit(1)
solv... | [
"def",
"parse_options",
"(",
")",
":",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"'hms:v'",
",",
"[",
"'help'",
",",
"'model'",
",",
"'solver='",
",",
"'verbose'",
"]",
")",
"... | Parses command-line options. | [
"Parses",
"command",
"-",
"line",
"options",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lsu.py#L308-L337 | train |
pysathq/pysat | examples/lsu.py | parse_formula | def parse_formula(fml_file):
"""
Parse and return MaxSAT formula.
"""
if re.search('\.wcnf(\.(gz|bz2|lzma|xz))?$', fml_file):
fml = WCNF(from_file=fml_file)
else: # expecting '*.cnf'
fml = CNF(from_file=fml_file).weighted()
return fml | python | def parse_formula(fml_file):
"""
Parse and return MaxSAT formula.
"""
if re.search('\.wcnf(\.(gz|bz2|lzma|xz))?$', fml_file):
fml = WCNF(from_file=fml_file)
else: # expecting '*.cnf'
fml = CNF(from_file=fml_file).weighted()
return fml | [
"def",
"parse_formula",
"(",
"fml_file",
")",
":",
"if",
"re",
".",
"search",
"(",
"'\\.wcnf(\\.(gz|bz2|lzma|xz))?$'",
",",
"fml_file",
")",
":",
"fml",
"=",
"WCNF",
"(",
"from_file",
"=",
"fml_file",
")",
"else",
":",
"# expecting '*.cnf'",
"fml",
"=",
"CNF... | Parse and return MaxSAT formula. | [
"Parse",
"and",
"return",
"MaxSAT",
"formula",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lsu.py#L358-L368 | train |
pysathq/pysat | examples/lsu.py | LSU._init | def _init(self, formula):
"""
SAT oracle initialization. The method creates a new SAT oracle and
feeds it with the formula's hard clauses. Afterwards, all soft
clauses of the formula are augmented with selector literals and
also added to the solver. The list of al... | python | def _init(self, formula):
"""
SAT oracle initialization. The method creates a new SAT oracle and
feeds it with the formula's hard clauses. Afterwards, all soft
clauses of the formula are augmented with selector literals and
also added to the solver. The list of al... | [
"def",
"_init",
"(",
"self",
",",
"formula",
")",
":",
"self",
".",
"oracle",
"=",
"Solver",
"(",
"name",
"=",
"self",
".",
"solver",
",",
"bootstrap_with",
"=",
"formula",
".",
"hard",
",",
"incr",
"=",
"True",
",",
"use_timer",
"=",
"True",
")",
... | SAT oracle initialization. The method creates a new SAT oracle and
feeds it with the formula's hard clauses. Afterwards, all soft
clauses of the formula are augmented with selector literals and
also added to the solver. The list of all introduced selectors is
stored in va... | [
"SAT",
"oracle",
"initialization",
".",
"The",
"method",
"creates",
"a",
"new",
"SAT",
"oracle",
"and",
"feeds",
"it",
"with",
"the",
"formula",
"s",
"hard",
"clauses",
".",
"Afterwards",
"all",
"soft",
"clauses",
"of",
"the",
"formula",
"are",
"augmented",
... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lsu.py#L139-L164 | train |
pysathq/pysat | examples/lsu.py | LSU._get_model_cost | def _get_model_cost(self, formula, model):
"""
Given a WCNF formula and a model, the method computes the MaxSAT
cost of the model, i.e. the sum of weights of soft clauses that are
unsatisfied by the model.
:param formula: an input MaxSAT formula
:para... | python | def _get_model_cost(self, formula, model):
"""
Given a WCNF formula and a model, the method computes the MaxSAT
cost of the model, i.e. the sum of weights of soft clauses that are
unsatisfied by the model.
:param formula: an input MaxSAT formula
:para... | [
"def",
"_get_model_cost",
"(",
"self",
",",
"formula",
",",
"model",
")",
":",
"model_set",
"=",
"set",
"(",
"model",
")",
"cost",
"=",
"0",
"for",
"i",
",",
"cl",
"in",
"enumerate",
"(",
"formula",
".",
"soft",
")",
":",
"cost",
"+=",
"formula",
"... | Given a WCNF formula and a model, the method computes the MaxSAT
cost of the model, i.e. the sum of weights of soft clauses that are
unsatisfied by the model.
:param formula: an input MaxSAT formula
:param model: a satisfying assignment
:type formula: :class... | [
"Given",
"a",
"WCNF",
"formula",
"and",
"a",
"model",
"the",
"method",
"computes",
"the",
"MaxSAT",
"cost",
"of",
"the",
"model",
"i",
".",
"e",
".",
"the",
"sum",
"of",
"weights",
"of",
"soft",
"clauses",
"that",
"are",
"unsatisfied",
"by",
"the",
"mo... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lsu.py#L249-L270 | train |
pysathq/pysat | examples/rc2.py | parse_options | def parse_options():
"""
Parses command-line option
"""
try:
opts, args = getopt.getopt(sys.argv[1:], 'ac:e:hilms:t:vx',
['adapt', 'comp=', 'enum=', 'exhaust', 'help', 'incr', 'blo',
'minimize', 'solver=', 'trim=', 'verbose'])
except getopt.GetoptErro... | python | def parse_options():
"""
Parses command-line option
"""
try:
opts, args = getopt.getopt(sys.argv[1:], 'ac:e:hilms:t:vx',
['adapt', 'comp=', 'enum=', 'exhaust', 'help', 'incr', 'blo',
'minimize', 'solver=', 'trim=', 'verbose'])
except getopt.GetoptErro... | [
"def",
"parse_options",
"(",
")",
":",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"'ac:e:hilms:t:vx'",
",",
"[",
"'adapt'",
",",
"'comp='",
",",
"'enum='",
",",
"'exhaust'",
",",
... | Parses command-line option | [
"Parses",
"command",
"-",
"line",
"option"
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L1463-L1520 | train |
pysathq/pysat | examples/rc2.py | RC2.delete | def delete(self):
"""
Explicit destructor of the internal SAT oracle and all the
totalizer objects creating during the solving process.
"""
if self.oracle:
self.oracle.delete()
self.oracle = None
if self.solver != 'mc': # for minicar... | python | def delete(self):
"""
Explicit destructor of the internal SAT oracle and all the
totalizer objects creating during the solving process.
"""
if self.oracle:
self.oracle.delete()
self.oracle = None
if self.solver != 'mc': # for minicar... | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"oracle",
":",
"self",
".",
"oracle",
".",
"delete",
"(",
")",
"self",
".",
"oracle",
"=",
"None",
"if",
"self",
".",
"solver",
"!=",
"'mc'",
":",
"# for minicard, there is nothing to free",
"for... | Explicit destructor of the internal SAT oracle and all the
totalizer objects creating during the solving process. | [
"Explicit",
"destructor",
"of",
"the",
"internal",
"SAT",
"oracle",
"and",
"all",
"the",
"totalizer",
"objects",
"creating",
"during",
"the",
"solving",
"process",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L382-L394 | train |
pysathq/pysat | examples/rc2.py | RC2.trim_core | def trim_core(self):
"""
This method trims a previously extracted unsatisfiable
core at most a given number of times. If a fixed point is
reached before that, the method returns.
"""
for i in range(self.trim):
# call solver with core assumption on... | python | def trim_core(self):
"""
This method trims a previously extracted unsatisfiable
core at most a given number of times. If a fixed point is
reached before that, the method returns.
"""
for i in range(self.trim):
# call solver with core assumption on... | [
"def",
"trim_core",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"trim",
")",
":",
"# call solver with core assumption only",
"# it must return 'unsatisfiable'",
"self",
".",
"oracle",
".",
"solve",
"(",
"assumptions",
"=",
"self",
".",
... | This method trims a previously extracted unsatisfiable
core at most a given number of times. If a fixed point is
reached before that, the method returns. | [
"This",
"method",
"trims",
"a",
"previously",
"extracted",
"unsatisfiable",
"core",
"at",
"most",
"a",
"given",
"number",
"of",
"times",
".",
"If",
"a",
"fixed",
"point",
"is",
"reached",
"before",
"that",
"the",
"method",
"returns",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L757-L777 | train |
pysathq/pysat | examples/rc2.py | RC2.minimize_core | def minimize_core(self):
"""
Reduce a previously extracted core and compute an
over-approximation of an MUS. This is done using the
simple deletion-based MUS extraction algorithm.
The idea is to try to deactivate soft clauses of the
unsatisfiable core... | python | def minimize_core(self):
"""
Reduce a previously extracted core and compute an
over-approximation of an MUS. This is done using the
simple deletion-based MUS extraction algorithm.
The idea is to try to deactivate soft clauses of the
unsatisfiable core... | [
"def",
"minimize_core",
"(",
"self",
")",
":",
"if",
"self",
".",
"minz",
"and",
"len",
"(",
"self",
".",
"core",
")",
">",
"1",
":",
"self",
".",
"core",
"=",
"sorted",
"(",
"self",
".",
"core",
",",
"key",
"=",
"lambda",
"l",
":",
"self",
"."... | Reduce a previously extracted core and compute an
over-approximation of an MUS. This is done using the
simple deletion-based MUS extraction algorithm.
The idea is to try to deactivate soft clauses of the
unsatisfiable core one by one while checking if the
rem... | [
"Reduce",
"a",
"previously",
"extracted",
"core",
"and",
"compute",
"an",
"over",
"-",
"approximation",
"of",
"an",
"MUS",
".",
"This",
"is",
"done",
"using",
"the",
"simple",
"deletion",
"-",
"based",
"MUS",
"extraction",
"algorithm",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L779-L808 | train |
pysathq/pysat | examples/rc2.py | RC2.update_sum | def update_sum(self, assump):
"""
The method is used to increase the bound for a given
totalizer sum. The totalizer object is identified by the
input parameter ``assump``, which is an assumption literal
associated with the totalizer object.
The method... | python | def update_sum(self, assump):
"""
The method is used to increase the bound for a given
totalizer sum. The totalizer object is identified by the
input parameter ``assump``, which is an assumption literal
associated with the totalizer object.
The method... | [
"def",
"update_sum",
"(",
"self",
",",
"assump",
")",
":",
"# getting a totalizer object corresponding to assumption",
"t",
"=",
"self",
".",
"tobj",
"[",
"assump",
"]",
"# increment the current bound",
"b",
"=",
"self",
".",
"bnds",
"[",
"assump",
"]",
"+",
"1"... | The method is used to increase the bound for a given
totalizer sum. The totalizer object is identified by the
input parameter ``assump``, which is an assumption literal
associated with the totalizer object.
The method increases the bound for the totalizer sum,
... | [
"The",
"method",
"is",
"used",
"to",
"increase",
"the",
"bound",
"for",
"a",
"given",
"totalizer",
"sum",
".",
"The",
"totalizer",
"object",
"is",
"identified",
"by",
"the",
"input",
"parameter",
"assump",
"which",
"is",
"an",
"assumption",
"literal",
"assoc... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L990-L1045 | train |
pysathq/pysat | examples/rc2.py | RC2.set_bound | def set_bound(self, tobj, rhs):
"""
Given a totalizer sum and its right-hand side to be
enforced, the method creates a new sum assumption literal,
which will be used in the following SAT oracle calls.
:param tobj: totalizer sum
:param rhs: right-hand ... | python | def set_bound(self, tobj, rhs):
"""
Given a totalizer sum and its right-hand side to be
enforced, the method creates a new sum assumption literal,
which will be used in the following SAT oracle calls.
:param tobj: totalizer sum
:param rhs: right-hand ... | [
"def",
"set_bound",
"(",
"self",
",",
"tobj",
",",
"rhs",
")",
":",
"# saving the sum and its weight in a mapping",
"self",
".",
"tobj",
"[",
"-",
"tobj",
".",
"rhs",
"[",
"rhs",
"]",
"]",
"=",
"tobj",
"self",
".",
"bnds",
"[",
"-",
"tobj",
".",
"rhs",... | Given a totalizer sum and its right-hand side to be
enforced, the method creates a new sum assumption literal,
which will be used in the following SAT oracle calls.
:param tobj: totalizer sum
:param rhs: right-hand side
:type tobj: :class:`.ITotalizer`
... | [
"Given",
"a",
"totalizer",
"sum",
"and",
"its",
"right",
"-",
"hand",
"side",
"to",
"be",
"enforced",
"the",
"method",
"creates",
"a",
"new",
"sum",
"assumption",
"literal",
"which",
"will",
"be",
"used",
"in",
"the",
"following",
"SAT",
"oracle",
"calls",... | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L1047-L1066 | train |
pysathq/pysat | examples/rc2.py | RC2.filter_assumps | def filter_assumps(self):
"""
Filter out unnecessary selectors and sums from the list of
assumption literals. The corresponding values are also
removed from the dictionaries of bounds and weights.
Note that assumptions marked as garbage are collected in
... | python | def filter_assumps(self):
"""
Filter out unnecessary selectors and sums from the list of
assumption literals. The corresponding values are also
removed from the dictionaries of bounds and weights.
Note that assumptions marked as garbage are collected in
... | [
"def",
"filter_assumps",
"(",
"self",
")",
":",
"self",
".",
"sels",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"not",
"in",
"self",
".",
"garbage",
",",
"self",
".",
"sels",
")",
")",
"self",
".",
"sums",
"=",
"list",
"(",
"filter... | Filter out unnecessary selectors and sums from the list of
assumption literals. The corresponding values are also
removed from the dictionaries of bounds and weights.
Note that assumptions marked as garbage are collected in
the core processing methods, i.e. in :func:`pro... | [
"Filter",
"out",
"unnecessary",
"selectors",
"and",
"sums",
"from",
"the",
"list",
"of",
"assumption",
"literals",
".",
"The",
"corresponding",
"values",
"are",
"also",
"removed",
"from",
"the",
"dictionaries",
"of",
"bounds",
"and",
"weights",
"."
] | 522742e8f2d4c6ac50ecd9087f7a346206774c67 | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L1068-L1085 | train |
Kensuke-Mitsuzawa/JapaneseTokenizers | JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py | MecabWrapper.__get_path_to_mecab_config | def __get_path_to_mecab_config(self):
"""You get path into mecab-config
"""
if six.PY2:
path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config'])
path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '')
else:
... | python | def __get_path_to_mecab_config(self):
"""You get path into mecab-config
"""
if six.PY2:
path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config'])
path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '')
else:
... | [
"def",
"__get_path_to_mecab_config",
"(",
"self",
")",
":",
"if",
"six",
".",
"PY2",
":",
"path_mecab_config_dir",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'which'",
",",
"'mecab-config'",
"]",
")",
"path_mecab_config_dir",
"=",
"path_mecab_config_dir",
... | You get path into mecab-config | [
"You",
"get",
"path",
"into",
"mecab",
"-",
"config"
] | 3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c | https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py#L79-L90 | train |
Kensuke-Mitsuzawa/JapaneseTokenizers | JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py | MecabWrapper.__result_parser | def __result_parser(self, analyzed_line, is_feature, is_surface):
# type: (text_type,bool,bool)->TokenizedResult
"""Extract surface word and feature from analyzed line.
Extracted elements are returned with TokenizedResult class
"""
assert isinstance(analyzed_line, str)
as... | python | def __result_parser(self, analyzed_line, is_feature, is_surface):
# type: (text_type,bool,bool)->TokenizedResult
"""Extract surface word and feature from analyzed line.
Extracted elements are returned with TokenizedResult class
"""
assert isinstance(analyzed_line, str)
as... | [
"def",
"__result_parser",
"(",
"self",
",",
"analyzed_line",
",",
"is_feature",
",",
"is_surface",
")",
":",
"# type: (text_type,bool,bool)->TokenizedResult",
"assert",
"isinstance",
"(",
"analyzed_line",
",",
"str",
")",
"assert",
"isinstance",
"(",
"is_feature",
","... | Extract surface word and feature from analyzed line.
Extracted elements are returned with TokenizedResult class | [
"Extract",
"surface",
"word",
"and",
"feature",
"from",
"analyzed",
"line",
".",
"Extracted",
"elements",
"are",
"returned",
"with",
"TokenizedResult",
"class"
] | 3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c | https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py#L239-L259 | train |
Kensuke-Mitsuzawa/JapaneseTokenizers | JapaneseTokenizer/datamodels.py | __is_valid_pos | def __is_valid_pos(pos_tuple, valid_pos):
# type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool
"""This function checks token's pos is with in POS set that user specified.
If token meets all conditions, Return True; else return False
"""
def is_valid_pos(valid_pos_tuple):
# type: (... | python | def __is_valid_pos(pos_tuple, valid_pos):
# type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool
"""This function checks token's pos is with in POS set that user specified.
If token meets all conditions, Return True; else return False
"""
def is_valid_pos(valid_pos_tuple):
# type: (... | [
"def",
"__is_valid_pos",
"(",
"pos_tuple",
",",
"valid_pos",
")",
":",
"# type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool",
"def",
"is_valid_pos",
"(",
"valid_pos_tuple",
")",
":",
"# type: (Tuple[text_type,...])->bool",
"length_valid_pos_tuple",
"=",
"len",
"(",
... | This function checks token's pos is with in POS set that user specified.
If token meets all conditions, Return True; else return False | [
"This",
"function",
"checks",
"token",
"s",
"pos",
"is",
"with",
"in",
"POS",
"set",
"that",
"user",
"specified",
".",
"If",
"token",
"meets",
"all",
"conditions",
"Return",
"True",
";",
"else",
"return",
"False"
] | 3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c | https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/datamodels.py#L25-L43 | train |
Kensuke-Mitsuzawa/JapaneseTokenizers | JapaneseTokenizer/datamodels.py | filter_words | def filter_words(tokenized_obj, valid_pos, stopwords, check_field_name='stem'):
# type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type],text_type) -> FilteredObject
"""This function filter token that user don't want to take.
Condition is stopword and pos.
* Input
- valid_pos
... | python | def filter_words(tokenized_obj, valid_pos, stopwords, check_field_name='stem'):
# type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type],text_type) -> FilteredObject
"""This function filter token that user don't want to take.
Condition is stopword and pos.
* Input
- valid_pos
... | [
"def",
"filter_words",
"(",
"tokenized_obj",
",",
"valid_pos",
",",
"stopwords",
",",
"check_field_name",
"=",
"'stem'",
")",
":",
"# type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type],text_type) -> FilteredObject",
"assert",
"isinstance",
"(",
"tokenized_obj"... | This function filter token that user don't want to take.
Condition is stopword and pos.
* Input
- valid_pos
- List of Tuple which has POS element to keep.
- Keep in your mind, each tokenizer has different POS structure.
>>> [('名詞', '固有名詞'), ('動詞', )]
- stopwords
- List ... | [
"This",
"function",
"filter",
"token",
"that",
"user",
"don",
"t",
"want",
"to",
"take",
".",
"Condition",
"is",
"stopword",
"and",
"pos",
"."
] | 3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c | https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/datamodels.py#L46-L91 | train |
Kensuke-Mitsuzawa/JapaneseTokenizers | JapaneseTokenizer/datamodels.py | TokenizedSenetence.__extend_token_object | def __extend_token_object(self, token_object,
is_denormalize=True,
func_denormalizer=denormalize_text):
# type: (TokenizedResult,bool,Callable[[str],str])->Tuple
"""This method creates dict object from token object.
"""
assert i... | python | def __extend_token_object(self, token_object,
is_denormalize=True,
func_denormalizer=denormalize_text):
# type: (TokenizedResult,bool,Callable[[str],str])->Tuple
"""This method creates dict object from token object.
"""
assert i... | [
"def",
"__extend_token_object",
"(",
"self",
",",
"token_object",
",",
"is_denormalize",
"=",
"True",
",",
"func_denormalizer",
"=",
"denormalize_text",
")",
":",
"# type: (TokenizedResult,bool,Callable[[str],str])->Tuple",
"assert",
"isinstance",
"(",
"token_object",
",",
... | This method creates dict object from token object. | [
"This",
"method",
"creates",
"dict",
"object",
"from",
"token",
"object",
"."
] | 3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c | https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/datamodels.py#L143-L174 | train |
mosquito/cysystemd | cysystemd/daemon.py | notify | def notify(notification, value=None, unset_environment=False):
""" Send notification to systemd daemon
:type notification: Notification
:type value: int
:type unset_environment: bool
:param value: str or int value for non constant notifications
:returns None
"""
if not isinstance(noti... | python | def notify(notification, value=None, unset_environment=False):
""" Send notification to systemd daemon
:type notification: Notification
:type value: int
:type unset_environment: bool
:param value: str or int value for non constant notifications
:returns None
"""
if not isinstance(noti... | [
"def",
"notify",
"(",
"notification",
",",
"value",
"=",
"None",
",",
"unset_environment",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"notification",
",",
"Notification",
")",
":",
"raise",
"TypeError",
"(",
"\"state must be an instance of Notificatio... | Send notification to systemd daemon
:type notification: Notification
:type value: int
:type unset_environment: bool
:param value: str or int value for non constant notifications
:returns None | [
"Send",
"notification",
"to",
"systemd",
"daemon"
] | e0acede93387d51e4d6b20fdc278b2675052958d | https://github.com/mosquito/cysystemd/blob/e0acede93387d51e4d6b20fdc278b2675052958d/cysystemd/daemon.py#L28-L59 | train |
Pylons/hupper | src/hupper/worker.py | expand_source_paths | def expand_source_paths(paths):
""" Convert pyc files into their source equivalents."""
for src_path in paths:
# only track the source path if we can find it to avoid double-reloads
# when the source and the compiled path change because on some
# platforms they are not changed at the sam... | python | def expand_source_paths(paths):
""" Convert pyc files into their source equivalents."""
for src_path in paths:
# only track the source path if we can find it to avoid double-reloads
# when the source and the compiled path change because on some
# platforms they are not changed at the sam... | [
"def",
"expand_source_paths",
"(",
"paths",
")",
":",
"for",
"src_path",
"in",
"paths",
":",
"# only track the source path if we can find it to avoid double-reloads",
"# when the source and the compiled path change because on some",
"# platforms they are not changed at the same time",
"i... | Convert pyc files into their source equivalents. | [
"Convert",
"pyc",
"files",
"into",
"their",
"source",
"equivalents",
"."
] | 197173c09e775b66c148468b6299c571e736c381 | https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/worker.py#L84-L94 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.