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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | 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 appropriate, but
# setting __wrapped__ may still help with introspection.
_exit_wrapper.__wrapped__ = callback
self._push_exit_callback(_exit_wrapper, False)
return callback | 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 appropriate, but
# setting __wrapped__ may still help with introspection.
_exit_wrapper.__wrapped__ = callback
self._push_exit_callback(_exit_wrapper, False)
return callback | [
"def",
"push_async_callback",
"(",
"self",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"_exit_wrapper",
"=",
"self",
".",
"_create_async_cb_wrapper",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"# We changed the signature, so using @wraps is not appropriate, but",
"# setting __wrapped__ may still help with introspection.",
"_exit_wrapper",
".",
"__wrapped__",
"=",
"callback",
"self",
".",
"_push_exit_callback",
"(",
"_exit_wrapper",
",",
"False",
")",
"return",
"callback"
] | 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(candidate):
raise PrintableError(
"Found {}, but it's not a file.".format(candidate))
if os.path.dirname(prefix) == prefix:
# We've walked all the way to the top. Bail.
raise PrintableError("Can't find " + basename)
# Not found at this level. We must go...shallower.
prefix = os.path.dirname(prefix) | 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(candidate):
raise PrintableError(
"Found {}, but it's not a file.".format(candidate))
if os.path.dirname(prefix) == prefix:
# We've walked all the way to the top. Bail.
raise PrintableError("Can't find " + basename)
# Not found at this level. We must go...shallower.
prefix = os.path.dirname(prefix) | [
"def",
"find_project_file",
"(",
"start_dir",
",",
"basename",
")",
":",
"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",
"(",
"candidate",
")",
":",
"raise",
"PrintableError",
"(",
"\"Found {}, but it's not a file.\"",
".",
"format",
"(",
"candidate",
")",
")",
"if",
"os",
".",
"path",
".",
"dirname",
"(",
"prefix",
")",
"==",
"prefix",
":",
"# We've walked all the way to the top. Bail.",
"raise",
"PrintableError",
"(",
"\"Can't find \"",
"+",
"basename",
")",
"# Not found at this level. We must go...shallower.",
"prefix",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"prefix",
")"
] | 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(
len(files)))
return lines | 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(
len(files)))
return lines | [
"def",
"_format_file_lines",
"(",
"files",
")",
":",
"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",
"(",
"len",
"(",
"files",
")",
")",
")",
"return",
"lines"
] | 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 tree. As
# a workaround, we absoluteify the path.
env["GIT_INDEX_FILE"] = os.path.abspath(self.index_file)
return env | 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 tree. As
# a workaround, we absoluteify the path.
env["GIT_INDEX_FILE"] = os.path.abspath(self.index_file)
return env | [
"def",
"git_env",
"(",
"self",
")",
":",
"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 tree. As",
"# a workaround, we absoluteify the path.",
"env",
"[",
"\"GIT_INDEX_FILE\"",
"]",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"index_file",
")",
"return",
"env"
] | 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
# load state data from pickle file
with resource_stream(__name__, 'states.pkl') as pklfile:
for s in pickle.load(pklfile):
state = State(**s) # create state object
# create separate lists for obsolete, states, and territories
if state.is_obsolete:
OBSOLETE.append(state)
elif state.is_territory:
TERRITORIES.append(state)
else:
STATES.append(state)
if state.is_contiguous:
STATES_CONTIGUOUS.append(state)
if state.is_continental:
STATES_CONTINENTAL.append(state)
# also create list of all states and territories
STATES_AND_TERRITORIES.append(state)
# provide package-level abbreviation access: us.states.MD
globals()[state.abbr] = state | 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
# load state data from pickle file
with resource_stream(__name__, 'states.pkl') as pklfile:
for s in pickle.load(pklfile):
state = State(**s) # create state object
# create separate lists for obsolete, states, and territories
if state.is_obsolete:
OBSOLETE.append(state)
elif state.is_territory:
TERRITORIES.append(state)
else:
STATES.append(state)
if state.is_contiguous:
STATES_CONTIGUOUS.append(state)
if state.is_continental:
STATES_CONTINENTAL.append(state)
# also create list of all states and territories
STATES_AND_TERRITORIES.append(state)
# provide package-level abbreviation access: us.states.MD
globals()[state.abbr] = state | [
"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",
"(",
"pklfile",
")",
":",
"state",
"=",
"State",
"(",
"*",
"*",
"s",
")",
"# create state object",
"# create separate lists for obsolete, states, and territories",
"if",
"state",
".",
"is_obsolete",
":",
"OBSOLETE",
".",
"append",
"(",
"state",
")",
"elif",
"state",
".",
"is_territory",
":",
"TERRITORIES",
".",
"append",
"(",
"state",
")",
"else",
":",
"STATES",
".",
"append",
"(",
"state",
")",
"if",
"state",
".",
"is_contiguous",
":",
"STATES_CONTIGUOUS",
".",
"append",
"(",
"state",
")",
"if",
"state",
".",
"is_continental",
":",
"STATES_CONTINENTAL",
".",
"append",
"(",
"state",
")",
"# also create list of all states and territories",
"STATES_AND_TERRITORIES",
".",
"append",
"(",
"state",
")",
"# provide package-level abbreviation access: us.states.MD",
"globals",
"(",
")",
"[",
"state",
".",
"abbr",
"]",
"=",
"state"
] | 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 else will try to match the metaphone of state names
Metaphone is used to allow for incorrect, but phonetically accurate,
spelling of state names.
Exact matches can be done on any attribute on State objects by passing
the `field` argument. This skips the fuzzy-ish matching and does an
exact, case-sensitive comparison against the specified field.
This method caches non-None results, but can the cache can be bypassed
with the `use_cache=False` argument.
"""
import jellyfish
if field is None:
if FIPS_RE.match(val):
field = 'fips'
elif ABBR_RE.match(val):
val = val.upper()
field = 'abbr'
else:
val = jellyfish.metaphone(val)
field = 'name_metaphone'
# see if result is in cache
cache_key = "%s:%s" % (field, val)
if use_cache and cache_key in _lookup_cache:
return _lookup_cache[cache_key]
for state in STATES_AND_TERRITORIES:
if val == getattr(state, field):
_lookup_cache[cache_key] = state
return state | 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 else will try to match the metaphone of state names
Metaphone is used to allow for incorrect, but phonetically accurate,
spelling of state names.
Exact matches can be done on any attribute on State objects by passing
the `field` argument. This skips the fuzzy-ish matching and does an
exact, case-sensitive comparison against the specified field.
This method caches non-None results, but can the cache can be bypassed
with the `use_cache=False` argument.
"""
import jellyfish
if field is None:
if FIPS_RE.match(val):
field = 'fips'
elif ABBR_RE.match(val):
val = val.upper()
field = 'abbr'
else:
val = jellyfish.metaphone(val)
field = 'name_metaphone'
# see if result is in cache
cache_key = "%s:%s" % (field, val)
if use_cache and cache_key in _lookup_cache:
return _lookup_cache[cache_key]
for state in STATES_AND_TERRITORIES:
if val == getattr(state, field):
_lookup_cache[cache_key] = state
return state | [
"def",
"lookup",
"(",
"val",
",",
"field",
"=",
"None",
",",
"use_cache",
"=",
"True",
")",
":",
"import",
"jellyfish",
"if",
"field",
"is",
"None",
":",
"if",
"FIPS_RE",
".",
"match",
"(",
"val",
")",
":",
"field",
"=",
"'fips'",
"elif",
"ABBR_RE",
".",
"match",
"(",
"val",
")",
":",
"val",
"=",
"val",
".",
"upper",
"(",
")",
"field",
"=",
"'abbr'",
"else",
":",
"val",
"=",
"jellyfish",
".",
"metaphone",
"(",
"val",
")",
"field",
"=",
"'name_metaphone'",
"# see if result is in cache",
"cache_key",
"=",
"\"%s:%s\"",
"%",
"(",
"field",
",",
"val",
")",
"if",
"use_cache",
"and",
"cache_key",
"in",
"_lookup_cache",
":",
"return",
"_lookup_cache",
"[",
"cache_key",
"]",
"for",
"state",
"in",
"STATES_AND_TERRITORIES",
":",
"if",
"val",
"==",
"getattr",
"(",
"state",
",",
"field",
")",
":",
"_lookup_cache",
"[",
"cache_key",
"]",
"=",
"state",
"return",
"state"
] | 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
Metaphone is used to allow for incorrect, but phonetically accurate,
spelling of state names.
Exact matches can be done on any attribute on State objects by passing
the `field` argument. This skips the fuzzy-ish matching and does an
exact, case-sensitive comparison against the specified field.
This method caches non-None results, but can the cache can be bypassed
with the `use_cache=False` argument. | [
"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 bibtex.
allresults : bool, optional
return all results or only the first (i.e. best one)
Returns
-------
result : list of strings
the list with citations
"""
logger.debug("Query: {sstring}".format(sstring=searchstr))
searchstr = '/scholar?q='+quote(searchstr)
url = GOOGLE_SCHOLAR_URL + searchstr
header = HEADERS
header['Cookie'] = "GSP=CF=%d" % outformat
request = Request(url, headers=header)
response = urlopen(request)
html = response.read()
html = html.decode('utf8')
# grab the links
tmp = get_links(html, outformat)
# follow the bibtex links to get the bibtex entries
result = list()
if not allresults:
tmp = tmp[:1]
for link in tmp:
url = GOOGLE_SCHOLAR_URL+link
request = Request(url, headers=header)
response = urlopen(request)
bib = response.read()
bib = bib.decode('utf8')
result.append(bib)
return result | 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 bibtex.
allresults : bool, optional
return all results or only the first (i.e. best one)
Returns
-------
result : list of strings
the list with citations
"""
logger.debug("Query: {sstring}".format(sstring=searchstr))
searchstr = '/scholar?q='+quote(searchstr)
url = GOOGLE_SCHOLAR_URL + searchstr
header = HEADERS
header['Cookie'] = "GSP=CF=%d" % outformat
request = Request(url, headers=header)
response = urlopen(request)
html = response.read()
html = html.decode('utf8')
# grab the links
tmp = get_links(html, outformat)
# follow the bibtex links to get the bibtex entries
result = list()
if not allresults:
tmp = tmp[:1]
for link in tmp:
url = GOOGLE_SCHOLAR_URL+link
request = Request(url, headers=header)
response = urlopen(request)
bib = response.read()
bib = bib.decode('utf8')
result.append(bib)
return result | [
"def",
"query",
"(",
"searchstr",
",",
"outformat",
"=",
"FORMAT_BIBTEX",
",",
"allresults",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Query: {sstring}\"",
".",
"format",
"(",
"sstring",
"=",
"searchstr",
")",
")",
"searchstr",
"=",
"'/scholar?q='",
"+",
"quote",
"(",
"searchstr",
")",
"url",
"=",
"GOOGLE_SCHOLAR_URL",
"+",
"searchstr",
"header",
"=",
"HEADERS",
"header",
"[",
"'Cookie'",
"]",
"=",
"\"GSP=CF=%d\"",
"%",
"outformat",
"request",
"=",
"Request",
"(",
"url",
",",
"headers",
"=",
"header",
")",
"response",
"=",
"urlopen",
"(",
"request",
")",
"html",
"=",
"response",
".",
"read",
"(",
")",
"html",
"=",
"html",
".",
"decode",
"(",
"'utf8'",
")",
"# grab the links",
"tmp",
"=",
"get_links",
"(",
"html",
",",
"outformat",
")",
"# follow the bibtex links to get the bibtex entries",
"result",
"=",
"list",
"(",
")",
"if",
"not",
"allresults",
":",
"tmp",
"=",
"tmp",
"[",
":",
"1",
"]",
"for",
"link",
"in",
"tmp",
":",
"url",
"=",
"GOOGLE_SCHOLAR_URL",
"+",
"link",
"request",
"=",
"Request",
"(",
"url",
",",
"headers",
"=",
"header",
")",
"response",
"=",
"urlopen",
"(",
"request",
")",
"bib",
"=",
"response",
".",
"read",
"(",
")",
"bib",
"=",
"bib",
".",
"decode",
"(",
"'utf8'",
")",
"result",
".",
"append",
"(",
"bib",
")",
"return",
"result"
] | 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 only the first (i.e. best one)
Returns
-------
result : list of strings
the list with citations | [
"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:
refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.bib\?[^"]*)')
elif outformat == FORMAT_ENDNOTE:
refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.enw\?[^"]*)"')
elif outformat == FORMAT_REFMAN:
refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.ris\?[^"]*)"')
elif outformat == FORMAT_WENXIANWANG:
refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.ral\?[^"]*)"')
reflist = refre.findall(html)
# escape html entities
reflist = [re.sub('&(%s);' % '|'.join(name2codepoint), lambda m:
chr(name2codepoint[m.group(1)]), s) for s in reflist]
return reflist | 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:
refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.bib\?[^"]*)')
elif outformat == FORMAT_ENDNOTE:
refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.enw\?[^"]*)"')
elif outformat == FORMAT_REFMAN:
refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.ris\?[^"]*)"')
elif outformat == FORMAT_WENXIANWANG:
refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.ral\?[^"]*)"')
reflist = refre.findall(html)
# escape html entities
reflist = [re.sub('&(%s);' % '|'.join(name2codepoint), lambda m:
chr(name2codepoint[m.group(1)]), s) for s in reflist]
return reflist | [
"def",
"get_links",
"(",
"html",
",",
"outformat",
")",
":",
"if",
"outformat",
"==",
"FORMAT_BIBTEX",
":",
"refre",
"=",
"re",
".",
"compile",
"(",
"r'<a href=\"https://scholar.googleusercontent.com(/scholar\\.bib\\?[^\"]*)'",
")",
"elif",
"outformat",
"==",
"FORMAT_ENDNOTE",
":",
"refre",
"=",
"re",
".",
"compile",
"(",
"r'<a href=\"https://scholar.googleusercontent.com(/scholar\\.enw\\?[^\"]*)\"'",
")",
"elif",
"outformat",
"==",
"FORMAT_REFMAN",
":",
"refre",
"=",
"re",
".",
"compile",
"(",
"r'<a href=\"https://scholar.googleusercontent.com(/scholar\\.ris\\?[^\"]*)\"'",
")",
"elif",
"outformat",
"==",
"FORMAT_WENXIANWANG",
":",
"refre",
"=",
"re",
".",
"compile",
"(",
"r'<a href=\"https://scholar.googleusercontent.com(/scholar\\.ral\\?[^\"]*)\"'",
")",
"reflist",
"=",
"refre",
".",
"findall",
"(",
"html",
")",
"# escape html entities",
"reflist",
"=",
"[",
"re",
".",
"sub",
"(",
"'&(%s);'",
"%",
"'|'",
".",
"join",
"(",
"name2codepoint",
")",
",",
"lambda",
"m",
":",
"chr",
"(",
"name2codepoint",
"[",
"m",
".",
"group",
"(",
"1",
")",
"]",
")",
",",
"s",
")",
"for",
"s",
"in",
"reflist",
"]",
"return",
"reflist"
] | 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
-------
str
the converted text
"""
if startpage is not None:
startpageargs = ['-f', str(startpage)]
else:
startpageargs = []
stdout = subprocess.Popen(["pdftotext", "-q"] + startpageargs + [pdf, "-"],
stdout=subprocess.PIPE).communicate()[0]
# python2 and 3
if not isinstance(stdout, str):
stdout = stdout.decode()
return stdout | 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
-------
str
the converted text
"""
if startpage is not None:
startpageargs = ['-f', str(startpage)]
else:
startpageargs = []
stdout = subprocess.Popen(["pdftotext", "-q"] + startpageargs + [pdf, "-"],
stdout=subprocess.PIPE).communicate()[0]
# python2 and 3
if not isinstance(stdout, str):
stdout = stdout.decode()
return stdout | [
"def",
"convert_pdf_to_txt",
"(",
"pdf",
",",
"startpage",
"=",
"None",
")",
":",
"if",
"startpage",
"is",
"not",
"None",
":",
"startpageargs",
"=",
"[",
"'-f'",
",",
"str",
"(",
"startpage",
")",
"]",
"else",
":",
"startpageargs",
"=",
"[",
"]",
"stdout",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"pdftotext\"",
",",
"\"-q\"",
"]",
"+",
"startpageargs",
"+",
"[",
"pdf",
",",
"\"-\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"# python2 and 3",
"if",
"not",
"isinstance",
"(",
"stdout",
",",
"str",
")",
":",
"stdout",
"=",
"stdout",
".",
"decode",
"(",
")",
"return",
"stdout"
] | 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 format of the citations
startpage : int
first page to start reading from
Returns
-------
List[str]
the list with citations
"""
txt = convert_pdf_to_txt(pdf, startpage)
# remove all non alphanumeric characters
txt = re.sub("\W", " ", txt)
words = txt.strip().split()[:20]
gsquery = " ".join(words)
bibtexlist = query(gsquery, outformat, allresults)
return bibtexlist | 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 format of the citations
startpage : int
first page to start reading from
Returns
-------
List[str]
the list with citations
"""
txt = convert_pdf_to_txt(pdf, startpage)
# remove all non alphanumeric characters
txt = re.sub("\W", " ", txt)
words = txt.strip().split()[:20]
gsquery = " ".join(words)
bibtexlist = query(gsquery, outformat, allresults)
return bibtexlist | [
"def",
"pdflookup",
"(",
"pdf",
",",
"allresults",
",",
"outformat",
",",
"startpage",
"=",
"None",
")",
":",
"txt",
"=",
"convert_pdf_to_txt",
"(",
"pdf",
",",
"startpage",
")",
"# remove all non alphanumeric characters",
"txt",
"=",
"re",
".",
"sub",
"(",
"\"\\W\"",
",",
"\" \"",
",",
"txt",
")",
"words",
"=",
"txt",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"[",
":",
"20",
"]",
"gsquery",
"=",
"\" \"",
".",
"join",
"(",
"words",
")",
"bibtexlist",
"=",
"query",
"(",
"gsquery",
",",
"outformat",
",",
"allresults",
")",
"return",
"bibtexlist"
] | 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 start reading from
Returns
-------
List[str]
the list with citations | [
"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]
value = value.strip()
while value.endswith(','):
value = value[:-1]
while value.startswith('{') or value.startswith('"'):
value = value[1:-1]
return value
return None | 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]
value = value.strip()
while value.endswith(','):
value = value[:-1]
while value.startswith('{') or value.startswith('"'):
value = value[1:-1]
return value
return None | [
"def",
"_get_bib_element",
"(",
"bibitem",
",",
"element",
")",
":",
"lst",
"=",
"[",
"i",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"bibitem",
".",
"split",
"(",
"\"\\n\"",
")",
"]",
"for",
"i",
"in",
"lst",
":",
"if",
"i",
".",
"startswith",
"(",
"element",
")",
":",
"value",
"=",
"i",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"[",
"-",
"1",
"]",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"while",
"value",
".",
"endswith",
"(",
"','",
")",
":",
"value",
"=",
"value",
"[",
":",
"-",
"1",
"]",
"while",
"value",
".",
"startswith",
"(",
"'{'",
")",
"or",
"value",
".",
"startswith",
"(",
"'\"'",
")",
":",
"value",
"=",
"value",
"[",
"1",
":",
"-",
"1",
"]",
"return",
"value",
"return",
"None"
] | 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, title) if i]
filename = "-".join(l) + ".pdf"
newfile = pdf.replace(os.path.basename(pdf), filename)
logger.info('Renaming {in_} to {out}'.format(in_=pdf, out=newfile))
os.rename(pdf, newfile) | 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, title) if i]
filename = "-".join(l) + ".pdf"
newfile = pdf.replace(os.path.basename(pdf), filename)
logger.info('Renaming {in_} to {out}'.format(in_=pdf, out=newfile))
os.rename(pdf, newfile) | [
"def",
"rename_file",
"(",
"pdf",
",",
"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",
",",
"title",
")",
"if",
"i",
"]",
"filename",
"=",
"\"-\"",
".",
"join",
"(",
"l",
")",
"+",
"\".pdf\"",
"newfile",
"=",
"pdf",
".",
"replace",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"pdf",
")",
",",
"filename",
")",
"logger",
".",
"info",
"(",
"'Renaming {in_} to {out}'",
".",
"format",
"(",
"in_",
"=",
"pdf",
",",
"out",
"=",
"newfile",
")",
")",
"os",
".",
"rename",
"(",
"pdf",
",",
"newfile",
")"
] | 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
soup = BeautifulStoneSoup(fh)
return soup | 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
soup = BeautifulStoneSoup(fh)
return soup | [
"def",
"soup_maker",
"(",
"fh",
")",
":",
"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",
"soup",
"=",
"BeautifulStoneSoup",
"(",
"fh",
")",
"return",
"soup"
] | 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)
else:
file_handler = file_handle
# Store the headers
xbrl_file = XBRLPreprocessedFile(file_handler)
xbrl = soup_maker(xbrl_file.fh)
file_handler.close()
xbrl_base = xbrl.find(name=re.compile("xbrl*:*"))
if xbrl.find('xbrl') is None and xbrl_base is None:
raise XBRLParserException('The xbrl file is empty!')
# lookahead to see if we need a custom leading element
lookahead = xbrl.find(name=re.compile("context",
re.IGNORECASE | re.MULTILINE)).name
if ":" in lookahead:
self.xbrl_base = lookahead.split(":")[0] + ":"
else:
self.xbrl_base = ""
return xbrl | 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)
else:
file_handler = file_handle
# Store the headers
xbrl_file = XBRLPreprocessedFile(file_handler)
xbrl = soup_maker(xbrl_file.fh)
file_handler.close()
xbrl_base = xbrl.find(name=re.compile("xbrl*:*"))
if xbrl.find('xbrl') is None and xbrl_base is None:
raise XBRLParserException('The xbrl file is empty!')
# lookahead to see if we need a custom leading element
lookahead = xbrl.find(name=re.compile("context",
re.IGNORECASE | re.MULTILINE)).name
if ":" in lookahead:
self.xbrl_base = lookahead.split(":")[0] + ":"
else:
self.xbrl_base = ""
return xbrl | [
"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",
")",
"else",
":",
"file_handler",
"=",
"file_handle",
"# Store the headers",
"xbrl_file",
"=",
"XBRLPreprocessedFile",
"(",
"file_handler",
")",
"xbrl",
"=",
"soup_maker",
"(",
"xbrl_file",
".",
"fh",
")",
"file_handler",
".",
"close",
"(",
")",
"xbrl_base",
"=",
"xbrl",
".",
"find",
"(",
"name",
"=",
"re",
".",
"compile",
"(",
"\"xbrl*:*\"",
")",
")",
"if",
"xbrl",
".",
"find",
"(",
"'xbrl'",
")",
"is",
"None",
"and",
"xbrl_base",
"is",
"None",
":",
"raise",
"XBRLParserException",
"(",
"'The xbrl file is empty!'",
")",
"# lookahead to see if we need a custom leading element",
"lookahead",
"=",
"xbrl",
".",
"find",
"(",
"name",
"=",
"re",
".",
"compile",
"(",
"\"context\"",
",",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"MULTILINE",
")",
")",
".",
"name",
"if",
"\":\"",
"in",
"lookahead",
":",
"self",
".",
"xbrl_base",
"=",
"lookahead",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"+",
"\":\"",
"else",
":",
"self",
".",
"xbrl_base",
"=",
"\"\"",
"return",
"xbrl"
] | 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,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger = logging.getLogger(__name__)
else:
logger = None
trading_symbol = xbrl.find_all(name=re.compile("(dei:tradingsymbol)",
re.IGNORECASE | re.MULTILINE))
dei_obj.trading_symbol = \
self.data_processing(trading_symbol, xbrl,
ignore_errors, logger,
options={'type': 'String',
'no_context': True})
company_name = xbrl.find_all(name=re.compile("(dei:entityregistrantname)",
re.IGNORECASE | re.MULTILINE))
dei_obj.company_name = \
self.data_processing(company_name, xbrl,
ignore_errors, logger,
options={'type': 'String',
'no_context': True})
shares_outstanding = xbrl.find_all(name=re.compile("(dei:entitycommonstocksharesoutstanding)",
re.IGNORECASE | re.MULTILINE))
dei_obj.shares_outstanding = \
self.data_processing(shares_outstanding, xbrl,
ignore_errors, logger,
options={'type': 'Number',
'no_context': True})
public_float = xbrl.find_all(name=re.compile("(dei:entitypublicfloat)",
re.IGNORECASE | re.MULTILINE))
dei_obj.public_float = \
self.data_processing(public_float, xbrl,
ignore_errors, logger,
options={'type': 'Number',
'no_context': True})
return dei_obj | 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,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger = logging.getLogger(__name__)
else:
logger = None
trading_symbol = xbrl.find_all(name=re.compile("(dei:tradingsymbol)",
re.IGNORECASE | re.MULTILINE))
dei_obj.trading_symbol = \
self.data_processing(trading_symbol, xbrl,
ignore_errors, logger,
options={'type': 'String',
'no_context': True})
company_name = xbrl.find_all(name=re.compile("(dei:entityregistrantname)",
re.IGNORECASE | re.MULTILINE))
dei_obj.company_name = \
self.data_processing(company_name, xbrl,
ignore_errors, logger,
options={'type': 'String',
'no_context': True})
shares_outstanding = xbrl.find_all(name=re.compile("(dei:entitycommonstocksharesoutstanding)",
re.IGNORECASE | re.MULTILINE))
dei_obj.shares_outstanding = \
self.data_processing(shares_outstanding, xbrl,
ignore_errors, logger,
options={'type': 'Number',
'no_context': True})
public_float = xbrl.find_all(name=re.compile("(dei:entitypublicfloat)",
re.IGNORECASE | re.MULTILINE))
dei_obj.public_float = \
self.data_processing(public_float, xbrl,
ignore_errors, logger,
options={'type': 'Number',
'no_context': True})
return dei_obj | [
"def",
"parseDEI",
"(",
"self",
",",
"xbrl",
",",
"ignore_errors",
"=",
"0",
")",
":",
"dei_obj",
"=",
"DEI",
"(",
")",
"if",
"ignore_errors",
"==",
"2",
":",
"logging",
".",
"basicConfig",
"(",
"filename",
"=",
"'/tmp/xbrl.log'",
",",
"level",
"=",
"logging",
".",
"ERROR",
",",
"format",
"=",
"'%(asctime)s %(levelname)s %(name)s %(message)s'",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"else",
":",
"logger",
"=",
"None",
"trading_symbol",
"=",
"xbrl",
".",
"find_all",
"(",
"name",
"=",
"re",
".",
"compile",
"(",
"\"(dei:tradingsymbol)\"",
",",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"MULTILINE",
")",
")",
"dei_obj",
".",
"trading_symbol",
"=",
"self",
".",
"data_processing",
"(",
"trading_symbol",
",",
"xbrl",
",",
"ignore_errors",
",",
"logger",
",",
"options",
"=",
"{",
"'type'",
":",
"'String'",
",",
"'no_context'",
":",
"True",
"}",
")",
"company_name",
"=",
"xbrl",
".",
"find_all",
"(",
"name",
"=",
"re",
".",
"compile",
"(",
"\"(dei:entityregistrantname)\"",
",",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"MULTILINE",
")",
")",
"dei_obj",
".",
"company_name",
"=",
"self",
".",
"data_processing",
"(",
"company_name",
",",
"xbrl",
",",
"ignore_errors",
",",
"logger",
",",
"options",
"=",
"{",
"'type'",
":",
"'String'",
",",
"'no_context'",
":",
"True",
"}",
")",
"shares_outstanding",
"=",
"xbrl",
".",
"find_all",
"(",
"name",
"=",
"re",
".",
"compile",
"(",
"\"(dei:entitycommonstocksharesoutstanding)\"",
",",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"MULTILINE",
")",
")",
"dei_obj",
".",
"shares_outstanding",
"=",
"self",
".",
"data_processing",
"(",
"shares_outstanding",
",",
"xbrl",
",",
"ignore_errors",
",",
"logger",
",",
"options",
"=",
"{",
"'type'",
":",
"'Number'",
",",
"'no_context'",
":",
"True",
"}",
")",
"public_float",
"=",
"xbrl",
".",
"find_all",
"(",
"name",
"=",
"re",
".",
"compile",
"(",
"\"(dei:entitypublicfloat)\"",
",",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"MULTILINE",
")",
")",
"dei_obj",
".",
"public_float",
"=",
"self",
".",
"data_processing",
"(",
"public_float",
",",
"xbrl",
",",
"ignore_errors",
",",
"logger",
",",
"options",
"=",
"{",
"'type'",
":",
"'Number'",
",",
"'no_context'",
":",
"True",
"}",
")",
"return",
"dei_obj"
] | 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*',
re.IGNORECASE | re.MULTILINE))
elements = {}
for data in custom_data:
if XBRLParser().is_number(data.text):
setattr(custom_obj, data.name.split(':')[1], data.text)
return custom_obj | 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*',
re.IGNORECASE | re.MULTILINE))
elements = {}
for data in custom_data:
if XBRLParser().is_number(data.text):
setattr(custom_obj, data.name.split(':')[1], data.text)
return custom_obj | [
"def",
"parseCustom",
"(",
"self",
",",
"xbrl",
",",
"ignore_errors",
"=",
"0",
")",
":",
"custom_obj",
"=",
"Custom",
"(",
")",
"custom_data",
"=",
"xbrl",
".",
"find_all",
"(",
"re",
".",
"compile",
"(",
"'^((?!(us-gaap|dei|xbrll|xbrldi)).)*:\\s*'",
",",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"MULTILINE",
")",
")",
"elements",
"=",
"{",
"}",
"for",
"data",
"in",
"custom_data",
":",
"if",
"XBRLParser",
"(",
")",
".",
"is_number",
"(",
"data",
".",
"text",
")",
":",
"setattr",
"(",
"custom_obj",
",",
"data",
".",
"name",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
",",
"data",
".",
"text",
")",
"return",
"custom_obj"
] | 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 precision is 0, this must be handled seperately
if precision == 0:
str_val = str(encoded)
else:
str_val = str(encoded)[:precision]
if len(str_val) > 0:
return float(str_val)
else:
return 0 | 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 precision is 0, this must be handled seperately
if precision == 0:
str_val = str(encoded)
else:
str_val = str(encoded)[:precision]
if len(str_val) > 0:
return float(str_val)
else:
return 0 | [
"def",
"trim_decimals",
"(",
"s",
",",
"precision",
"=",
"-",
"3",
")",
":",
"encoded",
"=",
"s",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"str_val",
"=",
"\"\"",
"if",
"six",
".",
"PY3",
":",
"str_val",
"=",
"str",
"(",
"encoded",
",",
"encoding",
"=",
"'ascii'",
",",
"errors",
"=",
"'ignore'",
")",
"[",
":",
"precision",
"]",
"else",
":",
"# If precision is 0, this must be handled seperately",
"if",
"precision",
"==",
"0",
":",
"str_val",
"=",
"str",
"(",
"encoded",
")",
"else",
":",
"str_val",
"=",
"str",
"(",
"encoded",
")",
"[",
":",
"precision",
"]",
"if",
"len",
"(",
"str_val",
")",
">",
"0",
":",
"return",
"float",
"(",
"str_val",
")",
"else",
":",
"return",
"0"
] | 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
stated by the context.
"""
options = kwargs.get('options', {'type': 'Number',
'no_context': False})
if options['type'] == 'String':
if len(elements) > 0:
return elements[0].text
if options['no_context'] == True:
if len(elements) > 0 and XBRLParser().is_number(elements[0].text):
return elements[0].text
try:
# Extract the correct values by context
correct_elements = []
for element in elements:
std = element.attrs['contextref']
if std in context_ids:
correct_elements.append(element)
elements = correct_elements
if len(elements) > 0 and XBRLParser().is_number(elements[0].text):
decimals = elements[0].attrs['decimals']
if decimals is not None:
attr_precision = decimals
if xbrl.precision != 0 \
and xbrl.precison != attr_precision:
xbrl.precision = attr_precision
if elements:
return XBRLParser().trim_decimals(elements[0].text,
int(xbrl.precision))
else:
return 0
else:
return 0
except Exception as e:
if ignore_errors == 0:
raise XBRLParserException('value extraction error')
elif ignore_errors == 1:
return 0
elif ignore_errors == 2:
logger.error(str(e) + " error at " +
''.join(elements[0].text)) | python | def data_processing(self,
elements,
xbrl,
ignore_errors,
logger,
context_ids=[],
**kwargs):
"""
Process a XBRL tag object and extract the correct value as
stated by the context.
"""
options = kwargs.get('options', {'type': 'Number',
'no_context': False})
if options['type'] == 'String':
if len(elements) > 0:
return elements[0].text
if options['no_context'] == True:
if len(elements) > 0 and XBRLParser().is_number(elements[0].text):
return elements[0].text
try:
# Extract the correct values by context
correct_elements = []
for element in elements:
std = element.attrs['contextref']
if std in context_ids:
correct_elements.append(element)
elements = correct_elements
if len(elements) > 0 and XBRLParser().is_number(elements[0].text):
decimals = elements[0].attrs['decimals']
if decimals is not None:
attr_precision = decimals
if xbrl.precision != 0 \
and xbrl.precison != attr_precision:
xbrl.precision = attr_precision
if elements:
return XBRLParser().trim_decimals(elements[0].text,
int(xbrl.precision))
else:
return 0
else:
return 0
except Exception as e:
if ignore_errors == 0:
raise XBRLParserException('value extraction error')
elif ignore_errors == 1:
return 0
elif ignore_errors == 2:
logger.error(str(e) + " error at " +
''.join(elements[0].text)) | [
"def",
"data_processing",
"(",
"self",
",",
"elements",
",",
"xbrl",
",",
"ignore_errors",
",",
"logger",
",",
"context_ids",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"kwargs",
".",
"get",
"(",
"'options'",
",",
"{",
"'type'",
":",
"'Number'",
",",
"'no_context'",
":",
"False",
"}",
")",
"if",
"options",
"[",
"'type'",
"]",
"==",
"'String'",
":",
"if",
"len",
"(",
"elements",
")",
">",
"0",
":",
"return",
"elements",
"[",
"0",
"]",
".",
"text",
"if",
"options",
"[",
"'no_context'",
"]",
"==",
"True",
":",
"if",
"len",
"(",
"elements",
")",
">",
"0",
"and",
"XBRLParser",
"(",
")",
".",
"is_number",
"(",
"elements",
"[",
"0",
"]",
".",
"text",
")",
":",
"return",
"elements",
"[",
"0",
"]",
".",
"text",
"try",
":",
"# Extract the correct values by context",
"correct_elements",
"=",
"[",
"]",
"for",
"element",
"in",
"elements",
":",
"std",
"=",
"element",
".",
"attrs",
"[",
"'contextref'",
"]",
"if",
"std",
"in",
"context_ids",
":",
"correct_elements",
".",
"append",
"(",
"element",
")",
"elements",
"=",
"correct_elements",
"if",
"len",
"(",
"elements",
")",
">",
"0",
"and",
"XBRLParser",
"(",
")",
".",
"is_number",
"(",
"elements",
"[",
"0",
"]",
".",
"text",
")",
":",
"decimals",
"=",
"elements",
"[",
"0",
"]",
".",
"attrs",
"[",
"'decimals'",
"]",
"if",
"decimals",
"is",
"not",
"None",
":",
"attr_precision",
"=",
"decimals",
"if",
"xbrl",
".",
"precision",
"!=",
"0",
"and",
"xbrl",
".",
"precison",
"!=",
"attr_precision",
":",
"xbrl",
".",
"precision",
"=",
"attr_precision",
"if",
"elements",
":",
"return",
"XBRLParser",
"(",
")",
".",
"trim_decimals",
"(",
"elements",
"[",
"0",
"]",
".",
"text",
",",
"int",
"(",
"xbrl",
".",
"precision",
")",
")",
"else",
":",
"return",
"0",
"else",
":",
"return",
"0",
"except",
"Exception",
"as",
"e",
":",
"if",
"ignore_errors",
"==",
"0",
":",
"raise",
"XBRLParserException",
"(",
"'value extraction error'",
")",
"elif",
"ignore_errors",
"==",
"1",
":",
"return",
"0",
"elif",
"ignore_errors",
"==",
"2",
":",
"logger",
".",
"error",
"(",
"str",
"(",
"e",
")",
"+",
"\" error at \"",
"+",
"''",
".",
"join",
"(",
"elements",
"[",
"0",
"]",
".",
"text",
")",
")"
] | 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__, self.instance.pk, section, name, self.instance.pk) | 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__, self.instance.pk, section, name, self.instance.pk) | [
"def",
"get_cache_key",
"(",
"self",
",",
"section",
",",
"name",
")",
":",
"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__",
",",
"self",
".",
"instance",
".",
"pk",
",",
"section",
",",
"name",
",",
"self",
".",
"instance",
".",
"pk",
")"
] | 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 == preferences_settings.CACHE_NONE_VALUE:
cached_value = None
return self.registry.get(
section=section, name=name).serializer.deserialize(cached_value) | 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 == preferences_settings.CACHE_NONE_VALUE:
cached_value = None
return self.registry.get(
section=section, name=name).serializer.deserialize(cached_value) | [
"def",
"from_cache",
"(",
"self",
",",
"section",
",",
"name",
")",
":",
"cached_value",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"self",
".",
"get_cache_key",
"(",
"section",
",",
"name",
")",
",",
"CachedValueNotFound",
")",
"if",
"cached_value",
"is",
"CachedValueNotFound",
":",
"raise",
"CachedValueNotFound",
"if",
"cached_value",
"==",
"preferences_settings",
".",
"CACHE_NONE_VALUE",
":",
"cached_value",
"=",
"None",
"return",
"self",
".",
"registry",
".",
"get",
"(",
"section",
"=",
"section",
",",
"name",
"=",
"name",
")",
".",
"serializer",
".",
"deserialize",
"(",
"cached_value",
")"
] | 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(keys.values()))
for k, v in cached.items():
# we replace dummy cached values by None here, if needed
if v == preferences_settings.CACHE_NONE_VALUE:
cached[k] = None
# we have to remap returned value since the underlying cached keys
# are not usable for an end user
return {
p.identifier(): p.serializer.deserialize(cached[k])
for p, k in keys.items()
if k in cached
} | 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(keys.values()))
for k, v in cached.items():
# we replace dummy cached values by None here, if needed
if v == preferences_settings.CACHE_NONE_VALUE:
cached[k] = None
# we have to remap returned value since the underlying cached keys
# are not usable for an end user
return {
p.identifier(): p.serializer.deserialize(cached[k])
for p, k in keys.items()
if k in cached
} | [
"def",
"many_from_cache",
"(",
"self",
",",
"preferences",
")",
":",
"keys",
"=",
"{",
"p",
":",
"self",
".",
"get_cache_key",
"(",
"p",
".",
"section",
".",
"name",
",",
"p",
".",
"name",
")",
"for",
"p",
"in",
"preferences",
"}",
"cached",
"=",
"self",
".",
"cache",
".",
"get_many",
"(",
"list",
"(",
"keys",
".",
"values",
"(",
")",
")",
")",
"for",
"k",
",",
"v",
"in",
"cached",
".",
"items",
"(",
")",
":",
"# we replace dummy cached values by None here, if needed",
"if",
"v",
"==",
"preferences_settings",
".",
"CACHE_NONE_VALUE",
":",
"cached",
"[",
"k",
"]",
"=",
"None",
"# we have to remap returned value since the underlying cached keys",
"# are not usable for an end user",
"return",
"{",
"p",
".",
"identifier",
"(",
")",
":",
"p",
".",
"serializer",
".",
"deserialize",
"(",
"cached",
"[",
"k",
"]",
")",
"for",
"p",
",",
"k",
"in",
"keys",
".",
"items",
"(",
")",
"if",
"k",
"in",
"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 the cache once for all existing preferences
a = self.many_from_cache(preferences)
if len(a) == len(preferences):
return a # avoid database hit if not necessary
# then we fill those that miss, but exist in the database
# (just hit the database for all of them, filtering is complicated, and
# in most cases you'd need to grab the majority of them anyway)
a.update(self.load_from_db(cache=True))
return a | 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 the cache once for all existing preferences
a = self.many_from_cache(preferences)
if len(a) == len(preferences):
return a # avoid database hit if not necessary
# then we fill those that miss, but exist in the database
# (just hit the database for all of them, filtering is complicated, and
# in most cases you'd need to grab the majority of them anyway)
a.update(self.load_from_db(cache=True))
return a | [
"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 existing preferences",
"a",
"=",
"self",
".",
"many_from_cache",
"(",
"preferences",
")",
"if",
"len",
"(",
"a",
")",
"==",
"len",
"(",
"preferences",
")",
":",
"return",
"a",
"# avoid database hit if not necessary",
"# then we fill those that miss, but exist in the database",
"# (just hit the database for all of them, filtering is complicated, and",
"# in most cases you'd need to grab the majority of them anyway)",
"a",
".",
"update",
"(",
"self",
".",
"load_from_db",
"(",
"cache",
"=",
"True",
")",
")",
"return",
"a"
] | 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.identifier()]
except KeyError:
db_pref = self.create_db_pref(
section=preference.section.name,
name=preference.name,
value=preference.get('default'))
else:
# cache if create_db_pref() hasn't already done so
if cache:
self.to_cache(db_pref)
a[preference.identifier()] = db_pref.value
return a | 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.identifier()]
except KeyError:
db_pref = self.create_db_pref(
section=preference.section.name,
name=preference.name,
value=preference.get('default'))
else:
# cache if create_db_pref() hasn't already done so
if cache:
self.to_cache(db_pref)
a[preference.identifier()] = db_pref.value
return a | [
"def",
"load_from_db",
"(",
"self",
",",
"cache",
"=",
"False",
")",
":",
"a",
"=",
"{",
"}",
"db_prefs",
"=",
"{",
"p",
".",
"preference",
".",
"identifier",
"(",
")",
":",
"p",
"for",
"p",
"in",
"self",
".",
"queryset",
"}",
"for",
"preference",
"in",
"self",
".",
"registry",
".",
"preferences",
"(",
")",
":",
"try",
":",
"db_pref",
"=",
"db_prefs",
"[",
"preference",
".",
"identifier",
"(",
")",
"]",
"except",
"KeyError",
":",
"db_pref",
"=",
"self",
".",
"create_db_pref",
"(",
"section",
"=",
"preference",
".",
"section",
".",
"name",
",",
"name",
"=",
"preference",
".",
"name",
",",
"value",
"=",
"preference",
".",
"get",
"(",
"'default'",
")",
")",
"else",
":",
"# cache if create_db_pref() hasn't already done so",
"if",
"cache",
":",
"self",
".",
"to_cache",
"(",
"db_pref",
")",
"a",
"[",
"preference",
".",
"identifier",
"(",
")",
"]",
"=",
"db_pref",
".",
"value",
"return",
"a"
] | 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",
")",
"field",
".",
"run_validators",
"(",
"value",
")",
"return",
"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
raise cls.exception("Cannot deserialize value {0} tostring".format(value)) | 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
raise cls.exception("Cannot deserialize value {0} tostring".format(value)) | [
"def",
"to_python",
"(",
"cls",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
":",
"return",
"''",
"try",
":",
"return",
"str",
"(",
"value",
")",
"except",
":",
"pass",
"try",
":",
"return",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"except",
":",
"pass",
"raise",
"cls",
".",
"exception",
"(",
"\"Cannot deserialize value {0} tostring\"",
".",
"format",
"(",
"value",
")",
")"
] | 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:
instance_class = model._meta.get_field('instance').remote_field.model
if isinstance(instance, instance_class):
return registry
except FieldDoesNotExist: # global preferences
pass
return None | 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:
instance_class = model._meta.get_field('instance').remote_field.model
if isinstance(instance, instance_class):
return registry
except FieldDoesNotExist: # global preferences
pass
return None | [
"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",
"(",
")",
":",
"try",
":",
"instance_class",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"'instance'",
")",
".",
"remote_field",
".",
"model",
"if",
"isinstance",
"(",
"instance",
",",
"instance_class",
")",
":",
"return",
"registry",
"except",
"FieldDoesNotExist",
":",
"# global preferences",
"pass",
"return",
"None"
] | 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.section
try:
self[preference.section.name][preference.name] = preference
except KeyError:
self[preference.section.name] = collections.OrderedDict()
self[preference.section.name][preference.name] = preference
return preference_class | 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.section
try:
self[preference.section.name][preference.name] = preference
except KeyError:
self[preference.section.name] = collections.OrderedDict()
self[preference.section.name][preference.name] = preference
return preference_class | [
"def",
"register",
"(",
"self",
",",
"preference_class",
")",
":",
"preference",
"=",
"preference_class",
"(",
"registry",
"=",
"self",
")",
"self",
".",
"section_objects",
"[",
"preference",
".",
"section",
".",
"name",
"]",
"=",
"preference",
".",
"section",
"try",
":",
"self",
"[",
"preference",
".",
"section",
".",
"name",
"]",
"[",
"preference",
".",
"name",
"]",
"=",
"preference",
"except",
"KeyError",
":",
"self",
"[",
"preference",
".",
"section",
".",
"name",
"]",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"self",
"[",
"preference",
".",
"section",
".",
"name",
"]",
"[",
"preference",
".",
"name",
"]",
"=",
"preference",
"return",
"preference_class"
] | 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 you want to avoid providing section param
:type name: str.
:param fallback: Should we return a dummy preference object instead of raising an error if no preference is found?
:type name: bool.
:return: a :py:class:`prefs.BasePreference` instance
"""
# try dotted notation
try:
_section, name = name.split(
preferences_settings.SECTION_KEY_SEPARATOR)
return self[_section][name]
except ValueError:
pass
# use standard params
try:
return self[section][name]
except KeyError:
if fallback:
return self._fallback(section_name=section, pref_name=name)
raise NotFoundInRegistry("No such preference in {0} with section={1} and name={2}".format(
self.__class__.__name__, section, name)) | 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 you want to avoid providing section param
:type name: str.
:param fallback: Should we return a dummy preference object instead of raising an error if no preference is found?
:type name: bool.
:return: a :py:class:`prefs.BasePreference` instance
"""
# try dotted notation
try:
_section, name = name.split(
preferences_settings.SECTION_KEY_SEPARATOR)
return self[_section][name]
except ValueError:
pass
# use standard params
try:
return self[section][name]
except KeyError:
if fallback:
return self._fallback(section_name=section, pref_name=name)
raise NotFoundInRegistry("No such preference in {0} with section={1} and name={2}".format(
self.__class__.__name__, section, name)) | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"section",
"=",
"None",
",",
"fallback",
"=",
"False",
")",
":",
"# try dotted notation",
"try",
":",
"_section",
",",
"name",
"=",
"name",
".",
"split",
"(",
"preferences_settings",
".",
"SECTION_KEY_SEPARATOR",
")",
"return",
"self",
"[",
"_section",
"]",
"[",
"name",
"]",
"except",
"ValueError",
":",
"pass",
"# use standard params",
"try",
":",
"return",
"self",
"[",
"section",
"]",
"[",
"name",
"]",
"except",
"KeyError",
":",
"if",
"fallback",
":",
"return",
"self",
".",
"_fallback",
"(",
"section_name",
"=",
"section",
",",
"pref_name",
"=",
"name",
")",
"raise",
"NotFoundInRegistry",
"(",
"\"No such preference in {0} with section={1} and name={2}\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"section",
",",
"name",
")",
")"
] | 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.
:param fallback: Should we return a dummy preference object instead of raising an error if no preference is found?
:type name: bool.
:return: a :py:class:`prefs.BasePreference` instance | [
"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.BasePreference` instances
"""
if section is None:
return [self[section][name] for section in self for name in self[section]]
else:
return [self[section][name] for name in self[section]] | 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.BasePreference` instances
"""
if section is None:
return [self[section][name] for section in self for name in self[section]]
else:
return [self[section][name] for name in self[section]] | [
"def",
"preferences",
"(",
"self",
",",
"section",
"=",
"None",
")",
":",
"if",
"section",
"is",
"None",
":",
"return",
"[",
"self",
"[",
"section",
"]",
"[",
"name",
"]",
"for",
"section",
"in",
"self",
"for",
"name",
"in",
"self",
"[",
"section",
"]",
"]",
"else",
":",
"return",
"[",
"self",
"[",
"section",
"]",
"[",
"name",
"]",
"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:
queryset = queryset.filter(section=section)
return queryset | 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:
queryset = queryset.filter(section=section)
return queryset | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"self",
".",
"init_preferences",
"(",
")",
"queryset",
"=",
"super",
"(",
"PreferenceViewSet",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"section",
"=",
"self",
".",
"request",
".",
"query_params",
".",
"get",
"(",
"'section'",
")",
"if",
"section",
":",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"section",
"=",
"section",
")",
"return",
"queryset"
] | 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 = []
payload = request.data
# first, we check updated preferences actually exists in the registry
try:
for identifier, value in payload.items():
try:
preferences.append(
self.queryset.model.registry.get(identifier))
except exceptions.NotFoundInRegistry:
errors[identifier] = 'invalid preference'
except (TypeError, AttributeError):
return Response('invalid payload', status=400)
if errors:
return Response(errors, status=400)
# now, we generate an optimized Q objects to retrieve all matching
# preferences at once from database
queries = [
Q(section=p.section.name, name=p.name)
for p in preferences
]
query = queries[0]
for q in queries[1:]:
query |= q
preferences_qs = self.get_queryset().filter(query)
# next, we generate a serializer for each database preference
serializer_objects = []
for p in preferences_qs:
s = self.get_serializer_class()(
p, data={'value': payload[p.preference.identifier()]})
serializer_objects.append(s)
validation_errors = {}
# we check if any serializer is invalid
for s in serializer_objects:
if s.is_valid():
continue
validation_errors[s.instance.preference.identifier()] = s.errors
if validation_errors:
return Response(validation_errors, status=400)
for s in serializer_objects:
s.save()
return Response(
[s.data for s in serializer_objects],
status=200,
) | 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 = []
payload = request.data
# first, we check updated preferences actually exists in the registry
try:
for identifier, value in payload.items():
try:
preferences.append(
self.queryset.model.registry.get(identifier))
except exceptions.NotFoundInRegistry:
errors[identifier] = 'invalid preference'
except (TypeError, AttributeError):
return Response('invalid payload', status=400)
if errors:
return Response(errors, status=400)
# now, we generate an optimized Q objects to retrieve all matching
# preferences at once from database
queries = [
Q(section=p.section.name, name=p.name)
for p in preferences
]
query = queries[0]
for q in queries[1:]:
query |= q
preferences_qs = self.get_queryset().filter(query)
# next, we generate a serializer for each database preference
serializer_objects = []
for p in preferences_qs:
s = self.get_serializer_class()(
p, data={'value': payload[p.preference.identifier()]})
serializer_objects.append(s)
validation_errors = {}
# we check if any serializer is invalid
for s in serializer_objects:
if s.is_valid():
continue
validation_errors[s.instance.preference.identifier()] = s.errors
if validation_errors:
return Response(validation_errors, status=400)
for s in serializer_objects:
s.save()
return Response(
[s.data for s in serializer_objects],
status=200,
) | [
"def",
"bulk",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"manager",
"=",
"self",
".",
"get_manager",
"(",
")",
"errors",
"=",
"{",
"}",
"preferences",
"=",
"[",
"]",
"payload",
"=",
"request",
".",
"data",
"# first, we check updated preferences actually exists in the registry",
"try",
":",
"for",
"identifier",
",",
"value",
"in",
"payload",
".",
"items",
"(",
")",
":",
"try",
":",
"preferences",
".",
"append",
"(",
"self",
".",
"queryset",
".",
"model",
".",
"registry",
".",
"get",
"(",
"identifier",
")",
")",
"except",
"exceptions",
".",
"NotFoundInRegistry",
":",
"errors",
"[",
"identifier",
"]",
"=",
"'invalid preference'",
"except",
"(",
"TypeError",
",",
"AttributeError",
")",
":",
"return",
"Response",
"(",
"'invalid payload'",
",",
"status",
"=",
"400",
")",
"if",
"errors",
":",
"return",
"Response",
"(",
"errors",
",",
"status",
"=",
"400",
")",
"# now, we generate an optimized Q objects to retrieve all matching",
"# preferences at once from database",
"queries",
"=",
"[",
"Q",
"(",
"section",
"=",
"p",
".",
"section",
".",
"name",
",",
"name",
"=",
"p",
".",
"name",
")",
"for",
"p",
"in",
"preferences",
"]",
"query",
"=",
"queries",
"[",
"0",
"]",
"for",
"q",
"in",
"queries",
"[",
"1",
":",
"]",
":",
"query",
"|=",
"q",
"preferences_qs",
"=",
"self",
".",
"get_queryset",
"(",
")",
".",
"filter",
"(",
"query",
")",
"# next, we generate a serializer for each database preference",
"serializer_objects",
"=",
"[",
"]",
"for",
"p",
"in",
"preferences_qs",
":",
"s",
"=",
"self",
".",
"get_serializer_class",
"(",
")",
"(",
"p",
",",
"data",
"=",
"{",
"'value'",
":",
"payload",
"[",
"p",
".",
"preference",
".",
"identifier",
"(",
")",
"]",
"}",
")",
"serializer_objects",
".",
"append",
"(",
"s",
")",
"validation_errors",
"=",
"{",
"}",
"# we check if any serializer is invalid",
"for",
"s",
"in",
"serializer_objects",
":",
"if",
"s",
".",
"is_valid",
"(",
")",
":",
"continue",
"validation_errors",
"[",
"s",
".",
"instance",
".",
"preference",
".",
"identifier",
"(",
")",
"]",
"=",
"s",
".",
"errors",
"if",
"validation_errors",
":",
"return",
"Response",
"(",
"validation_errors",
",",
"status",
"=",
"400",
")",
"for",
"s",
"in",
"serializer_objects",
":",
"s",
".",
"save",
"(",
")",
"return",
"Response",
"(",
"[",
"s",
".",
"data",
"for",
"s",
"in",
"serializer_objects",
"]",
",",
"status",
"=",
"200",
",",
")"
] | 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:
pref = p.registry.get(section=p.section, name=p.name, fallback=False)
except NotFoundInRegistry:
p.delete()
deleted.append(p)
return deleted | 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:
pref = p.registry.get(section=p.section, name=p.name, fallback=False)
except NotFoundInRegistry:
p.delete()
deleted.append(p)
return deleted | [
"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",
".",
"get",
"(",
"section",
"=",
"p",
".",
"section",
",",
"name",
"=",
"p",
".",
"name",
",",
"fallback",
"=",
"False",
")",
"except",
"NotFoundInRegistry",
":",
"p",
".",
"delete",
"(",
")",
"deleted",
".",
"append",
"(",
"p",
")",
"return",
"deleted"
] | 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\
.filter(name=preference.name,
section=preference.section)
related_preferences = queryset.filter(
raw_value=preference.serializer.serialize(instance))
related_preferences.delete()
return delete_related_preferences | 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\
.filter(name=preference.name,
section=preference.section)
related_preferences = queryset.filter(
raw_value=preference.serializer.serialize(instance))
related_preferences.delete()
return delete_related_preferences | [
"def",
"create_deletion_handler",
"(",
"preference",
")",
":",
"def",
"delete_related_preferences",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"preference",
".",
"registry",
".",
"preference_model",
".",
"objects",
".",
"filter",
"(",
"name",
"=",
"preference",
".",
"name",
",",
"section",
"=",
"preference",
".",
"section",
")",
"related_preferences",
"=",
"queryset",
".",
"filter",
"(",
"raw_value",
"=",
"preference",
".",
"serializer",
".",
"serialize",
"(",
"instance",
")",
")",
"related_preferences",
".",
"delete",
"(",
")",
"return",
"delete_related_preferences"
] | 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
- :py:attr:`instance.help_text` for the field help text
- :py:attr:`instance.widget` for the field widget
- :py:attr:`instance.required` defined if the value is required or not
- :py:attr:`instance.initial` defined if the initial value
"""
kwargs = self.field_kwargs.copy()
kwargs.setdefault('label', self.get('verbose_name'))
kwargs.setdefault('help_text', self.get('help_text'))
kwargs.setdefault('widget', self.get('widget'))
kwargs.setdefault('required', self.get('required'))
kwargs.setdefault('initial', self.initial)
kwargs.setdefault('validators', [])
kwargs['validators'].append(self.validate)
return kwargs | 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
- :py:attr:`instance.help_text` for the field help text
- :py:attr:`instance.widget` for the field widget
- :py:attr:`instance.required` defined if the value is required or not
- :py:attr:`instance.initial` defined if the initial value
"""
kwargs = self.field_kwargs.copy()
kwargs.setdefault('label', self.get('verbose_name'))
kwargs.setdefault('help_text', self.get('help_text'))
kwargs.setdefault('widget', self.get('widget'))
kwargs.setdefault('required', self.get('required'))
kwargs.setdefault('initial', self.initial)
kwargs.setdefault('validators', [])
kwargs['validators'].append(self.validate)
return kwargs | [
"def",
"get_field_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"self",
".",
"field_kwargs",
".",
"copy",
"(",
")",
"kwargs",
".",
"setdefault",
"(",
"'label'",
",",
"self",
".",
"get",
"(",
"'verbose_name'",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"'help_text'",
",",
"self",
".",
"get",
"(",
"'help_text'",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"'widget'",
",",
"self",
".",
"get",
"(",
"'widget'",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"'required'",
",",
"self",
".",
"get",
"(",
"'required'",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"'initial'",
",",
"self",
".",
"initial",
")",
"kwargs",
".",
"setdefault",
"(",
"'validators'",
",",
"[",
"]",
")",
"kwargs",
"[",
"'validators'",
"]",
".",
"append",
"(",
"self",
".",
"validate",
")",
"return",
"kwargs"
] | 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 field help text
- :py:attr:`instance.widget` for the field widget
- :py:attr:`instance.required` defined if the value is required or not
- :py:attr:`instance.initial` defined if the initial value | [
"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': {
'class': field.widget.__class__.__name__
}
}
try:
d['input_type'] = field.widget.input_type
except AttributeError:
# some widgets, such as Select do not have an input type
# in django < 1.11
d['input_type'] = None
return d | 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': {
'class': field.widget.__class__.__name__
}
}
try:
d['input_type'] = field.widget.input_type
except AttributeError:
# some widgets, such as Select do not have an input type
# in django < 1.11
d['input_type'] = None
return d | [
"def",
"get_api_field_data",
"(",
"self",
")",
":",
"field",
"=",
"self",
".",
"setup_field",
"(",
")",
"d",
"=",
"{",
"'class'",
":",
"field",
".",
"__class__",
".",
"__name__",
",",
"'widget'",
":",
"{",
"'class'",
":",
"field",
".",
"widget",
".",
"__class__",
".",
"__name__",
"}",
"}",
"try",
":",
"d",
"[",
"'input_type'",
"]",
"=",
"field",
".",
"widget",
".",
"input_type",
"except",
"AttributeError",
":",
"# some widgets, such as Select do not have an input type",
"# in django < 1.11",
"d",
"[",
"'input_type'",
"]",
"=",
"None",
"return",
"d"
] | 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"Try running 'pip install {name}'\n"
)
out.error(msg_error)
raise SystemExit(NO_COMMITIZEN_FOUND)
else:
return _cz | 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"Try running 'pip install {name}'\n"
)
out.error(msg_error)
raise SystemExit(NO_COMMITIZEN_FOUND)
else:
return _cz | [
"def",
"commiter_factory",
"(",
"config",
":",
"dict",
")",
"->",
"BaseCommitizen",
":",
"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\"Try running 'pip install {name}'\\n\"",
")",
"out",
".",
"error",
"(",
"msg_error",
")",
"raise",
"SystemExit",
"(",
"NO_COMMITIZEN_FOUND",
")",
"else",
":",
"return",
"_cz"
] | 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/
Example:
PATCH 1.0.0 -> 1.0.1
MINOR 1.0.0 -> 1.1.0
MAJOR 1.0.0 -> 2.0.0
"""
pre_version = prerelease_generator(current_version, prerelease=prerelease)
semver = semver_generator(current_version, increment=increment)
# TODO: post version
# TODO: dev version
return Version(f"{semver}{pre_version}") | 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/
Example:
PATCH 1.0.0 -> 1.0.1
MINOR 1.0.0 -> 1.1.0
MAJOR 1.0.0 -> 2.0.0
"""
pre_version = prerelease_generator(current_version, prerelease=prerelease)
semver = semver_generator(current_version, increment=increment)
# TODO: post version
# TODO: dev version
return Version(f"{semver}{pre_version}") | [
"def",
"generate_version",
"(",
"current_version",
":",
"str",
",",
"increment",
":",
"str",
",",
"prerelease",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Version",
":",
"pre_version",
"=",
"prerelease_generator",
"(",
"current_version",
",",
"prerelease",
"=",
"prerelease",
")",
"semver",
"=",
"semver_generator",
"(",
"current_version",
",",
"increment",
"=",
"increment",
")",
"# TODO: post version",
"# TODO: dev version",
"return",
"Version",
"(",
"f\"{semver}{pre_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`.
"""
for filepath in files:
# Read in the file
with open(filepath, "r") as file:
filedata = file.read()
# Replace the target string
filedata = filedata.replace(current_version, new_version)
# Write the file out again
with open(filepath, "w") as file:
file.write(filedata) | 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`.
"""
for filepath in files:
# Read in the file
with open(filepath, "r") as file:
filedata = file.read()
# Replace the target string
filedata = filedata.replace(current_version, new_version)
# Write the file out again
with open(filepath, "w") as file:
file.write(filedata) | [
"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",
"file",
":",
"filedata",
"=",
"file",
".",
"read",
"(",
")",
"# Replace the target string",
"filedata",
"=",
"filedata",
".",
"replace",
"(",
"current_version",
",",
"new_version",
")",
"# Write the file out again",
"with",
"open",
"(",
"filepath",
",",
"\"w\"",
")",
"as",
"file",
":",
"file",
".",
"write",
"(",
"filedata",
")"
] | 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.0a0 |
"""
if isinstance(version, str):
version = Version(version)
if not tag_format:
return version.public
major, minor, patch = version.release
prerelease = ""
if version.is_prerelease:
prerelease = f"{version.pre[0]}{version.pre[1]}"
t = Template(tag_format)
return t.safe_substitute(
version=version, major=major, minor=minor, patch=patch, prerelease=prerelease
) | 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.0a0 |
"""
if isinstance(version, str):
version = Version(version)
if not tag_format:
return version.public
major, minor, patch = version.release
prerelease = ""
if version.is_prerelease:
prerelease = f"{version.pre[0]}{version.pre[1]}"
t = Template(tag_format)
return t.safe_substitute(
version=version, major=major, minor=minor, patch=patch, prerelease=prerelease
) | [
"def",
"create_tag",
"(",
"version",
":",
"Union",
"[",
"Version",
",",
"str",
"]",
",",
"tag_format",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"version",
",",
"str",
")",
":",
"version",
"=",
"Version",
"(",
"version",
")",
"if",
"not",
"tag_format",
":",
"return",
"version",
".",
"public",
"major",
",",
"minor",
",",
"patch",
"=",
"version",
".",
"release",
"prerelease",
"=",
"\"\"",
"if",
"version",
".",
"is_prerelease",
":",
"prerelease",
"=",
"f\"{version.pre[0]}{version.pre[1]}\"",
"t",
"=",
"Template",
"(",
"tag_format",
")",
"return",
"t",
".",
"safe_substitute",
"(",
"version",
"=",
"version",
",",
"major",
"=",
"major",
",",
"minor",
"=",
"minor",
",",
"patch",
"=",
"patch",
",",
"prerelease",
"=",
"prerelease",
")"
] | 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",
":",
"return",
"{",
"}"
] | 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_value=True)
config.read_string(data)
try:
_data: dict = dict(config["commitizen"])
if "files" in _data:
files = _data["files"]
_f = json.loads(files)
_data.update({"files": _f})
return _data
except KeyError:
return {} | 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_value=True)
config.read_string(data)
try:
_data: dict = dict(config["commitizen"])
if "files" in _data:
files = _data["files"]
_f = json.loads(files)
_data.update({"files": _f})
return _data
except KeyError:
return {} | [
"def",
"read_raw_parser_conf",
"(",
"data",
":",
"str",
")",
"->",
"dict",
":",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"config",
".",
"read_string",
"(",
"data",
")",
"try",
":",
"_data",
":",
"dict",
"=",
"dict",
"(",
"config",
"[",
"\"commitizen\"",
"]",
")",
"if",
"\"files\"",
"in",
"_data",
":",
"files",
"=",
"_data",
"[",
"\"files\"",
"]",
"_f",
"=",
"json",
".",
"loads",
"(",
"files",
")",
"_data",
".",
"update",
"(",
"{",
"\"files\"",
":",
"_f",
"}",
")",
"return",
"_data",
"except",
"KeyError",
":",
"return",
"{",
"}"
] | 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())
parser["tool"]["commitizen"][key] = value
with open(_conf.path, "w") as f:
f.write(parser.as_string())
else:
parser = configparser.ConfigParser()
parser.read(_conf.path)
parser["commitizen"][key] = value
with open(_conf.path, "w") as f:
parser.write(f)
return _conf.config | 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())
parser["tool"]["commitizen"][key] = value
with open(_conf.path, "w") as f:
f.write(parser.as_string())
else:
parser = configparser.ConfigParser()
parser.read(_conf.path)
parser["commitizen"][key] = value
with open(_conf.path, "w") as f:
parser.write(f)
return _conf.config | [
"def",
"set_key",
"(",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"dict",
":",
"if",
"not",
"_conf",
".",
"path",
":",
"return",
"{",
"}",
"if",
"\"toml\"",
"in",
"_conf",
".",
"path",
":",
"with",
"open",
"(",
"_conf",
".",
"path",
",",
"\"r\"",
")",
"as",
"f",
":",
"parser",
"=",
"parse",
"(",
"f",
".",
"read",
"(",
")",
")",
"parser",
"[",
"\"tool\"",
"]",
"[",
"\"commitizen\"",
"]",
"[",
"key",
"]",
"=",
"value",
"with",
"open",
"(",
"_conf",
".",
"path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"parser",
".",
"as_string",
"(",
")",
")",
"else",
":",
"parser",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"parser",
".",
"read",
"(",
"_conf",
".",
"path",
")",
"parser",
"[",
"\"commitizen\"",
"]",
"[",
"key",
"]",
"=",
"value",
"with",
"open",
"(",
"_conf",
".",
"path",
",",
"\"w\"",
")",
"as",
"f",
":",
"parser",
".",
"write",
"(",
"f",
")",
"return",
"_conf",
".",
"config"
] | 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",
".",
"fp_extra",
"=",
"None",
"self",
".",
"ctype",
"=",
"None"
] | 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 = 'gzip'
elif ext == '.bz2':
self.ctype = 'bzip2'
elif ext in ('.xz', '.lzma'):
self.ctype = 'lzma'
else:
self.ctype = None | 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 = 'gzip'
elif ext == '.bz2':
self.ctype = 'bzip2'
elif ext in ('.xz', '.lzma'):
self.ctype = 'lzma'
else:
self.ctype = None | [
"def",
"get_compression_type",
"(",
"self",
",",
"file_name",
")",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"[",
"1",
"]",
"if",
"ext",
"==",
"'.gz'",
":",
"self",
".",
"ctype",
"=",
"'gzip'",
"elif",
"ext",
"==",
"'.bz2'",
":",
"self",
".",
"ctype",
"=",
"'bzip2'",
"elif",
"ext",
"in",
"(",
"'.xz'",
",",
"'.lzma'",
")",
":",
"self",
".",
"ctype",
"=",
"'lzma'",
"else",
":",
"self",
".",
"ctype",
"=",
"None"
] | 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(solver)
compile_solver(solver) | 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(solver)
compile_solver(solver) | [
"def",
"do",
"(",
"to_install",
")",
":",
"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",
"(",
"solver",
")",
"compile_solver",
"(",
"solver",
")"
] | 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)
for fnames in to_move[solver]:
old = os.path.join(root, fnames[0])
new = os.path.join(root, fnames[1])
os.rename(old, new)
for f in to_remove[solver]:
f = os.path.join(root, f)
if os.path.isdir(f):
shutil.rmtree(f)
else:
os.remove(f) | 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)
for fnames in to_move[solver]:
old = os.path.join(root, fnames[0])
new = os.path.join(root, fnames[1])
os.rename(old, new)
for f in to_remove[solver]:
f = os.path.join(root, f)
if os.path.isdir(f):
shutil.rmtree(f)
else:
os.remove(f) | [
"def",
"adapt_files",
"(",
"solver",
")",
":",
"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",
")",
"for",
"fnames",
"in",
"to_move",
"[",
"solver",
"]",
":",
"old",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"fnames",
"[",
"0",
"]",
")",
"new",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"fnames",
"[",
"1",
"]",
")",
"os",
".",
"rename",
"(",
"old",
",",
"new",
")",
"for",
"f",
"in",
"to_remove",
"[",
"solver",
"]",
":",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"f",
")",
":",
"shutil",
".",
"rmtree",
"(",
"f",
")",
"else",
":",
"os",
".",
"remove",
"(",
"f",
")"
] | 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*. The method
makes sure no clash occurs, i.e. it maps the original variables
used in the new problem clauses to the newly introduced auxiliary
variables (see :func:`add_clause`).
Given an integer literal, a fresh literal is returned. The returned
integer has the same sign as the input literal.
:param l: literal to map
:type l: int
:rtype: int
"""
v = abs(l)
if v in self.vmap.e2i:
return int(copysign(self.vmap.e2i[v], l))
else:
self.topv += 1
self.vmap.e2i[v] = self.topv
self.vmap.i2e[self.topv] = v
return int(copysign(self.topv, l)) | 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*. The method
makes sure no clash occurs, i.e. it maps the original variables
used in the new problem clauses to the newly introduced auxiliary
variables (see :func:`add_clause`).
Given an integer literal, a fresh literal is returned. The returned
integer has the same sign as the input literal.
:param l: literal to map
:type l: int
:rtype: int
"""
v = abs(l)
if v in self.vmap.e2i:
return int(copysign(self.vmap.e2i[v], l))
else:
self.topv += 1
self.vmap.e2i[v] = self.topv
self.vmap.i2e[self.topv] = v
return int(copysign(self.topv, l)) | [
"def",
"_map_extlit",
"(",
"self",
",",
"l",
")",
":",
"v",
"=",
"abs",
"(",
"l",
")",
"if",
"v",
"in",
"self",
".",
"vmap",
".",
"e2i",
":",
"return",
"int",
"(",
"copysign",
"(",
"self",
".",
"vmap",
".",
"e2i",
"[",
"v",
"]",
",",
"l",
")",
")",
"else",
":",
"self",
".",
"topv",
"+=",
"1",
"self",
".",
"vmap",
".",
"e2i",
"[",
"v",
"]",
"=",
"self",
".",
"topv",
"self",
".",
"vmap",
".",
"i2e",
"[",
"self",
".",
"topv",
"]",
"=",
"v",
"return",
"int",
"(",
"copysign",
"(",
"self",
".",
"topv",
",",
"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 occurs, i.e. it maps the original variables
used in the new problem clauses to the newly introduced auxiliary
variables (see :func:`add_clause`).
Given an integer literal, a fresh literal is returned. The returned
integer has the same sign as the input literal.
:param l: literal to map
:type l: int
:rtype: int | [
"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 MCS enumerator.
:param bootstrap_with: input set of sets to hit
:type bootstrap_with: iterable(iterable(obj))
"""
# formula encoding the sets to hit
formula = WCNF()
# hard clauses
for to_hit in bootstrap_with:
to_hit = list(map(lambda obj: self.idpool.id(obj), to_hit))
formula.append(to_hit)
# soft clauses
for obj_id in six.iterkeys(self.idpool.id2obj):
formula.append([-obj_id], weight=1)
if self.htype == 'rc2':
# using the RC2-A options from MaxSAT evaluation 2018
self.oracle = RC2(formula, solver=self.solver, adapt=False,
exhaust=True, trim=5)
elif self.htype == 'lbx':
self.oracle = LBX(formula, solver_name=self.solver, use_cld=True)
else:
self.oracle = MCSls(formula, solver_name=self.solver, use_cld=True) | 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 MCS enumerator.
:param bootstrap_with: input set of sets to hit
:type bootstrap_with: iterable(iterable(obj))
"""
# formula encoding the sets to hit
formula = WCNF()
# hard clauses
for to_hit in bootstrap_with:
to_hit = list(map(lambda obj: self.idpool.id(obj), to_hit))
formula.append(to_hit)
# soft clauses
for obj_id in six.iterkeys(self.idpool.id2obj):
formula.append([-obj_id], weight=1)
if self.htype == 'rc2':
# using the RC2-A options from MaxSAT evaluation 2018
self.oracle = RC2(formula, solver=self.solver, adapt=False,
exhaust=True, trim=5)
elif self.htype == 'lbx':
self.oracle = LBX(formula, solver_name=self.solver, use_cld=True)
else:
self.oracle = MCSls(formula, solver_name=self.solver, use_cld=True) | [
"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",
":",
"self",
".",
"idpool",
".",
"id",
"(",
"obj",
")",
",",
"to_hit",
")",
")",
"formula",
".",
"append",
"(",
"to_hit",
")",
"# soft clauses",
"for",
"obj_id",
"in",
"six",
".",
"iterkeys",
"(",
"self",
".",
"idpool",
".",
"id2obj",
")",
":",
"formula",
".",
"append",
"(",
"[",
"-",
"obj_id",
"]",
",",
"weight",
"=",
"1",
")",
"if",
"self",
".",
"htype",
"==",
"'rc2'",
":",
"# using the RC2-A options from MaxSAT evaluation 2018",
"self",
".",
"oracle",
"=",
"RC2",
"(",
"formula",
",",
"solver",
"=",
"self",
".",
"solver",
",",
"adapt",
"=",
"False",
",",
"exhaust",
"=",
"True",
",",
"trim",
"=",
"5",
")",
"elif",
"self",
".",
"htype",
"==",
"'lbx'",
":",
"self",
".",
"oracle",
"=",
"LBX",
"(",
"formula",
",",
"solver_name",
"=",
"self",
".",
"solver",
",",
"use_cld",
"=",
"True",
")",
"else",
":",
"self",
".",
"oracle",
"=",
"MCSls",
"(",
"formula",
",",
"solver_name",
"=",
"self",
".",
"solver",
",",
"use_cld",
"=",
"True",
")"
] | 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: input set of sets to hit
:type bootstrap_with: iterable(iterable(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",
"."
] | 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(obj)
"""
model = self.oracle.compute()
if model:
if self.htype == 'rc2':
# extracting a hitting set
self.hset = filter(lambda v: v > 0, model)
else:
self.hset = model
return list(map(lambda vid: self.idpool.id2obj[vid], self.hset)) | 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(obj)
"""
model = self.oracle.compute()
if model:
if self.htype == 'rc2':
# extracting a hitting set
self.hset = filter(lambda v: v > 0, model)
else:
self.hset = model
return list(map(lambda vid: self.idpool.id2obj[vid], self.hset)) | [
"def",
"get",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"oracle",
".",
"compute",
"(",
")",
"if",
"model",
":",
"if",
"self",
".",
"htype",
"==",
"'rc2'",
":",
"# extracting a hitting set",
"self",
".",
"hset",
"=",
"filter",
"(",
"lambda",
"v",
":",
"v",
">",
"0",
",",
"model",
")",
"else",
":",
"self",
".",
"hset",
"=",
"model",
"return",
"list",
"(",
"map",
"(",
"lambda",
"vid",
":",
"self",
".",
"idpool",
".",
"id2obj",
"[",
"vid",
"]",
",",
"self",
".",
"hset",
")",
")"
] | 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",
"mapped",
"back",
"to",
"objects",
"of",
"the",
"problem",
"domain",
"."
] | 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 to_hit: iterable(obj)
"""
# translating objects to variables
to_hit = list(map(lambda obj: self.idpool.id(obj), to_hit))
# a soft clause should be added for each new object
new_obj = list(filter(lambda vid: vid not in self.oracle.vmap.e2i, to_hit))
# new hard clause
self.oracle.add_clause(to_hit)
# new soft clauses
for vid in new_obj:
self.oracle.add_clause([-vid], 1) | 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 to_hit: iterable(obj)
"""
# translating objects to variables
to_hit = list(map(lambda obj: self.idpool.id(obj), to_hit))
# a soft clause should be added for each new object
new_obj = list(filter(lambda vid: vid not in self.oracle.vmap.e2i, to_hit))
# new hard clause
self.oracle.add_clause(to_hit)
# new soft clauses
for vid in new_obj:
self.oracle.add_clause([-vid], 1) | [
"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 added for each new object",
"new_obj",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"vid",
":",
"vid",
"not",
"in",
"self",
".",
"oracle",
".",
"vmap",
".",
"e2i",
",",
"to_hit",
")",
")",
"# new hard clause",
"self",
".",
"oracle",
".",
"add_clause",
"(",
"to_hit",
")",
"# new soft clauses",
"for",
"vid",
"in",
"new_obj",
":",
"self",
".",
"oracle",
".",
"add_clause",
"(",
"[",
"-",
"vid",
"]",
",",
"1",
")"
] | 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",
"MaxSAT",
"problem",
"formulation",
"."
] | 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 oracle.
:param to_block: a set to block
:type to_block: iterable(obj)
"""
# translating objects to variables
to_block = list(map(lambda obj: self.idpool.id(obj), to_block))
# a soft clause should be added for each new object
new_obj = list(filter(lambda vid: vid not in self.oracle.vmap.e2i, to_block))
# new hard clause
self.oracle.add_clause([-vid for vid in to_block])
# new soft clauses
for vid in new_obj:
self.oracle.add_clause([-vid], 1) | 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 oracle.
:param to_block: a set to block
:type to_block: iterable(obj)
"""
# translating objects to variables
to_block = list(map(lambda obj: self.idpool.id(obj), to_block))
# a soft clause should be added for each new object
new_obj = list(filter(lambda vid: vid not in self.oracle.vmap.e2i, to_block))
# new hard clause
self.oracle.add_clause([-vid for vid in to_block])
# new soft clauses
for vid in new_obj:
self.oracle.add_clause([-vid], 1) | [
"def",
"block",
"(",
"self",
",",
"to_block",
")",
":",
"# translating objects to variables",
"to_block",
"=",
"list",
"(",
"map",
"(",
"lambda",
"obj",
":",
"self",
".",
"idpool",
".",
"id",
"(",
"obj",
")",
",",
"to_block",
")",
")",
"# a soft clause should be added for each new object",
"new_obj",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"vid",
":",
"vid",
"not",
"in",
"self",
".",
"oracle",
".",
"vmap",
".",
"e2i",
",",
"to_block",
")",
")",
"# new hard clause",
"self",
".",
"oracle",
".",
"add_clause",
"(",
"[",
"-",
"vid",
"for",
"vid",
"in",
"to_block",
"]",
")",
"# new soft clauses",
"for",
"vid",
"in",
"new_obj",
":",
"self",
".",
"oracle",
".",
"add_clause",
"(",
"[",
"-",
"vid",
"]",
",",
"1",
")"
] | 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
:type to_block: iterable(obj) | [
"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",
"."
] | 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 whether the remaining
clauses of the approximation are unsatisfiable together with the
hard clauses.
Soft clauses are (de)activated using the standard MiniSat-like
assumptions interface [2]_. Each soft clause :math:`c` is augmented
with a selector literal :math:`s`, e.g. :math:`(c) \gets (c \\vee
\\neg{s})`. As a result, clause :math:`c` can be activated by
assuming literal :math:`s`. The over-approximation provided as an
input is specified as a list of selector literals for clauses in
the unsatisfiable core.
.. [2] Niklas Eén, Niklas Sörensson. *Temporal induction by
incremental SAT solving*. Electr. Notes Theor. Comput. Sci.
89(4). 2003. pp. 543-560
:param approx: an over-approximation of an MUS
:type approx: list(int)
Note that the method does not return. Instead, after its execution,
the input over-approximation is refined and contains an MUS.
"""
i = 0
while i < len(approx):
to_test = approx[:i] + approx[(i + 1):]
sel, clid = approx[i], self.vmap[approx[i]]
if self.verbose > 1:
print('c testing clid: {0}'.format(clid), end='')
if self.oracle.solve(assumptions=to_test):
if self.verbose > 1:
print(' -> sat (keeping {0})'.format(clid))
i += 1
else:
if self.verbose > 1:
print(' -> unsat (removing {0})'.format(clid))
approx = to_test | 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 whether the remaining
clauses of the approximation are unsatisfiable together with the
hard clauses.
Soft clauses are (de)activated using the standard MiniSat-like
assumptions interface [2]_. Each soft clause :math:`c` is augmented
with a selector literal :math:`s`, e.g. :math:`(c) \gets (c \\vee
\\neg{s})`. As a result, clause :math:`c` can be activated by
assuming literal :math:`s`. The over-approximation provided as an
input is specified as a list of selector literals for clauses in
the unsatisfiable core.
.. [2] Niklas Eén, Niklas Sörensson. *Temporal induction by
incremental SAT solving*. Electr. Notes Theor. Comput. Sci.
89(4). 2003. pp. 543-560
:param approx: an over-approximation of an MUS
:type approx: list(int)
Note that the method does not return. Instead, after its execution,
the input over-approximation is refined and contains an MUS.
"""
i = 0
while i < len(approx):
to_test = approx[:i] + approx[(i + 1):]
sel, clid = approx[i], self.vmap[approx[i]]
if self.verbose > 1:
print('c testing clid: {0}'.format(clid), end='')
if self.oracle.solve(assumptions=to_test):
if self.verbose > 1:
print(' -> sat (keeping {0})'.format(clid))
i += 1
else:
if self.verbose > 1:
print(' -> unsat (removing {0})'.format(clid))
approx = to_test | [
"def",
"_compute",
"(",
"self",
",",
"approx",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"approx",
")",
":",
"to_test",
"=",
"approx",
"[",
":",
"i",
"]",
"+",
"approx",
"[",
"(",
"i",
"+",
"1",
")",
":",
"]",
"sel",
",",
"clid",
"=",
"approx",
"[",
"i",
"]",
",",
"self",
".",
"vmap",
"[",
"approx",
"[",
"i",
"]",
"]",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print",
"(",
"'c testing clid: {0}'",
".",
"format",
"(",
"clid",
")",
",",
"end",
"=",
"''",
")",
"if",
"self",
".",
"oracle",
".",
"solve",
"(",
"assumptions",
"=",
"to_test",
")",
":",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print",
"(",
"' -> sat (keeping {0})'",
".",
"format",
"(",
"clid",
")",
")",
"i",
"+=",
"1",
"else",
":",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print",
"(",
"' -> unsat (removing {0})'",
".",
"format",
"(",
"clid",
")",
")",
"approx",
"=",
"to_test"
] | 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 approximation are unsatisfiable together with the
hard clauses.
Soft clauses are (de)activated using the standard MiniSat-like
assumptions interface [2]_. Each soft clause :math:`c` is augmented
with a selector literal :math:`s`, e.g. :math:`(c) \gets (c \\vee
\\neg{s})`. As a result, clause :math:`c` can be activated by
assuming literal :math:`s`. The over-approximation provided as an
input is specified as a list of selector literals for clauses in
the unsatisfiable core.
.. [2] Niklas Eén, Niklas Sörensson. *Temporal induction by
incremental SAT solving*. Electr. Notes Theor. Comput. Sci.
89(4). 2003. pp. 543-560
:param approx: an over-approximation of an MUS
:type approx: list(int)
Note that the method does not return. Instead, after its execution,
the input over-approximation is refined and contains an MUS. | [
"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",
"approximation",
"are",
"unsatisfiable",
"together",
"with",
"the",
"hard",
"clauses",
"."
] | 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 over literals.
:param no_return: check solver's internal formula and return the
result, if set to ``False``.
:type clause: iterable(int)
:type no_return: bool
:rtype: bool if ``no_return`` is set to ``False``.
Note that a clause can be either a ``list`` of integers or another
iterable type over integers, e.g. ``tuple`` or ``set`` among
others.
A usage example is the following:
.. code-block:: python
>>> s = Solver(bootstrap_with=[[-1, 2], [-1, -2]])
>>> s.add_clause([1], no_return=False)
False
"""
if self.solver:
res = self.solver.add_clause(clause, no_return)
if not no_return:
return res | 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 over literals.
:param no_return: check solver's internal formula and return the
result, if set to ``False``.
:type clause: iterable(int)
:type no_return: bool
:rtype: bool if ``no_return`` is set to ``False``.
Note that a clause can be either a ``list`` of integers or another
iterable type over integers, e.g. ``tuple`` or ``set`` among
others.
A usage example is the following:
.. code-block:: python
>>> s = Solver(bootstrap_with=[[-1, 2], [-1, -2]])
>>> s.add_clause([1], no_return=False)
False
"""
if self.solver:
res = self.solver.add_clause(clause, no_return)
if not no_return:
return res | [
"def",
"add_clause",
"(",
"self",
",",
"clause",
",",
"no_return",
"=",
"True",
")",
":",
"if",
"self",
".",
"solver",
":",
"res",
"=",
"self",
".",
"solver",
".",
"add_clause",
"(",
"clause",
",",
"no_return",
")",
"if",
"not",
"no_return",
":",
"return",
"res"
] | 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 formula and return the
result, if set to ``False``.
:type clause: iterable(int)
:type no_return: bool
:rtype: bool if ``no_return`` is set to ``False``.
Note that a clause can be either a ``list`` of integers or another
iterable type over integers, e.g. ``tuple`` or ``set`` among
others.
A usage example is the following:
.. code-block:: python
>>> s = Solver(bootstrap_with=[[-1, 2], [-1, -2]])
>>> s.add_clause([1], no_return=False)
False | [
"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",
"."
] | 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 ``False``.
:type formula: iterable(iterable(int))
:type no_return: bool
The ``no_return`` argument is set to ``True`` by default.
:rtype: bool if ``no_return`` is set to ``False``.
.. code-block:: python
>>> cnf = CNF()
... # assume the formula contains clauses
>>> s = Solver()
>>> s.append_formula(cnf.clauses, no_return=False)
True
"""
if self.solver:
res = self.solver.append_formula(formula, no_return)
if not no_return:
return res | 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 ``False``.
:type formula: iterable(iterable(int))
:type no_return: bool
The ``no_return`` argument is set to ``True`` by default.
:rtype: bool if ``no_return`` is set to ``False``.
.. code-block:: python
>>> cnf = CNF()
... # assume the formula contains clauses
>>> s = Solver()
>>> s.append_formula(cnf.clauses, no_return=False)
True
"""
if self.solver:
res = self.solver.append_formula(formula, no_return)
if not no_return:
return res | [
"def",
"append_formula",
"(",
"self",
",",
"formula",
",",
"no_return",
"=",
"True",
")",
":",
"if",
"self",
".",
"solver",
":",
"res",
"=",
"self",
".",
"solver",
".",
"append_formula",
"(",
"formula",
",",
"no_return",
")",
"if",
"not",
"no_return",
":",
"return",
"res"
] | 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))
:type no_return: bool
The ``no_return`` argument is set to ``True`` by default.
:rtype: bool if ``no_return`` is set to ``False``.
.. code-block:: python
>>> cnf = CNF()
... # assume the formula contains clauses
>>> s = Solver()
>>> s.append_formula(cnf.clauses, no_return=False)
True | [
"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.glucose41_solve(self.glucose, assumptions)
if self.use_timer:
self.call_time = time.clock() - start_time
self.accu_time += self.call_time
model = self.get_model()
if model:
self.add_clause([-l for l in model]) # blocking model
yield model
else:
done = True | 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.glucose41_solve(self.glucose, assumptions)
if self.use_timer:
self.call_time = time.clock() - start_time
self.accu_time += self.call_time
model = self.get_model()
if model:
self.add_clause([-l for l in model]) # blocking model
yield model
else:
done = True | [
"def",
"enum_models",
"(",
"self",
",",
"assumptions",
"=",
"[",
"]",
")",
":",
"if",
"self",
".",
"glucose",
":",
"done",
"=",
"False",
"while",
"not",
"done",
":",
"if",
"self",
".",
"use_timer",
":",
"start_time",
"=",
"time",
".",
"clock",
"(",
")",
"self",
".",
"status",
"=",
"pysolvers",
".",
"glucose41_solve",
"(",
"self",
".",
"glucose",
",",
"assumptions",
")",
"if",
"self",
".",
"use_timer",
":",
"self",
".",
"call_time",
"=",
"time",
".",
"clock",
"(",
")",
"-",
"start_time",
"self",
".",
"accu_time",
"+=",
"self",
".",
"call_time",
"model",
"=",
"self",
".",
"get_model",
"(",
")",
"if",
"model",
":",
"self",
".",
"add_clause",
"(",
"[",
"-",
"l",
"for",
"l",
"in",
"model",
"]",
")",
"# blocking model",
"yield",
"model",
"else",
":",
"done",
"=",
"True"
] | 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.signal(signal.SIGINT, signal.SIG_DFL)
st, props = pysolvers.maplechrono_propagate(self.maplesat, assumptions, phase_saving)
# recovering default SIGINT handler
def_sigint_handler = signal.signal(signal.SIGINT, def_sigint_handler)
if self.use_timer:
self.call_time = time.clock() - start_time
self.accu_time += self.call_time
return bool(st), props if props != None else [] | 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.signal(signal.SIGINT, signal.SIG_DFL)
st, props = pysolvers.maplechrono_propagate(self.maplesat, assumptions, phase_saving)
# recovering default SIGINT handler
def_sigint_handler = signal.signal(signal.SIGINT, def_sigint_handler)
if self.use_timer:
self.call_time = time.clock() - start_time
self.accu_time += self.call_time
return bool(st), props if props != None else [] | [
"def",
"propagate",
"(",
"self",
",",
"assumptions",
"=",
"[",
"]",
",",
"phase_saving",
"=",
"0",
")",
":",
"if",
"self",
".",
"maplesat",
":",
"if",
"self",
".",
"use_timer",
":",
"start_time",
"=",
"time",
".",
"clock",
"(",
")",
"# saving default SIGINT handler",
"def_sigint_handler",
"=",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_DFL",
")",
"st",
",",
"props",
"=",
"pysolvers",
".",
"maplechrono_propagate",
"(",
"self",
".",
"maplesat",
",",
"assumptions",
",",
"phase_saving",
")",
"# recovering default SIGINT handler",
"def_sigint_handler",
"=",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"def_sigint_handler",
")",
"if",
"self",
".",
"use_timer",
":",
"self",
".",
"call_time",
"=",
"time",
".",
"clock",
"(",
")",
"-",
"start_time",
"self",
".",
"accu_time",
"+=",
"self",
".",
"call_time",
"return",
"bool",
"(",
"st",
")",
",",
"props",
"if",
"props",
"!=",
"None",
"else",
"[",
"]"
] | 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",
".",
"prfile",
".",
"readlines",
"(",
")",
"]"
] | 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 not no_return:
return res | 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 not no_return:
return res | [
"def",
"add_atmost",
"(",
"self",
",",
"lits",
",",
"k",
",",
"no_return",
"=",
"True",
")",
":",
"if",
"self",
".",
"minicard",
":",
"res",
"=",
"pysolvers",
".",
"minicard_add_am",
"(",
"self",
".",
"minicard",
",",
"lits",
",",
"k",
")",
"if",
"res",
"==",
"False",
":",
"self",
".",
"status",
"=",
"False",
"if",
"not",
"no_return",
":",
"return",
"res"
] | 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
string variable names.
:param obj: an object to assign an ID to.
:rtype: int.
Example:
.. code-block:: python
>>> from pysat.formula import IDPool
>>> vpool = IDPool(occupied=[[12, 18], [3, 10]])
>>>
>>> # creating 5 unique variables for the following strings
>>> for i in range(5):
... print vpool.id('v{0}'.format(i + 1))
1
2
11
19
20
In some cases, it makes sense to create an external function for
accessing IDPool, e.g.:
.. code-block:: python
>>> # continuing the previous example
>>> var = lambda i: vpool.id('var{0}'.format(i))
>>> var(5)
20
>>> var('hello_world!')
21
"""
vid = self.obj2id[obj]
if vid not in self.id2obj:
self.id2obj[vid] = obj
return vid | 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
string variable names.
:param obj: an object to assign an ID to.
:rtype: int.
Example:
.. code-block:: python
>>> from pysat.formula import IDPool
>>> vpool = IDPool(occupied=[[12, 18], [3, 10]])
>>>
>>> # creating 5 unique variables for the following strings
>>> for i in range(5):
... print vpool.id('v{0}'.format(i + 1))
1
2
11
19
20
In some cases, it makes sense to create an external function for
accessing IDPool, e.g.:
.. code-block:: python
>>> # continuing the previous example
>>> var = lambda i: vpool.id('var{0}'.format(i))
>>> var(5)
20
>>> var('hello_world!')
21
"""
vid = self.obj2id[obj]
if vid not in self.id2obj:
self.id2obj[vid] = obj
return vid | [
"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.
:param obj: an object to assign an ID to.
:rtype: int.
Example:
.. code-block:: python
>>> from pysat.formula import IDPool
>>> vpool = IDPool(occupied=[[12, 18], [3, 10]])
>>>
>>> # creating 5 unique variables for the following strings
>>> for i in range(5):
... print vpool.id('v{0}'.format(i + 1))
1
2
11
19
20
In some cases, it makes sense to create an external function for
accessing IDPool, e.g.:
.. code-block:: python
>>> # continuing the previous example
>>> var = lambda i: vpool.id('var{0}'.format(i))
>>> var(5)
20
>>> var('hello_world!')
21 | [
"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",
"."
] | 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._occupied.pop(0)
return self.top | 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._occupied.pop(0)
return self.top | [
"def",
"_next",
"(",
"self",
")",
":",
"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",
".",
"_occupied",
".",
"pop",
"(",
"0",
")",
"return",
"self",
".",
"top"
] | 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 either
gzip, bzip2, or lzma.
:param fname: name of a file to parse.
:param comment_lead: a list of characters leading comment lines
:param compressed_with: file compression algorithm
:type fname: str
:type comment_lead: list(str)
:type compressed_with: str
Note that the ``compressed_with`` parameter can be ``None`` (i.e.
the file is uncompressed), ``'gzip'``, ``'bzip2'``, ``'lzma'``, or
``'use_ext'``. The latter value indicates that compression type
should be automatically determined based on the file extension.
Using ``'lzma'`` in Python 2 requires the ``backports.lzma``
package to be additionally installed.
Usage example:
.. code-block:: python
>>> from pysat.formula import CNF
>>> cnf1 = CNF()
>>> cnf1.from_file('some-file.cnf.gz', compressed_with='gzip')
>>>
>>> cnf2 = CNF(from_file='another-file.cnf')
"""
with FileObject(fname, mode='r', compression=compressed_with) as fobj:
self.from_fp(fobj.fp, comment_lead) | 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 either
gzip, bzip2, or lzma.
:param fname: name of a file to parse.
:param comment_lead: a list of characters leading comment lines
:param compressed_with: file compression algorithm
:type fname: str
:type comment_lead: list(str)
:type compressed_with: str
Note that the ``compressed_with`` parameter can be ``None`` (i.e.
the file is uncompressed), ``'gzip'``, ``'bzip2'``, ``'lzma'``, or
``'use_ext'``. The latter value indicates that compression type
should be automatically determined based on the file extension.
Using ``'lzma'`` in Python 2 requires the ``backports.lzma``
package to be additionally installed.
Usage example:
.. code-block:: python
>>> from pysat.formula import CNF
>>> cnf1 = CNF()
>>> cnf1.from_file('some-file.cnf.gz', compressed_with='gzip')
>>>
>>> cnf2 = CNF(from_file='another-file.cnf')
"""
with FileObject(fname, mode='r', compression=compressed_with) as fobj:
self.from_fp(fobj.fp, comment_lead) | [
"def",
"from_file",
"(",
"self",
",",
"fname",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
",",
"compressed_with",
"=",
"'use_ext'",
")",
":",
"with",
"FileObject",
"(",
"fname",
",",
"mode",
"=",
"'r'",
",",
"compression",
"=",
"compressed_with",
")",
"as",
"fobj",
":",
"self",
".",
"from_fp",
"(",
"fobj",
".",
"fp",
",",
"comment_lead",
")"
] | 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.
:param comment_lead: a list of characters leading comment lines
:param compressed_with: file compression algorithm
:type fname: str
:type comment_lead: list(str)
:type compressed_with: str
Note that the ``compressed_with`` parameter can be ``None`` (i.e.
the file is uncompressed), ``'gzip'``, ``'bzip2'``, ``'lzma'``, or
``'use_ext'``. The latter value indicates that compression type
should be automatically determined based on the file extension.
Using ``'lzma'`` in Python 2 requires the ``backports.lzma``
package to be additionally installed.
Usage example:
.. code-block:: python
>>> from pysat.formula import CNF
>>> cnf1 = CNF()
>>> cnf1.from_file('some-file.cnf.gz', compressed_with='gzip')
>>>
>>> cnf2 = CNF(from_file='another-file.cnf') | [
"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",
"."
] | 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.
:param file_pointer: a file pointer to read the formula from.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.cnf', 'r') as fp:
... cnf1 = CNF()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.cnf', 'r') as fp:
... cnf2 = CNF(from_fp=fp)
"""
self.nv = 0
self.clauses = []
self.comments = []
comment_lead = tuple('p') + tuple(comment_lead)
for line in file_pointer:
line = line.strip()
if line:
if line[0] not in comment_lead:
cl = [int(l) for l in line.split()[:-1]]
self.nv = max([abs(l) for l in cl] + [self.nv])
self.clauses.append(cl)
elif not line.startswith('p cnf '):
self.comments.append(line) | 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.
:param file_pointer: a file pointer to read the formula from.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.cnf', 'r') as fp:
... cnf1 = CNF()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.cnf', 'r') as fp:
... cnf2 = CNF(from_fp=fp)
"""
self.nv = 0
self.clauses = []
self.comments = []
comment_lead = tuple('p') + tuple(comment_lead)
for line in file_pointer:
line = line.strip()
if line:
if line[0] not in comment_lead:
cl = [int(l) for l in line.split()[:-1]]
self.nv = max([abs(l) for l in cl] + [self.nv])
self.clauses.append(cl)
elif not line.startswith('p cnf '):
self.comments.append(line) | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"clauses",
"=",
"[",
"]",
"self",
".",
"comments",
"=",
"[",
"]",
"comment_lead",
"=",
"tuple",
"(",
"'p'",
")",
"+",
"tuple",
"(",
"comment_lead",
")",
"for",
"line",
"in",
"file_pointer",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"if",
"line",
"[",
"0",
"]",
"not",
"in",
"comment_lead",
":",
"cl",
"=",
"[",
"int",
"(",
"l",
")",
"for",
"l",
"in",
"line",
".",
"split",
"(",
")",
"[",
":",
"-",
"1",
"]",
"]",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"cl",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"self",
".",
"clauses",
".",
"append",
"(",
"cl",
")",
"elif",
"not",
"line",
".",
"startswith",
"(",
"'p cnf '",
")",
":",
"self",
".",
"comments",
".",
"append",
"(",
"line",
")"
] | 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.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.cnf', 'r') as fp:
... cnf1 = CNF()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.cnf', 'r') as fp:
... cnf2 = CNF(from_fp=fp) | [
"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",
"."
] | 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
>>> cnf = CNF(from_clauses=[[-1, 2], [1, -2], [5]])
>>> print cnf.clauses
[[-1, 2], [1, -2], [5]]
>>> print cnf.nv
5
"""
self.clauses = copy.deepcopy(clauses)
for cl in self.clauses:
self.nv = max([abs(l) for l in cl] + [self.nv]) | 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
>>> cnf = CNF(from_clauses=[[-1, 2], [1, -2], [5]])
>>> print cnf.clauses
[[-1, 2], [1, -2], [5]]
>>> print cnf.nv
5
"""
self.clauses = copy.deepcopy(clauses)
for cl in self.clauses:
self.nv = max([abs(l) for l in cl] + [self.nv]) | [
"def",
"from_clauses",
"(",
"self",
",",
"clauses",
")",
":",
"self",
".",
"clauses",
"=",
"copy",
".",
"deepcopy",
"(",
"clauses",
")",
"for",
"cl",
"in",
"self",
".",
"clauses",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"cl",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")"
] | 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], [5]])
>>> print cnf.clauses
[[-1, 2], [1, -2], [5]]
>>> print cnf.nv
5 | [
"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.
:param fname: a file name where to store the formula.
:param comments: additional comments to put in the file.
:type fname: str
:type comments: list(str)
Example:
.. code-block:: python
>>> from pysat.formula import CNF
>>> cnf = CNF()
...
>>> # the formula is filled with a bunch of clauses
>>> with open('some-file.cnf', 'w') as fp:
... cnf.to_fp(fp) # writing to the file pointer
"""
# saving formula's internal comments
for c in self.comments:
print(c, file=file_pointer)
# saving externally specified comments
if comments:
for c in comments:
print(c, file=file_pointer)
print('p cnf', self.nv, len(self.clauses), file=file_pointer)
for cl in self.clauses:
print(' '.join(str(l) for l in cl), '0', file=file_pointer) | 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.
:param fname: a file name where to store the formula.
:param comments: additional comments to put in the file.
:type fname: str
:type comments: list(str)
Example:
.. code-block:: python
>>> from pysat.formula import CNF
>>> cnf = CNF()
...
>>> # the formula is filled with a bunch of clauses
>>> with open('some-file.cnf', 'w') as fp:
... cnf.to_fp(fp) # writing to the file pointer
"""
# saving formula's internal comments
for c in self.comments:
print(c, file=file_pointer)
# saving externally specified comments
if comments:
for c in comments:
print(c, file=file_pointer)
print('p cnf', self.nv, len(self.clauses), file=file_pointer)
for cl in self.clauses:
print(' '.join(str(l) for l in cl), '0', file=file_pointer) | [
"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 specified comments",
"if",
"comments",
":",
"for",
"c",
"in",
"comments",
":",
"print",
"(",
"c",
",",
"file",
"=",
"file_pointer",
")",
"print",
"(",
"'p cnf'",
",",
"self",
".",
"nv",
",",
"len",
"(",
"self",
".",
"clauses",
")",
",",
"file",
"=",
"file_pointer",
")",
"for",
"cl",
"in",
"self",
".",
"clauses",
":",
"print",
"(",
"' '",
".",
"join",
"(",
"str",
"(",
"l",
")",
"for",
"l",
"in",
"cl",
")",
",",
"'0'",
",",
"file",
"=",
"file_pointer",
")"
] | 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.
:param comments: additional comments to put in the file.
:type fname: str
:type comments: list(str)
Example:
.. code-block:: python
>>> from pysat.formula import CNF
>>> cnf = CNF()
...
>>> # the formula is filled with a bunch of clauses
>>> with open('some-file.cnf', 'w') as fp:
... cnf.to_fp(fp) # writing to the file pointer | [
"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",
"."
] | 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)
.. code-block:: python
>>> from pysat.formula import CNF
>>> cnf = CNF(from_clauses=[[-1, 2], [3]])
>>> cnf.append([-3, 4])
>>> print cnf.clauses
[[-1, 2], [3], [-3, 4]]
"""
self.nv = max([abs(l) for l in clause] + [self.nv])
self.clauses.append(clause) | 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)
.. code-block:: python
>>> from pysat.formula import CNF
>>> cnf = CNF(from_clauses=[[-1, 2], [3]])
>>> cnf.append([-3, 4])
>>> print cnf.clauses
[[-1, 2], [3], [-3, 4]]
"""
self.nv = max([abs(l) for l in clause] + [self.nv])
self.clauses.append(clause) | [
"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.formula import CNF
>>> cnf = CNF(from_clauses=[[-1, 2], [3]])
>>> cnf.append([-3, 4])
>>> print cnf.clauses
[[-1, 2], [3], [-3, 4]] | [
"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.
:param file_pointer: a file pointer to read the formula from.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.cnf', 'r') as fp:
... cnf1 = WCNF()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.cnf', 'r') as fp:
... cnf2 = WCNF(from_fp=fp)
"""
self.nv = 0
self.hard = []
self.soft = []
self.wght = []
self.topw = 0
self.comments = []
comment_lead = tuple('p') + tuple(comment_lead)
for line in file_pointer:
line = line.strip()
if line:
if line[0] not in comment_lead:
cl = [int(l) for l in line.split()[:-1]]
w = cl.pop(0)
self.nv = max([abs(l) for l in cl] + [self.nv])
if w >= self.topw:
self.hard.append(cl)
else:
self.soft.append(cl)
self.wght.append(w)
elif not line.startswith('p wcnf '):
self.comments.append(line)
else: # expecting the preamble
self.topw = int(line.rsplit(' ', 1)[1]) | 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.
:param file_pointer: a file pointer to read the formula from.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.cnf', 'r') as fp:
... cnf1 = WCNF()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.cnf', 'r') as fp:
... cnf2 = WCNF(from_fp=fp)
"""
self.nv = 0
self.hard = []
self.soft = []
self.wght = []
self.topw = 0
self.comments = []
comment_lead = tuple('p') + tuple(comment_lead)
for line in file_pointer:
line = line.strip()
if line:
if line[0] not in comment_lead:
cl = [int(l) for l in line.split()[:-1]]
w = cl.pop(0)
self.nv = max([abs(l) for l in cl] + [self.nv])
if w >= self.topw:
self.hard.append(cl)
else:
self.soft.append(cl)
self.wght.append(w)
elif not line.startswith('p wcnf '):
self.comments.append(line)
else: # expecting the preamble
self.topw = int(line.rsplit(' ', 1)[1]) | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"hard",
"=",
"[",
"]",
"self",
".",
"soft",
"=",
"[",
"]",
"self",
".",
"wght",
"=",
"[",
"]",
"self",
".",
"topw",
"=",
"0",
"self",
".",
"comments",
"=",
"[",
"]",
"comment_lead",
"=",
"tuple",
"(",
"'p'",
")",
"+",
"tuple",
"(",
"comment_lead",
")",
"for",
"line",
"in",
"file_pointer",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"if",
"line",
"[",
"0",
"]",
"not",
"in",
"comment_lead",
":",
"cl",
"=",
"[",
"int",
"(",
"l",
")",
"for",
"l",
"in",
"line",
".",
"split",
"(",
")",
"[",
":",
"-",
"1",
"]",
"]",
"w",
"=",
"cl",
".",
"pop",
"(",
"0",
")",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"cl",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"if",
"w",
">=",
"self",
".",
"topw",
":",
"self",
".",
"hard",
".",
"append",
"(",
"cl",
")",
"else",
":",
"self",
".",
"soft",
".",
"append",
"(",
"cl",
")",
"self",
".",
"wght",
".",
"append",
"(",
"w",
")",
"elif",
"not",
"line",
".",
"startswith",
"(",
"'p wcnf '",
")",
":",
"self",
".",
"comments",
".",
"append",
"(",
"line",
")",
"else",
":",
"# expecting the preamble",
"self",
".",
"topw",
"=",
"int",
"(",
"line",
".",
"rsplit",
"(",
"' '",
",",
"1",
")",
"[",
"1",
"]",
")"
] | 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.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.cnf', 'r') as fp:
... cnf1 = WCNF()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.cnf', 'r') as fp:
... cnf2 = WCNF(from_fp=fp) | [
"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",
"."
] | 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.
:param fname: a file name where to store the formula.
:param comments: additional comments to put in the file.
:type fname: str
:type comments: list(str)
Example:
.. code-block:: python
>>> from pysat.formula import WCNF
>>> wcnf = WCNF()
...
>>> # the formula is filled with a bunch of clauses
>>> with open('some-file.wcnf', 'w') as fp:
... wcnf.to_fp(fp) # writing to the file pointer
"""
# saving formula's internal comments
for c in self.comments:
print(c, file=file_pointer)
# saving externally specified comments
if comments:
for c in comments:
print(c, file=file_pointer)
print('p wcnf', self.nv, len(self.hard) + len(self.soft), self.topw, file=file_pointer)
# soft clauses are dumped first because
# some tools (e.g. LBX) cannot count them properly
for i, cl in enumerate(self.soft):
print(self.wght[i], ' '.join(str(l) for l in cl), '0', file=file_pointer)
for cl in self.hard:
print(self.topw, ' '.join(str(l) for l in cl), '0', file=file_pointer) | 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.
:param fname: a file name where to store the formula.
:param comments: additional comments to put in the file.
:type fname: str
:type comments: list(str)
Example:
.. code-block:: python
>>> from pysat.formula import WCNF
>>> wcnf = WCNF()
...
>>> # the formula is filled with a bunch of clauses
>>> with open('some-file.wcnf', 'w') as fp:
... wcnf.to_fp(fp) # writing to the file pointer
"""
# saving formula's internal comments
for c in self.comments:
print(c, file=file_pointer)
# saving externally specified comments
if comments:
for c in comments:
print(c, file=file_pointer)
print('p wcnf', self.nv, len(self.hard) + len(self.soft), self.topw, file=file_pointer)
# soft clauses are dumped first because
# some tools (e.g. LBX) cannot count them properly
for i, cl in enumerate(self.soft):
print(self.wght[i], ' '.join(str(l) for l in cl), '0', file=file_pointer)
for cl in self.hard:
print(self.topw, ' '.join(str(l) for l in cl), '0', file=file_pointer) | [
"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 specified comments",
"if",
"comments",
":",
"for",
"c",
"in",
"comments",
":",
"print",
"(",
"c",
",",
"file",
"=",
"file_pointer",
")",
"print",
"(",
"'p wcnf'",
",",
"self",
".",
"nv",
",",
"len",
"(",
"self",
".",
"hard",
")",
"+",
"len",
"(",
"self",
".",
"soft",
")",
",",
"self",
".",
"topw",
",",
"file",
"=",
"file_pointer",
")",
"# soft clauses are dumped first because",
"# some tools (e.g. LBX) cannot count them properly",
"for",
"i",
",",
"cl",
"in",
"enumerate",
"(",
"self",
".",
"soft",
")",
":",
"print",
"(",
"self",
".",
"wght",
"[",
"i",
"]",
",",
"' '",
".",
"join",
"(",
"str",
"(",
"l",
")",
"for",
"l",
"in",
"cl",
")",
",",
"'0'",
",",
"file",
"=",
"file_pointer",
")",
"for",
"cl",
"in",
"self",
".",
"hard",
":",
"print",
"(",
"self",
".",
"topw",
",",
"' '",
".",
"join",
"(",
"str",
"(",
"l",
")",
"for",
"l",
"in",
"cl",
")",
",",
"'0'",
",",
"file",
"=",
"file_pointer",
")"
] | 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.
:param comments: additional comments to put in the file.
:type fname: str
:type comments: list(str)
Example:
.. code-block:: python
>>> from pysat.formula import WCNF
>>> wcnf = WCNF()
...
>>> # the formula is filled with a bunch of clauses
>>> with open('some-file.wcnf', 'w') as fp:
... wcnf.to_fp(fp) # writing to the file pointer | [
"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",
"."
] | 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``
argument. If no weight is set, the clause is considered to be hard.
:param clause: a new clause to add.
:param weight: integer weight of the clause.
:type clause: list(int)
:type weight: integer or None
.. code-block:: python
>>> from pysat.formula import WCNF
>>> cnf = WCNF()
>>> cnf.append([-1, 2])
>>> cnf.append([1], weight=10)
>>> cnf.append([-2], weight=20)
>>> print cnf.hard
[[-1, 2]]
>>> print cnf.soft
[[1], [-2]]
>>> print cnf.wght
[10, 20]
"""
self.nv = max([abs(l) for l in clause] + [self.nv])
if weight:
self.soft.append(clause)
self.wght.append(weight)
else:
self.hard.append(clause) | 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``
argument. If no weight is set, the clause is considered to be hard.
:param clause: a new clause to add.
:param weight: integer weight of the clause.
:type clause: list(int)
:type weight: integer or None
.. code-block:: python
>>> from pysat.formula import WCNF
>>> cnf = WCNF()
>>> cnf.append([-1, 2])
>>> cnf.append([1], weight=10)
>>> cnf.append([-2], weight=20)
>>> print cnf.hard
[[-1, 2]]
>>> print cnf.soft
[[1], [-2]]
>>> print cnf.wght
[10, 20]
"""
self.nv = max([abs(l) for l in clause] + [self.nv])
if weight:
self.soft.append(clause)
self.wght.append(weight)
else:
self.hard.append(clause) | [
"def",
"append",
"(",
"self",
",",
"clause",
",",
"weight",
"=",
"None",
")",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"clause",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"if",
"weight",
":",
"self",
".",
"soft",
".",
"append",
"(",
"clause",
")",
"self",
".",
"wght",
".",
"append",
"(",
"weight",
")",
"else",
":",
"self",
".",
"hard",
".",
"append",
"(",
"clause",
")"
] | 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.
:param clause: a new clause to add.
:param weight: integer weight of the clause.
:type clause: list(int)
:type weight: integer or None
.. code-block:: python
>>> from pysat.formula import WCNF
>>> cnf = WCNF()
>>> cnf.append([-1, 2])
>>> cnf.append([1], weight=10)
>>> cnf.append([-2], weight=20)
>>> print cnf.hard
[[-1, 2]]
>>> print cnf.soft
[[1], [-2]]
>>> print cnf.wght
[10, 20] | [
"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.
:param file_pointer: a file pointer to read the formula from.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.cnf+', 'r') as fp:
... cnf1 = CNFPlus()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.cnf+', 'r') as fp:
... cnf2 = CNFPlus(from_fp=fp)
"""
self.nv = 0
self.clauses = []
self.atmosts = []
self.comments = []
comment_lead = tuple('p') + tuple(comment_lead)
for line in file_pointer:
line = line.strip()
if line:
if line[0] not in comment_lead:
if line[-1] == '0': # normal clause
cl = [int(l) for l in line.split()[:-1]]
self.nv = max([abs(l) for l in cl] + [self.nv])
self.clauses.append(cl)
else: # atmost/atleast constraint
items = [i for i in line.split()]
lits = [int(l) for l in items[:-2]]
rhs = int(items[-1])
self.nv = max([abs(l) for l in lits] + [self.nv])
if items[-2][0] == '>':
lits = list(map(lambda l: -l, lits))
rhs = len(lits) - rhs
self.atmosts.append([lits, rhs])
elif not line.startswith('p cnf+ '):
self.comments.append(line) | 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.
:param file_pointer: a file pointer to read the formula from.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.cnf+', 'r') as fp:
... cnf1 = CNFPlus()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.cnf+', 'r') as fp:
... cnf2 = CNFPlus(from_fp=fp)
"""
self.nv = 0
self.clauses = []
self.atmosts = []
self.comments = []
comment_lead = tuple('p') + tuple(comment_lead)
for line in file_pointer:
line = line.strip()
if line:
if line[0] not in comment_lead:
if line[-1] == '0': # normal clause
cl = [int(l) for l in line.split()[:-1]]
self.nv = max([abs(l) for l in cl] + [self.nv])
self.clauses.append(cl)
else: # atmost/atleast constraint
items = [i for i in line.split()]
lits = [int(l) for l in items[:-2]]
rhs = int(items[-1])
self.nv = max([abs(l) for l in lits] + [self.nv])
if items[-2][0] == '>':
lits = list(map(lambda l: -l, lits))
rhs = len(lits) - rhs
self.atmosts.append([lits, rhs])
elif not line.startswith('p cnf+ '):
self.comments.append(line) | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"clauses",
"=",
"[",
"]",
"self",
".",
"atmosts",
"=",
"[",
"]",
"self",
".",
"comments",
"=",
"[",
"]",
"comment_lead",
"=",
"tuple",
"(",
"'p'",
")",
"+",
"tuple",
"(",
"comment_lead",
")",
"for",
"line",
"in",
"file_pointer",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"if",
"line",
"[",
"0",
"]",
"not",
"in",
"comment_lead",
":",
"if",
"line",
"[",
"-",
"1",
"]",
"==",
"'0'",
":",
"# normal clause",
"cl",
"=",
"[",
"int",
"(",
"l",
")",
"for",
"l",
"in",
"line",
".",
"split",
"(",
")",
"[",
":",
"-",
"1",
"]",
"]",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"cl",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"self",
".",
"clauses",
".",
"append",
"(",
"cl",
")",
"else",
":",
"# atmost/atleast constraint",
"items",
"=",
"[",
"i",
"for",
"i",
"in",
"line",
".",
"split",
"(",
")",
"]",
"lits",
"=",
"[",
"int",
"(",
"l",
")",
"for",
"l",
"in",
"items",
"[",
":",
"-",
"2",
"]",
"]",
"rhs",
"=",
"int",
"(",
"items",
"[",
"-",
"1",
"]",
")",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"lits",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"if",
"items",
"[",
"-",
"2",
"]",
"[",
"0",
"]",
"==",
"'>'",
":",
"lits",
"=",
"list",
"(",
"map",
"(",
"lambda",
"l",
":",
"-",
"l",
",",
"lits",
")",
")",
"rhs",
"=",
"len",
"(",
"lits",
")",
"-",
"rhs",
"self",
".",
"atmosts",
".",
"append",
"(",
"[",
"lits",
",",
"rhs",
"]",
")",
"elif",
"not",
"line",
".",
"startswith",
"(",
"'p cnf+ '",
")",
":",
"self",
".",
"comments",
".",
"append",
"(",
"line",
")"
] | 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.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.cnf+', 'r') as fp:
... cnf1 = CNFPlus()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.cnf+', 'r') as fp:
... cnf2 = CNFPlus(from_fp=fp) | [
"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",
"."
] | 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.
:param fname: a file name where to store the formula.
:param comments: additional comments to put in the file.
:type fname: str
:type comments: list(str)
Example:
.. code-block:: python
>>> from pysat.formula import CNFPlus
>>> cnf = CNFPlus()
...
>>> # the formula is filled with a bunch of clauses
>>> with open('some-file.cnf+', 'w') as fp:
... cnf.to_fp(fp) # writing to the file pointer
"""
# saving formula's internal comments
for c in self.comments:
print(c, file=file_pointer)
# saving externally specified comments
if comments:
for c in comments:
print(c, file=file_pointer)
ftype = 'cnf+' if self.atmosts else 'cnf'
print('p', ftype, self.nv, len(self.clauses) + len(self.atmosts),
file=file_pointer)
for cl in self.clauses:
print(' '.join(str(l) for l in cl), '0', file=file_pointer)
for am in self.atmosts:
print(' '.join(str(l) for l in am[0]), '<=', am[1], file=file_pointer) | 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.
:param fname: a file name where to store the formula.
:param comments: additional comments to put in the file.
:type fname: str
:type comments: list(str)
Example:
.. code-block:: python
>>> from pysat.formula import CNFPlus
>>> cnf = CNFPlus()
...
>>> # the formula is filled with a bunch of clauses
>>> with open('some-file.cnf+', 'w') as fp:
... cnf.to_fp(fp) # writing to the file pointer
"""
# saving formula's internal comments
for c in self.comments:
print(c, file=file_pointer)
# saving externally specified comments
if comments:
for c in comments:
print(c, file=file_pointer)
ftype = 'cnf+' if self.atmosts else 'cnf'
print('p', ftype, self.nv, len(self.clauses) + len(self.atmosts),
file=file_pointer)
for cl in self.clauses:
print(' '.join(str(l) for l in cl), '0', file=file_pointer)
for am in self.atmosts:
print(' '.join(str(l) for l in am[0]), '<=', am[1], file=file_pointer) | [
"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 specified comments",
"if",
"comments",
":",
"for",
"c",
"in",
"comments",
":",
"print",
"(",
"c",
",",
"file",
"=",
"file_pointer",
")",
"ftype",
"=",
"'cnf+'",
"if",
"self",
".",
"atmosts",
"else",
"'cnf'",
"print",
"(",
"'p'",
",",
"ftype",
",",
"self",
".",
"nv",
",",
"len",
"(",
"self",
".",
"clauses",
")",
"+",
"len",
"(",
"self",
".",
"atmosts",
")",
",",
"file",
"=",
"file_pointer",
")",
"for",
"cl",
"in",
"self",
".",
"clauses",
":",
"print",
"(",
"' '",
".",
"join",
"(",
"str",
"(",
"l",
")",
"for",
"l",
"in",
"cl",
")",
",",
"'0'",
",",
"file",
"=",
"file_pointer",
")",
"for",
"am",
"in",
"self",
".",
"atmosts",
":",
"print",
"(",
"' '",
".",
"join",
"(",
"str",
"(",
"l",
")",
"for",
"l",
"in",
"am",
"[",
"0",
"]",
")",
",",
"'<='",
",",
"am",
"[",
"1",
"]",
",",
"file",
"=",
"file_pointer",
")"
] | 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.
:param comments: additional comments to put in the file.
:type fname: str
:type comments: list(str)
Example:
.. code-block:: python
>>> from pysat.formula import CNFPlus
>>> cnf = CNFPlus()
...
>>> # the formula is filled with a bunch of clauses
>>> with open('some-file.cnf+', 'w') as fp:
... cnf.to_fp(fp) # writing to the file pointer | [
"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",
"."
] | 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, this should be set with the
use of the additional default argument ``is_atmost``, which is set
to ``False`` by default.
:param clause: a new clause to add.
:param is_atmost: if ``True``, the clause is AtMostK.
:type clause: list(int)
:type is_atmost: bool
.. code-block:: python
>>> from pysat.formula import CNFPlus
>>> cnf = CNFPlus()
>>> cnf.append([-3, 4])
>>> cnf.append([[1, 2, 3], 1], is_atmost=True)
>>> print cnf.clauses
[[-3, 4]]
>>> print cnf.atmosts
[[1, 2, 3], 1]
"""
if not is_atmost:
self.nv = max([abs(l) for l in clause] + [self.nv])
self.clauses.append(clause)
else:
self.nv = max([abs(l) for l in clause[0]] + [self.nv])
self.atmosts.append(clause) | 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, this should be set with the
use of the additional default argument ``is_atmost``, which is set
to ``False`` by default.
:param clause: a new clause to add.
:param is_atmost: if ``True``, the clause is AtMostK.
:type clause: list(int)
:type is_atmost: bool
.. code-block:: python
>>> from pysat.formula import CNFPlus
>>> cnf = CNFPlus()
>>> cnf.append([-3, 4])
>>> cnf.append([[1, 2, 3], 1], is_atmost=True)
>>> print cnf.clauses
[[-3, 4]]
>>> print cnf.atmosts
[[1, 2, 3], 1]
"""
if not is_atmost:
self.nv = max([abs(l) for l in clause] + [self.nv])
self.clauses.append(clause)
else:
self.nv = max([abs(l) for l in clause[0]] + [self.nv])
self.atmosts.append(clause) | [
"def",
"append",
"(",
"self",
",",
"clause",
",",
"is_atmost",
"=",
"False",
")",
":",
"if",
"not",
"is_atmost",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"clause",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"self",
".",
"clauses",
".",
"append",
"(",
"clause",
")",
"else",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"clause",
"[",
"0",
"]",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"self",
".",
"atmosts",
".",
"append",
"(",
"clause",
")"
] | 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 argument ``is_atmost``, which is set
to ``False`` by default.
:param clause: a new clause to add.
:param is_atmost: if ``True``, the clause is AtMostK.
:type clause: list(int)
:type is_atmost: bool
.. code-block:: python
>>> from pysat.formula import CNFPlus
>>> cnf = CNFPlus()
>>> cnf.append([-3, 4])
>>> cnf.append([[1, 2, 3], 1], is_atmost=True)
>>> print cnf.clauses
[[-3, 4]]
>>> print cnf.atmosts
[[1, 2, 3], 1] | [
"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",
"."
] | 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.
:param file_pointer: a file pointer to read the formula from.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.wcnf+', 'r') as fp:
... cnf1 = WCNFPlus()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.wcnf+', 'r') as fp:
... cnf2 = WCNFPlus(from_fp=fp)
"""
self.nv = 0
self.hard = []
self.atms = []
self.soft = []
self.wght = []
self.topw = 0
self.comments = []
comment_lead = tuple('p') + tuple(comment_lead)
for line in file_pointer:
line = line.strip()
if line:
if line[0] not in comment_lead:
if line[-1] == '0': # normal clause
cl = [int(l) for l in line.split()[:-1]]
w = cl.pop(0)
self.nv = max([abs(l) for l in cl] + [self.nv])
if w >= self.topw:
self.hard.append(cl)
else:
self.soft.append(cl)
self.wght.append(w)
else: # atmost/atleast constraint
items = [i for i in line.split()]
lits = [int(l) for l in items[1:-2]]
rhs = int(items[-1])
self.nv = max([abs(l) for l in lits] + [self.nv])
if items[-2][0] == '>':
lits = list(map(lambda l: -l, lits))
rhs = len(lits) - rhs
self.atms.append([lits, rhs])
elif not line.startswith('p wcnf+ '):
self.comments.append(line)
else: # expecting the preamble
self.topw = int(line.rsplit(' ', 1)[1]) | 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.
:param file_pointer: a file pointer to read the formula from.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.wcnf+', 'r') as fp:
... cnf1 = WCNFPlus()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.wcnf+', 'r') as fp:
... cnf2 = WCNFPlus(from_fp=fp)
"""
self.nv = 0
self.hard = []
self.atms = []
self.soft = []
self.wght = []
self.topw = 0
self.comments = []
comment_lead = tuple('p') + tuple(comment_lead)
for line in file_pointer:
line = line.strip()
if line:
if line[0] not in comment_lead:
if line[-1] == '0': # normal clause
cl = [int(l) for l in line.split()[:-1]]
w = cl.pop(0)
self.nv = max([abs(l) for l in cl] + [self.nv])
if w >= self.topw:
self.hard.append(cl)
else:
self.soft.append(cl)
self.wght.append(w)
else: # atmost/atleast constraint
items = [i for i in line.split()]
lits = [int(l) for l in items[1:-2]]
rhs = int(items[-1])
self.nv = max([abs(l) for l in lits] + [self.nv])
if items[-2][0] == '>':
lits = list(map(lambda l: -l, lits))
rhs = len(lits) - rhs
self.atms.append([lits, rhs])
elif not line.startswith('p wcnf+ '):
self.comments.append(line)
else: # expecting the preamble
self.topw = int(line.rsplit(' ', 1)[1]) | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"hard",
"=",
"[",
"]",
"self",
".",
"atms",
"=",
"[",
"]",
"self",
".",
"soft",
"=",
"[",
"]",
"self",
".",
"wght",
"=",
"[",
"]",
"self",
".",
"topw",
"=",
"0",
"self",
".",
"comments",
"=",
"[",
"]",
"comment_lead",
"=",
"tuple",
"(",
"'p'",
")",
"+",
"tuple",
"(",
"comment_lead",
")",
"for",
"line",
"in",
"file_pointer",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"if",
"line",
"[",
"0",
"]",
"not",
"in",
"comment_lead",
":",
"if",
"line",
"[",
"-",
"1",
"]",
"==",
"'0'",
":",
"# normal clause",
"cl",
"=",
"[",
"int",
"(",
"l",
")",
"for",
"l",
"in",
"line",
".",
"split",
"(",
")",
"[",
":",
"-",
"1",
"]",
"]",
"w",
"=",
"cl",
".",
"pop",
"(",
"0",
")",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"cl",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"if",
"w",
">=",
"self",
".",
"topw",
":",
"self",
".",
"hard",
".",
"append",
"(",
"cl",
")",
"else",
":",
"self",
".",
"soft",
".",
"append",
"(",
"cl",
")",
"self",
".",
"wght",
".",
"append",
"(",
"w",
")",
"else",
":",
"# atmost/atleast constraint",
"items",
"=",
"[",
"i",
"for",
"i",
"in",
"line",
".",
"split",
"(",
")",
"]",
"lits",
"=",
"[",
"int",
"(",
"l",
")",
"for",
"l",
"in",
"items",
"[",
"1",
":",
"-",
"2",
"]",
"]",
"rhs",
"=",
"int",
"(",
"items",
"[",
"-",
"1",
"]",
")",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"lits",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"if",
"items",
"[",
"-",
"2",
"]",
"[",
"0",
"]",
"==",
"'>'",
":",
"lits",
"=",
"list",
"(",
"map",
"(",
"lambda",
"l",
":",
"-",
"l",
",",
"lits",
")",
")",
"rhs",
"=",
"len",
"(",
"lits",
")",
"-",
"rhs",
"self",
".",
"atms",
".",
"append",
"(",
"[",
"lits",
",",
"rhs",
"]",
")",
"elif",
"not",
"line",
".",
"startswith",
"(",
"'p wcnf+ '",
")",
":",
"self",
".",
"comments",
".",
"append",
"(",
"line",
")",
"else",
":",
"# expecting the preamble",
"self",
".",
"topw",
"=",
"int",
"(",
"line",
".",
"rsplit",
"(",
"' '",
",",
"1",
")",
"[",
"1",
"]",
")"
] | 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.
:param comment_lead: a list of characters leading comment lines
:type file_pointer: file pointer
:type comment_lead: list(str)
Usage example:
.. code-block:: python
>>> with open('some-file.wcnf+', 'r') as fp:
... cnf1 = WCNFPlus()
... cnf1.from_fp(fp)
>>>
>>> with open('another-file.wcnf+', 'r') as fp:
... cnf2 = WCNFPlus(from_fp=fp) | [
"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",
"."
] | 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 constraint, this should be set with the
use of the additional default argument ``is_atmost``, which is set
to ``False`` by default.
If ``is_atmost`` is set to ``False``, the clause can be either hard
or soft depending on the ``weight`` argument. If no weight is
specified, the clause is considered hard. Otherwise, the clause is
soft.
:param clause: a new clause to add.
:param weight: an integer weight of the clause.
:param is_atmost: if ``True``, the clause is AtMostK.
:type clause: list(int)
:type weight: integer or None
:type is_atmost: bool
.. code-block:: python
>>> from pysat.formula import WCNFPlus
>>> cnf = WCNFPlus()
>>> cnf.append([-3, 4])
>>> cnf.append([[1, 2, 3], 1], is_atmost=True)
>>> cnf.append([-1, -2], weight=35)
>>> print cnf.hard
[[-3, 4]]
>>> print cnf.atms
[[1, 2, 3], 1]
>>> print cnf.soft
[[-1, -2]]
>>> print cnf.wght
[35]
"""
if not is_atmost:
self.nv = max([abs(l) for l in clause] + [self.nv])
if weight:
self.soft.append(clause)
self.wght.append(weight)
else:
self.hard.append(clause)
else:
self.nv = max([abs(l) for l in clause[0]] + [self.nv])
self.atms.append(clause) | 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 constraint, this should be set with the
use of the additional default argument ``is_atmost``, which is set
to ``False`` by default.
If ``is_atmost`` is set to ``False``, the clause can be either hard
or soft depending on the ``weight`` argument. If no weight is
specified, the clause is considered hard. Otherwise, the clause is
soft.
:param clause: a new clause to add.
:param weight: an integer weight of the clause.
:param is_atmost: if ``True``, the clause is AtMostK.
:type clause: list(int)
:type weight: integer or None
:type is_atmost: bool
.. code-block:: python
>>> from pysat.formula import WCNFPlus
>>> cnf = WCNFPlus()
>>> cnf.append([-3, 4])
>>> cnf.append([[1, 2, 3], 1], is_atmost=True)
>>> cnf.append([-1, -2], weight=35)
>>> print cnf.hard
[[-3, 4]]
>>> print cnf.atms
[[1, 2, 3], 1]
>>> print cnf.soft
[[-1, -2]]
>>> print cnf.wght
[35]
"""
if not is_atmost:
self.nv = max([abs(l) for l in clause] + [self.nv])
if weight:
self.soft.append(clause)
self.wght.append(weight)
else:
self.hard.append(clause)
else:
self.nv = max([abs(l) for l in clause[0]] + [self.nv])
self.atms.append(clause) | [
"def",
"append",
"(",
"self",
",",
"clause",
",",
"weight",
"=",
"None",
",",
"is_atmost",
"=",
"False",
")",
":",
"if",
"not",
"is_atmost",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"clause",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"if",
"weight",
":",
"self",
".",
"soft",
".",
"append",
"(",
"clause",
")",
"self",
".",
"wght",
".",
"append",
"(",
"weight",
")",
"else",
":",
"self",
".",
"hard",
".",
"append",
"(",
"clause",
")",
"else",
":",
"self",
".",
"nv",
"=",
"max",
"(",
"[",
"abs",
"(",
"l",
")",
"for",
"l",
"in",
"clause",
"[",
"0",
"]",
"]",
"+",
"[",
"self",
".",
"nv",
"]",
")",
"self",
".",
"atms",
".",
"append",
"(",
"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 default argument ``is_atmost``, which is set
to ``False`` by default.
If ``is_atmost`` is set to ``False``, the clause can be either hard
or soft depending on the ``weight`` argument. If no weight is
specified, the clause is considered hard. Otherwise, the clause is
soft.
:param clause: a new clause to add.
:param weight: an integer weight of the clause.
:param is_atmost: if ``True``, the clause is AtMostK.
:type clause: list(int)
:type weight: integer or None
:type is_atmost: bool
.. code-block:: python
>>> from pysat.formula import WCNFPlus
>>> cnf = WCNFPlus()
>>> cnf.append([-3, 4])
>>> cnf.append([[1, 2, 3], 1], is_atmost=True)
>>> cnf.append([-1, -2], weight=35)
>>> print cnf.hard
[[-3, 4]]
>>> print cnf.atms
[[1, 2, 3], 1]
>>> print cnf.soft
[[-1, -2]]
>>> print cnf.wght
[35] | [
"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",
"."
] | 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",
"=",
"None"
] | 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 computed in
:func:`treat_core`. Each clause :math:`(c\\vee\\neg{s},w)`, s.t.
:math:`w>minw` and :math:`s` is its selector literal, is split into
clauses (1) clause :math:`(c\\vee\\neg{s}, minw)` and (2) a
residual clause :math:`(c\\vee\\neg{s}',w-minw)`. Note that the
residual clause has a fresh selector literal :math:`s'` different
from :math:`s`.
:param minw: minimum weight of the core
:type minw: int
"""
for clid in self.core:
sel = self.sels[clid]
if self.wght[clid] > minw:
self.topv += 1
cl_new = []
for l in self.soft[clid]:
if l != -sel:
cl_new.append(l)
else:
cl_new.append(-self.topv)
self.sels.append(self.topv)
self.vmap[self.topv] = len(self.soft)
self.soft.append(cl_new)
self.wght.append(self.wght[clid] - minw)
self.wght[clid] = minw
self.scpy.append(True) | 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 computed in
:func:`treat_core`. Each clause :math:`(c\\vee\\neg{s},w)`, s.t.
:math:`w>minw` and :math:`s` is its selector literal, is split into
clauses (1) clause :math:`(c\\vee\\neg{s}, minw)` and (2) a
residual clause :math:`(c\\vee\\neg{s}',w-minw)`. Note that the
residual clause has a fresh selector literal :math:`s'` different
from :math:`s`.
:param minw: minimum weight of the core
:type minw: int
"""
for clid in self.core:
sel = self.sels[clid]
if self.wght[clid] > minw:
self.topv += 1
cl_new = []
for l in self.soft[clid]:
if l != -sel:
cl_new.append(l)
else:
cl_new.append(-self.topv)
self.sels.append(self.topv)
self.vmap[self.topv] = len(self.soft)
self.soft.append(cl_new)
self.wght.append(self.wght[clid] - minw)
self.wght[clid] = minw
self.scpy.append(True) | [
"def",
"split_core",
"(",
"self",
",",
"minw",
")",
":",
"for",
"clid",
"in",
"self",
".",
"core",
":",
"sel",
"=",
"self",
".",
"sels",
"[",
"clid",
"]",
"if",
"self",
".",
"wght",
"[",
"clid",
"]",
">",
"minw",
":",
"self",
".",
"topv",
"+=",
"1",
"cl_new",
"=",
"[",
"]",
"for",
"l",
"in",
"self",
".",
"soft",
"[",
"clid",
"]",
":",
"if",
"l",
"!=",
"-",
"sel",
":",
"cl_new",
".",
"append",
"(",
"l",
")",
"else",
":",
"cl_new",
".",
"append",
"(",
"-",
"self",
".",
"topv",
")",
"self",
".",
"sels",
".",
"append",
"(",
"self",
".",
"topv",
")",
"self",
".",
"vmap",
"[",
"self",
".",
"topv",
"]",
"=",
"len",
"(",
"self",
".",
"soft",
")",
"self",
".",
"soft",
".",
"append",
"(",
"cl_new",
")",
"self",
".",
"wght",
".",
"append",
"(",
"self",
".",
"wght",
"[",
"clid",
"]",
"-",
"minw",
")",
"self",
".",
"wght",
"[",
"clid",
"]",
"=",
"minw",
"self",
".",
"scpy",
".",
"append",
"(",
"True",
")"
] | 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 clause :math:`(c\\vee\\neg{s},w)`, s.t.
:math:`w>minw` and :math:`s` is its selector literal, is split into
clauses (1) clause :math:`(c\\vee\\neg{s}, minw)` and (2) a
residual clause :math:`(c\\vee\\neg{s}',w-minw)`. Note that the
residual clause has a fresh selector literal :math:`s'` different
from :math:`s`.
:param minw: minimum weight of the core
:type minw: int | [
"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
augmented with the negation of the clause (see
:func:`remove_unit_core`).
Otherwise (if the core contains more than one clause), every clause
:math:`c` of the core is *relaxed*. This means a new *relaxation
literal* is added to the clause, i.e. :math:`c\gets c\\vee r`,
where :math:`r` is a fresh (unused) relaxation variable. After the
clauses get relaxed, a new cardinality encoding is added to the
formula enforcing the sum of the new relaxation variables to be not
greater than 1, :math:`\sum_{c\in\phi}{r\leq 1}`, where
:math:`\phi` denotes the unsatisfiable core.
"""
if len(self.core) > 1:
# relaxing
rels = []
for clid in self.core:
self.topv += 1
rels.append(self.topv)
self.soft[clid].append(self.topv)
# creating a new cardinality constraint
am1 = CardEnc.atmost(lits=rels, top_id=self.topv, encoding=self.cenc)
for cl in am1.clauses:
self.hard.append(cl)
# only if minicard
# (for other solvers am1.atmosts should be empty)
for am in am1.atmosts:
self.atm1.append(am)
self.topv = am1.nv
elif len(self.core) == 1: # unit core => simply negate the clause
self.remove_unit_core() | 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
augmented with the negation of the clause (see
:func:`remove_unit_core`).
Otherwise (if the core contains more than one clause), every clause
:math:`c` of the core is *relaxed*. This means a new *relaxation
literal* is added to the clause, i.e. :math:`c\gets c\\vee r`,
where :math:`r` is a fresh (unused) relaxation variable. After the
clauses get relaxed, a new cardinality encoding is added to the
formula enforcing the sum of the new relaxation variables to be not
greater than 1, :math:`\sum_{c\in\phi}{r\leq 1}`, where
:math:`\phi` denotes the unsatisfiable core.
"""
if len(self.core) > 1:
# relaxing
rels = []
for clid in self.core:
self.topv += 1
rels.append(self.topv)
self.soft[clid].append(self.topv)
# creating a new cardinality constraint
am1 = CardEnc.atmost(lits=rels, top_id=self.topv, encoding=self.cenc)
for cl in am1.clauses:
self.hard.append(cl)
# only if minicard
# (for other solvers am1.atmosts should be empty)
for am in am1.atmosts:
self.atm1.append(am)
self.topv = am1.nv
elif len(self.core) == 1: # unit core => simply negate the clause
self.remove_unit_core() | [
"def",
"relax_core",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"core",
")",
">",
"1",
":",
"# relaxing",
"rels",
"=",
"[",
"]",
"for",
"clid",
"in",
"self",
".",
"core",
":",
"self",
".",
"topv",
"+=",
"1",
"rels",
".",
"append",
"(",
"self",
".",
"topv",
")",
"self",
".",
"soft",
"[",
"clid",
"]",
".",
"append",
"(",
"self",
".",
"topv",
")",
"# creating a new cardinality constraint",
"am1",
"=",
"CardEnc",
".",
"atmost",
"(",
"lits",
"=",
"rels",
",",
"top_id",
"=",
"self",
".",
"topv",
",",
"encoding",
"=",
"self",
".",
"cenc",
")",
"for",
"cl",
"in",
"am1",
".",
"clauses",
":",
"self",
".",
"hard",
".",
"append",
"(",
"cl",
")",
"# only if minicard",
"# (for other solvers am1.atmosts should be empty)",
"for",
"am",
"in",
"am1",
".",
"atmosts",
":",
"self",
".",
"atm1",
".",
"append",
"(",
"am",
")",
"self",
".",
"topv",
"=",
"am1",
".",
"nv",
"elif",
"len",
"(",
"self",
".",
"core",
")",
"==",
"1",
":",
"# unit core => simply negate the clause",
"self",
".",
"remove_unit_core",
"(",
")"
] | 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
:func:`remove_unit_core`).
Otherwise (if the core contains more than one clause), every clause
:math:`c` of the core is *relaxed*. This means a new *relaxation
literal* is added to the clause, i.e. :math:`c\gets c\\vee r`,
where :math:`r` is a fresh (unused) relaxation variable. After the
clauses get relaxed, a new cardinality encoding is added to the
formula enforcing the sum of the new relaxation variables to be not
greater than 1, :math:`\sum_{c\in\phi}{r\leq 1}`, where
:math:`\phi` denotes the unsatisfiable core. | [
"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)
solver = 'g4'
verbose = 1
print_model = False
for opt, arg in opts:
if opt in ('-h', '--help'):
print_usage()
sys.exit(0)
elif opt in ('-m', '--model'):
print_model = True
elif opt in ('-s', '--solver'):
solver = str(arg)
elif opt in ('-v', '--verbose'):
verbose += 1
else:
assert False, 'Unhandled option: {0} {1}'.format(opt, arg)
return print_model, solver, verbose, args | 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)
solver = 'g4'
verbose = 1
print_model = False
for opt, arg in opts:
if opt in ('-h', '--help'):
print_usage()
sys.exit(0)
elif opt in ('-m', '--model'):
print_model = True
elif opt in ('-s', '--solver'):
solver = str(arg)
elif opt in ('-v', '--verbose'):
verbose += 1
else:
assert False, 'Unhandled option: {0} {1}'.format(opt, arg)
return print_model, solver, verbose, args | [
"def",
"parse_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",
")",
"solver",
"=",
"'g4'",
"verbose",
"=",
"1",
"print_model",
"=",
"False",
"for",
"opt",
",",
"arg",
"in",
"opts",
":",
"if",
"opt",
"in",
"(",
"'-h'",
",",
"'--help'",
")",
":",
"print_usage",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"elif",
"opt",
"in",
"(",
"'-m'",
",",
"'--model'",
")",
":",
"print_model",
"=",
"True",
"elif",
"opt",
"in",
"(",
"'-s'",
",",
"'--solver'",
")",
":",
"solver",
"=",
"str",
"(",
"arg",
")",
"elif",
"opt",
"in",
"(",
"'-v'",
",",
"'--verbose'",
")",
":",
"verbose",
"+=",
"1",
"else",
":",
"assert",
"False",
",",
"'Unhandled option: {0} {1}'",
".",
"format",
"(",
"opt",
",",
"arg",
")",
"return",
"print_model",
",",
"solver",
",",
"verbose",
",",
"args"
] | 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",
"(",
"from_file",
"=",
"fml_file",
")",
".",
"weighted",
"(",
")",
"return",
"fml"
] | 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 all introduced selectors is
stored in variable ``self.sels``.
:param formula: input MaxSAT formula
:type formula: :class:`WCNF`
"""
self.oracle = Solver(name=self.solver, bootstrap_with=formula.hard,
incr=True, use_timer=True)
for i, cl in enumerate(formula.soft):
# TODO: if clause is unit, use its literal as selector
# (ITotalizer must be extended to support PB constraints first)
self.topv += 1
selv = self.topv
cl.append(self.topv)
self.oracle.add_clause(cl)
self.sels.append(selv)
if self.verbose > 1:
print('c formula: {0} vars, {1} hard, {2} soft'.format(formula.nv, len(formula.hard), len(formula.soft))) | 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 all introduced selectors is
stored in variable ``self.sels``.
:param formula: input MaxSAT formula
:type formula: :class:`WCNF`
"""
self.oracle = Solver(name=self.solver, bootstrap_with=formula.hard,
incr=True, use_timer=True)
for i, cl in enumerate(formula.soft):
# TODO: if clause is unit, use its literal as selector
# (ITotalizer must be extended to support PB constraints first)
self.topv += 1
selv = self.topv
cl.append(self.topv)
self.oracle.add_clause(cl)
self.sels.append(selv)
if self.verbose > 1:
print('c formula: {0} vars, {1} hard, {2} soft'.format(formula.nv, len(formula.hard), len(formula.soft))) | [
"def",
"_init",
"(",
"self",
",",
"formula",
")",
":",
"self",
".",
"oracle",
"=",
"Solver",
"(",
"name",
"=",
"self",
".",
"solver",
",",
"bootstrap_with",
"=",
"formula",
".",
"hard",
",",
"incr",
"=",
"True",
",",
"use_timer",
"=",
"True",
")",
"for",
"i",
",",
"cl",
"in",
"enumerate",
"(",
"formula",
".",
"soft",
")",
":",
"# TODO: if clause is unit, use its literal as selector",
"# (ITotalizer must be extended to support PB constraints first)",
"self",
".",
"topv",
"+=",
"1",
"selv",
"=",
"self",
".",
"topv",
"cl",
".",
"append",
"(",
"self",
".",
"topv",
")",
"self",
".",
"oracle",
".",
"add_clause",
"(",
"cl",
")",
"self",
".",
"sels",
".",
"append",
"(",
"selv",
")",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print",
"(",
"'c formula: {0} vars, {1} hard, {2} soft'",
".",
"format",
"(",
"formula",
".",
"nv",
",",
"len",
"(",
"formula",
".",
"hard",
")",
",",
"len",
"(",
"formula",
".",
"soft",
")",
")",
")"
] | 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 variable ``self.sels``.
:param formula: input MaxSAT formula
:type formula: :class:`WCNF` | [
"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",
"variable",
"self",
".",
"sels",
"."
] | 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
:param model: a satisfying assignment
:type formula: :class:`.WCNF`
:type model: list(int)
:rtype: int
"""
model_set = set(model)
cost = 0
for i, cl in enumerate(formula.soft):
cost += formula.wght[i] if all(l not in model_set for l in filter(lambda l: abs(l) <= self.formula.nv, cl)) else 0
return cost | 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
:param model: a satisfying assignment
:type formula: :class:`.WCNF`
:type model: list(int)
:rtype: int
"""
model_set = set(model)
cost = 0
for i, cl in enumerate(formula.soft):
cost += formula.wght[i] if all(l not in model_set for l in filter(lambda l: abs(l) <= self.formula.nv, cl)) else 0
return cost | [
"def",
"_get_model_cost",
"(",
"self",
",",
"formula",
",",
"model",
")",
":",
"model_set",
"=",
"set",
"(",
"model",
")",
"cost",
"=",
"0",
"for",
"i",
",",
"cl",
"in",
"enumerate",
"(",
"formula",
".",
"soft",
")",
":",
"cost",
"+=",
"formula",
".",
"wght",
"[",
"i",
"]",
"if",
"all",
"(",
"l",
"not",
"in",
"model_set",
"for",
"l",
"in",
"filter",
"(",
"lambda",
"l",
":",
"abs",
"(",
"l",
")",
"<=",
"self",
".",
"formula",
".",
"nv",
",",
"cl",
")",
")",
"else",
"0",
"return",
"cost"
] | 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:`.WCNF`
:type model: list(int)
:rtype: int | [
"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",
"."
] | 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.GetoptError as err:
sys.stderr.write(str(err).capitalize())
usage()
sys.exit(1)
adapt = False
exhaust = False
cmode = None
to_enum = 1
incr = False
blo = False
minz = False
solver = 'g3'
trim = 0
verbose = 1
for opt, arg in opts:
if opt in ('-a', '--adapt'):
adapt = True
elif opt in ('-c', '--comp'):
cmode = str(arg)
elif opt in ('-e', '--enum'):
to_enum = str(arg)
if to_enum != 'all':
to_enum = int(to_enum)
else:
to_enum = 0
elif opt in ('-h', '--help'):
usage()
sys.exit(0)
elif opt in ('-i', '--incr'):
incr = True
elif opt in ('-l', '--blo'):
blo = True
elif opt in ('-m', '--minimize'):
minz = True
elif opt in ('-s', '--solver'):
solver = str(arg)
elif opt in ('-t', '--trim'):
trim = int(arg)
elif opt in ('-v', '--verbose'):
verbose += 1
elif opt in ('-x', '--exhaust'):
exhaust = True
else:
assert False, 'Unhandled option: {0} {1}'.format(opt, arg)
return adapt, blo, cmode, to_enum, exhaust, incr, minz, solver, trim, \
verbose, args | 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.GetoptError as err:
sys.stderr.write(str(err).capitalize())
usage()
sys.exit(1)
adapt = False
exhaust = False
cmode = None
to_enum = 1
incr = False
blo = False
minz = False
solver = 'g3'
trim = 0
verbose = 1
for opt, arg in opts:
if opt in ('-a', '--adapt'):
adapt = True
elif opt in ('-c', '--comp'):
cmode = str(arg)
elif opt in ('-e', '--enum'):
to_enum = str(arg)
if to_enum != 'all':
to_enum = int(to_enum)
else:
to_enum = 0
elif opt in ('-h', '--help'):
usage()
sys.exit(0)
elif opt in ('-i', '--incr'):
incr = True
elif opt in ('-l', '--blo'):
blo = True
elif opt in ('-m', '--minimize'):
minz = True
elif opt in ('-s', '--solver'):
solver = str(arg)
elif opt in ('-t', '--trim'):
trim = int(arg)
elif opt in ('-v', '--verbose'):
verbose += 1
elif opt in ('-x', '--exhaust'):
exhaust = True
else:
assert False, 'Unhandled option: {0} {1}'.format(opt, arg)
return adapt, blo, cmode, to_enum, exhaust, incr, minz, solver, trim, \
verbose, args | [
"def",
"parse_options",
"(",
")",
":",
"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",
".",
"GetoptError",
"as",
"err",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"str",
"(",
"err",
")",
".",
"capitalize",
"(",
")",
")",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"adapt",
"=",
"False",
"exhaust",
"=",
"False",
"cmode",
"=",
"None",
"to_enum",
"=",
"1",
"incr",
"=",
"False",
"blo",
"=",
"False",
"minz",
"=",
"False",
"solver",
"=",
"'g3'",
"trim",
"=",
"0",
"verbose",
"=",
"1",
"for",
"opt",
",",
"arg",
"in",
"opts",
":",
"if",
"opt",
"in",
"(",
"'-a'",
",",
"'--adapt'",
")",
":",
"adapt",
"=",
"True",
"elif",
"opt",
"in",
"(",
"'-c'",
",",
"'--comp'",
")",
":",
"cmode",
"=",
"str",
"(",
"arg",
")",
"elif",
"opt",
"in",
"(",
"'-e'",
",",
"'--enum'",
")",
":",
"to_enum",
"=",
"str",
"(",
"arg",
")",
"if",
"to_enum",
"!=",
"'all'",
":",
"to_enum",
"=",
"int",
"(",
"to_enum",
")",
"else",
":",
"to_enum",
"=",
"0",
"elif",
"opt",
"in",
"(",
"'-h'",
",",
"'--help'",
")",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"elif",
"opt",
"in",
"(",
"'-i'",
",",
"'--incr'",
")",
":",
"incr",
"=",
"True",
"elif",
"opt",
"in",
"(",
"'-l'",
",",
"'--blo'",
")",
":",
"blo",
"=",
"True",
"elif",
"opt",
"in",
"(",
"'-m'",
",",
"'--minimize'",
")",
":",
"minz",
"=",
"True",
"elif",
"opt",
"in",
"(",
"'-s'",
",",
"'--solver'",
")",
":",
"solver",
"=",
"str",
"(",
"arg",
")",
"elif",
"opt",
"in",
"(",
"'-t'",
",",
"'--trim'",
")",
":",
"trim",
"=",
"int",
"(",
"arg",
")",
"elif",
"opt",
"in",
"(",
"'-v'",
",",
"'--verbose'",
")",
":",
"verbose",
"+=",
"1",
"elif",
"opt",
"in",
"(",
"'-x'",
",",
"'--exhaust'",
")",
":",
"exhaust",
"=",
"True",
"else",
":",
"assert",
"False",
",",
"'Unhandled option: {0} {1}'",
".",
"format",
"(",
"opt",
",",
"arg",
")",
"return",
"adapt",
",",
"blo",
",",
"cmode",
",",
"to_enum",
",",
"exhaust",
",",
"incr",
",",
"minz",
",",
"solver",
",",
"trim",
",",
"verbose",
",",
"args"
] | 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 minicard, there is nothing to free
for t in six.itervalues(self.tobj):
t.delete() | 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 minicard, there is nothing to free
for t in six.itervalues(self.tobj):
t.delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"oracle",
":",
"self",
".",
"oracle",
".",
"delete",
"(",
")",
"self",
".",
"oracle",
"=",
"None",
"if",
"self",
".",
"solver",
"!=",
"'mc'",
":",
"# for minicard, there is nothing to free",
"for",
"t",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"tobj",
")",
":",
"t",
".",
"delete",
"(",
")"
] | 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 only
# it must return 'unsatisfiable'
self.oracle.solve(assumptions=self.core)
# extract a new core
new_core = self.oracle.get_core()
if len(new_core) == len(self.core):
# stop if new core is not better than the previous one
break
# otherwise, update core
self.core = new_core | 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 only
# it must return 'unsatisfiable'
self.oracle.solve(assumptions=self.core)
# extract a new core
new_core = self.oracle.get_core()
if len(new_core) == len(self.core):
# stop if new core is not better than the previous one
break
# otherwise, update core
self.core = new_core | [
"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",
".",
"core",
")",
"# extract a new core",
"new_core",
"=",
"self",
".",
"oracle",
".",
"get_core",
"(",
")",
"if",
"len",
"(",
"new_core",
")",
"==",
"len",
"(",
"self",
".",
"core",
")",
":",
"# stop if new core is not better than the previous one",
"break",
"# otherwise, update core",
"self",
".",
"core",
"=",
"new_core"
] | 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 one by one while checking if the
remaining soft clauses together with the hard part of the
formula are unsatisfiable. Clauses that are necessary for
preserving unsatisfiability comprise an MUS of the input
formula (it is contained in the given unsatisfiable core)
and are reported as a result of the procedure.
During this core minimization procedure, all SAT calls are
dropped after obtaining 1000 conflicts.
"""
if self.minz and len(self.core) > 1:
self.core = sorted(self.core, key=lambda l: self.wght[l])
self.oracle.conf_budget(1000)
i = 0
while i < len(self.core):
to_test = self.core[:i] + self.core[(i + 1):]
if self.oracle.solve_limited(assumptions=to_test) == False:
self.core = to_test
else:
i += 1 | 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 one by one while checking if the
remaining soft clauses together with the hard part of the
formula are unsatisfiable. Clauses that are necessary for
preserving unsatisfiability comprise an MUS of the input
formula (it is contained in the given unsatisfiable core)
and are reported as a result of the procedure.
During this core minimization procedure, all SAT calls are
dropped after obtaining 1000 conflicts.
"""
if self.minz and len(self.core) > 1:
self.core = sorted(self.core, key=lambda l: self.wght[l])
self.oracle.conf_budget(1000)
i = 0
while i < len(self.core):
to_test = self.core[:i] + self.core[(i + 1):]
if self.oracle.solve_limited(assumptions=to_test) == False:
self.core = to_test
else:
i += 1 | [
"def",
"minimize_core",
"(",
"self",
")",
":",
"if",
"self",
".",
"minz",
"and",
"len",
"(",
"self",
".",
"core",
")",
">",
"1",
":",
"self",
".",
"core",
"=",
"sorted",
"(",
"self",
".",
"core",
",",
"key",
"=",
"lambda",
"l",
":",
"self",
".",
"wght",
"[",
"l",
"]",
")",
"self",
".",
"oracle",
".",
"conf_budget",
"(",
"1000",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"self",
".",
"core",
")",
":",
"to_test",
"=",
"self",
".",
"core",
"[",
":",
"i",
"]",
"+",
"self",
".",
"core",
"[",
"(",
"i",
"+",
"1",
")",
":",
"]",
"if",
"self",
".",
"oracle",
".",
"solve_limited",
"(",
"assumptions",
"=",
"to_test",
")",
"==",
"False",
":",
"self",
".",
"core",
"=",
"to_test",
"else",
":",
"i",
"+=",
"1"
] | 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
remaining soft clauses together with the hard part of the
formula are unsatisfiable. Clauses that are necessary for
preserving unsatisfiability comprise an MUS of the input
formula (it is contained in the given unsatisfiable core)
and are reported as a result of the procedure.
During this core minimization procedure, all SAT calls are
dropped after obtaining 1000 conflicts. | [
"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 increases the bound for the totalizer sum,
which involves adding the corresponding new clauses to the
internal SAT oracle.
The method returns the totalizer object followed by the
new bound obtained.
:param assump: assumption literal associated with the sum
:type assump: int
:rtype: :class:`.ITotalizer`, int
Note that if Minicard is used as a SAT oracle, native
cardinality constraints are used instead of
:class:`.ITotalizer`.
"""
# getting a totalizer object corresponding to assumption
t = self.tobj[assump]
# increment the current bound
b = self.bnds[assump] + 1
if self.solver != 'mc': # the case of standard totalizer encoding
# increasing its bound
t.increase(ubound=b, top_id=self.topv)
# updating top variable id
self.topv = t.top_id
# adding its clauses to oracle
if t.nof_new:
for cl in t.cnf.clauses[-t.nof_new:]:
self.oracle.add_clause(cl)
else: # the case of cardinality constraints represented natively
# right-hand side is always equal to the number of input literals
rhs = len(t.lits)
if b < rhs:
# creating an additional bound
if not t.rhs[b]:
self.topv += 1
t.rhs[b] = self.topv
# a new at-most-b constraint
amb = [[-t.rhs[b]] * (rhs - b) + t.lits, rhs]
self.oracle.add_atmost(*amb)
return t, b | 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 increases the bound for the totalizer sum,
which involves adding the corresponding new clauses to the
internal SAT oracle.
The method returns the totalizer object followed by the
new bound obtained.
:param assump: assumption literal associated with the sum
:type assump: int
:rtype: :class:`.ITotalizer`, int
Note that if Minicard is used as a SAT oracle, native
cardinality constraints are used instead of
:class:`.ITotalizer`.
"""
# getting a totalizer object corresponding to assumption
t = self.tobj[assump]
# increment the current bound
b = self.bnds[assump] + 1
if self.solver != 'mc': # the case of standard totalizer encoding
# increasing its bound
t.increase(ubound=b, top_id=self.topv)
# updating top variable id
self.topv = t.top_id
# adding its clauses to oracle
if t.nof_new:
for cl in t.cnf.clauses[-t.nof_new:]:
self.oracle.add_clause(cl)
else: # the case of cardinality constraints represented natively
# right-hand side is always equal to the number of input literals
rhs = len(t.lits)
if b < rhs:
# creating an additional bound
if not t.rhs[b]:
self.topv += 1
t.rhs[b] = self.topv
# a new at-most-b constraint
amb = [[-t.rhs[b]] * (rhs - b) + t.lits, rhs]
self.oracle.add_atmost(*amb)
return t, b | [
"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",
"if",
"self",
".",
"solver",
"!=",
"'mc'",
":",
"# the case of standard totalizer encoding",
"# increasing its bound",
"t",
".",
"increase",
"(",
"ubound",
"=",
"b",
",",
"top_id",
"=",
"self",
".",
"topv",
")",
"# updating top variable id",
"self",
".",
"topv",
"=",
"t",
".",
"top_id",
"# adding its clauses to oracle",
"if",
"t",
".",
"nof_new",
":",
"for",
"cl",
"in",
"t",
".",
"cnf",
".",
"clauses",
"[",
"-",
"t",
".",
"nof_new",
":",
"]",
":",
"self",
".",
"oracle",
".",
"add_clause",
"(",
"cl",
")",
"else",
":",
"# the case of cardinality constraints represented natively",
"# right-hand side is always equal to the number of input literals",
"rhs",
"=",
"len",
"(",
"t",
".",
"lits",
")",
"if",
"b",
"<",
"rhs",
":",
"# creating an additional bound",
"if",
"not",
"t",
".",
"rhs",
"[",
"b",
"]",
":",
"self",
".",
"topv",
"+=",
"1",
"t",
".",
"rhs",
"[",
"b",
"]",
"=",
"self",
".",
"topv",
"# a new at-most-b constraint",
"amb",
"=",
"[",
"[",
"-",
"t",
".",
"rhs",
"[",
"b",
"]",
"]",
"*",
"(",
"rhs",
"-",
"b",
")",
"+",
"t",
".",
"lits",
",",
"rhs",
"]",
"self",
".",
"oracle",
".",
"add_atmost",
"(",
"*",
"amb",
")",
"return",
"t",
",",
"b"
] | 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,
which involves adding the corresponding new clauses to the
internal SAT oracle.
The method returns the totalizer object followed by the
new bound obtained.
:param assump: assumption literal associated with the sum
:type assump: int
:rtype: :class:`.ITotalizer`, int
Note that if Minicard is used as a SAT oracle, native
cardinality constraints are used instead of
:class:`.ITotalizer`. | [
"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",
"."
] | 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 side
:type tobj: :class:`.ITotalizer`
:type rhs: int
"""
# saving the sum and its weight in a mapping
self.tobj[-tobj.rhs[rhs]] = tobj
self.bnds[-tobj.rhs[rhs]] = rhs
self.wght[-tobj.rhs[rhs]] = self.minw
# adding a new assumption to force the sum to be at most rhs
self.sums.append(-tobj.rhs[rhs]) | 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 side
:type tobj: :class:`.ITotalizer`
:type rhs: int
"""
# saving the sum and its weight in a mapping
self.tobj[-tobj.rhs[rhs]] = tobj
self.bnds[-tobj.rhs[rhs]] = rhs
self.wght[-tobj.rhs[rhs]] = self.minw
# adding a new assumption to force the sum to be at most rhs
self.sums.append(-tobj.rhs[rhs]) | [
"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",
"[",
"rhs",
"]",
"]",
"=",
"rhs",
"self",
".",
"wght",
"[",
"-",
"tobj",
".",
"rhs",
"[",
"rhs",
"]",
"]",
"=",
"self",
".",
"minw",
"# adding a new assumption to force the sum to be at most rhs",
"self",
".",
"sums",
".",
"append",
"(",
"-",
"tobj",
".",
"rhs",
"[",
"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`
:type rhs: int | [
"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
the core processing methods, i.e. in :func:`process_core`,
:func:`process_sels`, and :func:`process_sums`.
"""
self.sels = list(filter(lambda x: x not in self.garbage, self.sels))
self.sums = list(filter(lambda x: x not in self.garbage, self.sums))
self.bnds = {l: b for l, b in six.iteritems(self.bnds) if l not in self.garbage}
self.wght = {l: w for l, w in six.iteritems(self.wght) if l not in self.garbage}
self.garbage.clear() | 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
the core processing methods, i.e. in :func:`process_core`,
:func:`process_sels`, and :func:`process_sums`.
"""
self.sels = list(filter(lambda x: x not in self.garbage, self.sels))
self.sums = list(filter(lambda x: x not in self.garbage, self.sums))
self.bnds = {l: b for l, b in six.iteritems(self.bnds) if l not in self.garbage}
self.wght = {l: w for l, w in six.iteritems(self.wght) if l not in self.garbage}
self.garbage.clear() | [
"def",
"filter_assumps",
"(",
"self",
")",
":",
"self",
".",
"sels",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"not",
"in",
"self",
".",
"garbage",
",",
"self",
".",
"sels",
")",
")",
"self",
".",
"sums",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"not",
"in",
"self",
".",
"garbage",
",",
"self",
".",
"sums",
")",
")",
"self",
".",
"bnds",
"=",
"{",
"l",
":",
"b",
"for",
"l",
",",
"b",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"bnds",
")",
"if",
"l",
"not",
"in",
"self",
".",
"garbage",
"}",
"self",
".",
"wght",
"=",
"{",
"l",
":",
"w",
"for",
"l",
",",
"w",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"wght",
")",
"if",
"l",
"not",
"in",
"self",
".",
"garbage",
"}",
"self",
".",
"garbage",
".",
"clear",
"(",
")"
] | 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:`process_core`,
:func:`process_sels`, and :func:`process_sums`. | [
"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:
path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config']).decode(self.string_encoding)
path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '')
logger.info(msg='mecab-config is detected at {}'.format(path_mecab_config_dir))
return path_mecab_config_dir | 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:
path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config']).decode(self.string_encoding)
path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '')
logger.info(msg='mecab-config is detected at {}'.format(path_mecab_config_dir))
return path_mecab_config_dir | [
"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",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"'/mecab-config'",
",",
"''",
")",
"else",
":",
"path_mecab_config_dir",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'which'",
",",
"'mecab-config'",
"]",
")",
".",
"decode",
"(",
"self",
".",
"string_encoding",
")",
"path_mecab_config_dir",
"=",
"path_mecab_config_dir",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"'/mecab-config'",
",",
"''",
")",
"logger",
".",
"info",
"(",
"msg",
"=",
"'mecab-config is detected at {}'",
".",
"format",
"(",
"path_mecab_config_dir",
")",
")",
"return",
"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)
assert isinstance(is_feature, bool)
assert isinstance(is_surface, bool)
surface, features = analyzed_line.split('\t', 1)
tuple_pos, word_stem = self.__feature_parser(features, surface)
tokenized_obj = TokenizedResult(
node_obj=None,
analyzed_line=analyzed_line,
tuple_pos=tuple_pos,
word_stem=word_stem,
word_surface=surface,
is_feature=is_feature,
is_surface=is_surface
)
return tokenized_obj | 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)
assert isinstance(is_feature, bool)
assert isinstance(is_surface, bool)
surface, features = analyzed_line.split('\t', 1)
tuple_pos, word_stem = self.__feature_parser(features, surface)
tokenized_obj = TokenizedResult(
node_obj=None,
analyzed_line=analyzed_line,
tuple_pos=tuple_pos,
word_stem=word_stem,
word_surface=surface,
is_feature=is_feature,
is_surface=is_surface
)
return tokenized_obj | [
"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",
",",
"bool",
")",
"assert",
"isinstance",
"(",
"is_surface",
",",
"bool",
")",
"surface",
",",
"features",
"=",
"analyzed_line",
".",
"split",
"(",
"'\\t'",
",",
"1",
")",
"tuple_pos",
",",
"word_stem",
"=",
"self",
".",
"__feature_parser",
"(",
"features",
",",
"surface",
")",
"tokenized_obj",
"=",
"TokenizedResult",
"(",
"node_obj",
"=",
"None",
",",
"analyzed_line",
"=",
"analyzed_line",
",",
"tuple_pos",
"=",
"tuple_pos",
",",
"word_stem",
"=",
"word_stem",
",",
"word_surface",
"=",
"surface",
",",
"is_feature",
"=",
"is_feature",
",",
"is_surface",
"=",
"is_surface",
")",
"return",
"tokenized_obj"
] | 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: (Tuple[text_type,...])->bool
length_valid_pos_tuple = len(valid_pos_tuple)
if valid_pos_tuple == pos_tuple[:length_valid_pos_tuple]:
return True
else:
return False
seq_bool_flags = [is_valid_pos(valid_pos_tuple) for valid_pos_tuple in valid_pos]
if True in set(seq_bool_flags):
return True
else:
return False | 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: (Tuple[text_type,...])->bool
length_valid_pos_tuple = len(valid_pos_tuple)
if valid_pos_tuple == pos_tuple[:length_valid_pos_tuple]:
return True
else:
return False
seq_bool_flags = [is_valid_pos(valid_pos_tuple) for valid_pos_tuple in valid_pos]
if True in set(seq_bool_flags):
return True
else:
return False | [
"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",
"(",
"valid_pos_tuple",
")",
"if",
"valid_pos_tuple",
"==",
"pos_tuple",
"[",
":",
"length_valid_pos_tuple",
"]",
":",
"return",
"True",
"else",
":",
"return",
"False",
"seq_bool_flags",
"=",
"[",
"is_valid_pos",
"(",
"valid_pos_tuple",
")",
"for",
"valid_pos_tuple",
"in",
"valid_pos",
"]",
"if",
"True",
"in",
"set",
"(",
"seq_bool_flags",
")",
":",
"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 | [
"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
- List of Tuple which has POS element to keep.
- Keep in your mind, each tokenizer has different POS structure.
>>> [('名詞', '固有名詞'), ('動詞', )]
- stopwords
- List of str, which you'd like to remove
>>> ['残念', '今日']
"""
assert isinstance(tokenized_obj, TokenizedSenetence)
assert isinstance(valid_pos, list)
assert isinstance(stopwords, list)
filtered_tokens = []
for token_obj in tokenized_obj.tokenized_objects:
assert isinstance(token_obj, TokenizedResult)
if check_field_name=='stem':
res_stopwords = __is_sotpwords(token_obj.word_stem, stopwords)
else:
res_stopwords = __is_sotpwords(token_obj.word_surface, stopwords)
res_pos_condition = __is_valid_pos(token_obj.tuple_pos, valid_pos)
# case1: only pos filtering is ON
if valid_pos != [] and stopwords == []:
if res_pos_condition: filtered_tokens.append(token_obj)
# case2: only stopwords filtering is ON
if valid_pos == [] and stopwords != []:
if res_stopwords is False: filtered_tokens.append(token_obj)
# case3: both condition is ON
if valid_pos != [] and stopwords != []:
if res_stopwords is False and res_pos_condition: filtered_tokens.append(token_obj)
filtered_object = FilteredObject(
sentence=tokenized_obj.sentence,
tokenized_objects=filtered_tokens,
pos_condition=valid_pos,
stopwords=stopwords
)
return filtered_object | 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
- List of Tuple which has POS element to keep.
- Keep in your mind, each tokenizer has different POS structure.
>>> [('名詞', '固有名詞'), ('動詞', )]
- stopwords
- List of str, which you'd like to remove
>>> ['残念', '今日']
"""
assert isinstance(tokenized_obj, TokenizedSenetence)
assert isinstance(valid_pos, list)
assert isinstance(stopwords, list)
filtered_tokens = []
for token_obj in tokenized_obj.tokenized_objects:
assert isinstance(token_obj, TokenizedResult)
if check_field_name=='stem':
res_stopwords = __is_sotpwords(token_obj.word_stem, stopwords)
else:
res_stopwords = __is_sotpwords(token_obj.word_surface, stopwords)
res_pos_condition = __is_valid_pos(token_obj.tuple_pos, valid_pos)
# case1: only pos filtering is ON
if valid_pos != [] and stopwords == []:
if res_pos_condition: filtered_tokens.append(token_obj)
# case2: only stopwords filtering is ON
if valid_pos == [] and stopwords != []:
if res_stopwords is False: filtered_tokens.append(token_obj)
# case3: both condition is ON
if valid_pos != [] and stopwords != []:
if res_stopwords is False and res_pos_condition: filtered_tokens.append(token_obj)
filtered_object = FilteredObject(
sentence=tokenized_obj.sentence,
tokenized_objects=filtered_tokens,
pos_condition=valid_pos,
stopwords=stopwords
)
return filtered_object | [
"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",
",",
"TokenizedSenetence",
")",
"assert",
"isinstance",
"(",
"valid_pos",
",",
"list",
")",
"assert",
"isinstance",
"(",
"stopwords",
",",
"list",
")",
"filtered_tokens",
"=",
"[",
"]",
"for",
"token_obj",
"in",
"tokenized_obj",
".",
"tokenized_objects",
":",
"assert",
"isinstance",
"(",
"token_obj",
",",
"TokenizedResult",
")",
"if",
"check_field_name",
"==",
"'stem'",
":",
"res_stopwords",
"=",
"__is_sotpwords",
"(",
"token_obj",
".",
"word_stem",
",",
"stopwords",
")",
"else",
":",
"res_stopwords",
"=",
"__is_sotpwords",
"(",
"token_obj",
".",
"word_surface",
",",
"stopwords",
")",
"res_pos_condition",
"=",
"__is_valid_pos",
"(",
"token_obj",
".",
"tuple_pos",
",",
"valid_pos",
")",
"# case1: only pos filtering is ON",
"if",
"valid_pos",
"!=",
"[",
"]",
"and",
"stopwords",
"==",
"[",
"]",
":",
"if",
"res_pos_condition",
":",
"filtered_tokens",
".",
"append",
"(",
"token_obj",
")",
"# case2: only stopwords filtering is ON",
"if",
"valid_pos",
"==",
"[",
"]",
"and",
"stopwords",
"!=",
"[",
"]",
":",
"if",
"res_stopwords",
"is",
"False",
":",
"filtered_tokens",
".",
"append",
"(",
"token_obj",
")",
"# case3: both condition is ON",
"if",
"valid_pos",
"!=",
"[",
"]",
"and",
"stopwords",
"!=",
"[",
"]",
":",
"if",
"res_stopwords",
"is",
"False",
"and",
"res_pos_condition",
":",
"filtered_tokens",
".",
"append",
"(",
"token_obj",
")",
"filtered_object",
"=",
"FilteredObject",
"(",
"sentence",
"=",
"tokenized_obj",
".",
"sentence",
",",
"tokenized_objects",
"=",
"filtered_tokens",
",",
"pos_condition",
"=",
"valid_pos",
",",
"stopwords",
"=",
"stopwords",
")",
"return",
"filtered_object"
] | 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 of str, which you'd like to remove
>>> ['残念', '今日'] | [
"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 isinstance(token_object, TokenizedResult)
if is_denormalize:
if token_object.is_feature == True:
if token_object.is_surface == True:
token = (func_denormalizer(token_object.word_surface), token_object.tuple_pos)
else:
token = (func_denormalizer(token_object.word_stem), token_object.tuple_pos)
else:
if token_object.is_surface == True:
token = func_denormalizer(token_object.word_surface)
else:
token = func_denormalizer(token_object.word_stem)
else:
if token_object.is_feature == True:
if token_object.is_surface == True:
token = (token_object.word_surface, token_object.tuple_pos)
else:
token = (token_object.word_stem, token_object.tuple_pos)
else:
if token_object.is_surface == True:
token = token_object.word_surface
else:
token = token_object.word_stem
return token | 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 isinstance(token_object, TokenizedResult)
if is_denormalize:
if token_object.is_feature == True:
if token_object.is_surface == True:
token = (func_denormalizer(token_object.word_surface), token_object.tuple_pos)
else:
token = (func_denormalizer(token_object.word_stem), token_object.tuple_pos)
else:
if token_object.is_surface == True:
token = func_denormalizer(token_object.word_surface)
else:
token = func_denormalizer(token_object.word_stem)
else:
if token_object.is_feature == True:
if token_object.is_surface == True:
token = (token_object.word_surface, token_object.tuple_pos)
else:
token = (token_object.word_stem, token_object.tuple_pos)
else:
if token_object.is_surface == True:
token = token_object.word_surface
else:
token = token_object.word_stem
return token | [
"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",
",",
"TokenizedResult",
")",
"if",
"is_denormalize",
":",
"if",
"token_object",
".",
"is_feature",
"==",
"True",
":",
"if",
"token_object",
".",
"is_surface",
"==",
"True",
":",
"token",
"=",
"(",
"func_denormalizer",
"(",
"token_object",
".",
"word_surface",
")",
",",
"token_object",
".",
"tuple_pos",
")",
"else",
":",
"token",
"=",
"(",
"func_denormalizer",
"(",
"token_object",
".",
"word_stem",
")",
",",
"token_object",
".",
"tuple_pos",
")",
"else",
":",
"if",
"token_object",
".",
"is_surface",
"==",
"True",
":",
"token",
"=",
"func_denormalizer",
"(",
"token_object",
".",
"word_surface",
")",
"else",
":",
"token",
"=",
"func_denormalizer",
"(",
"token_object",
".",
"word_stem",
")",
"else",
":",
"if",
"token_object",
".",
"is_feature",
"==",
"True",
":",
"if",
"token_object",
".",
"is_surface",
"==",
"True",
":",
"token",
"=",
"(",
"token_object",
".",
"word_surface",
",",
"token_object",
".",
"tuple_pos",
")",
"else",
":",
"token",
"=",
"(",
"token_object",
".",
"word_stem",
",",
"token_object",
".",
"tuple_pos",
")",
"else",
":",
"if",
"token_object",
".",
"is_surface",
"==",
"True",
":",
"token",
"=",
"token_object",
".",
"word_surface",
"else",
":",
"token",
"=",
"token_object",
".",
"word_stem",
"return",
"token"
] | 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(notification, Notification):
raise TypeError("state must be an instance of Notification")
state = notification.value
if state.constant is not None and value:
raise ValueError(
"State %s should contain only constant value %r" % (state.name, state.constant),
state.name, state.constant
)
line = "%s=%s" % (
state.name,
state.constant if state.constant is not None else state.type(value)
)
log.debug("Send %r into systemd", line)
try:
return sd_notify(line, unset_environment)
except Exception as e:
log.error("%s", e) | 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(notification, Notification):
raise TypeError("state must be an instance of Notification")
state = notification.value
if state.constant is not None and value:
raise ValueError(
"State %s should contain only constant value %r" % (state.name, state.constant),
state.name, state.constant
)
line = "%s=%s" % (
state.name,
state.constant if state.constant is not None else state.type(value)
)
log.debug("Send %r into systemd", line)
try:
return sd_notify(line, unset_environment)
except Exception as e:
log.error("%s", e) | [
"def",
"notify",
"(",
"notification",
",",
"value",
"=",
"None",
",",
"unset_environment",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"notification",
",",
"Notification",
")",
":",
"raise",
"TypeError",
"(",
"\"state must be an instance of Notification\"",
")",
"state",
"=",
"notification",
".",
"value",
"if",
"state",
".",
"constant",
"is",
"not",
"None",
"and",
"value",
":",
"raise",
"ValueError",
"(",
"\"State %s should contain only constant value %r\"",
"%",
"(",
"state",
".",
"name",
",",
"state",
".",
"constant",
")",
",",
"state",
".",
"name",
",",
"state",
".",
"constant",
")",
"line",
"=",
"\"%s=%s\"",
"%",
"(",
"state",
".",
"name",
",",
"state",
".",
"constant",
"if",
"state",
".",
"constant",
"is",
"not",
"None",
"else",
"state",
".",
"type",
"(",
"value",
")",
")",
"log",
".",
"debug",
"(",
"\"Send %r into systemd\"",
",",
"line",
")",
"try",
":",
"return",
"sd_notify",
"(",
"line",
",",
"unset_environment",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"error",
"(",
"\"%s\"",
",",
"e",
")"
] | 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 same time
if src_path.endswith(('.pyc', '.pyo')):
py_path = get_py_path(src_path)
if os.path.exists(py_path):
src_path = py_path
yield src_path | 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 same time
if src_path.endswith(('.pyc', '.pyo')):
py_path = get_py_path(src_path)
if os.path.exists(py_path):
src_path = py_path
yield src_path | [
"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",
"if",
"src_path",
".",
"endswith",
"(",
"(",
"'.pyc'",
",",
"'.pyo'",
")",
")",
":",
"py_path",
"=",
"get_py_path",
"(",
"src_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"py_path",
")",
":",
"src_path",
"=",
"py_path",
"yield",
"src_path"
] | 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