id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
228,100
sassoftware/saspy
saspy/sasiostdio.py
SASsessionSTDIO.exist
def exist(self, table: str, libref: str ="") -> bool: """ table - the name of the SAS Data Set libref - the libref for the Data Set, defaults to WORK, or USER if assigned Returns True it the Data Set exists and False if it does not """ code = "data _null_; e = exist('" if len(libref): code += libref+"." code += table+"');\n" code += "v = exist('" if len(libref): code += libref+"." code += table+"', 'VIEW');\n if e or v then e = 1;\n" code += "te='TABLE_EXISTS='; put te e;run;" ll = self.submit(code, "text") l2 = ll['LOG'].rpartition("TABLE_EXISTS= ") l2 = l2[2].partition("\n") exists = int(l2[0]) return bool(exists)
python
def exist(self, table: str, libref: str ="") -> bool: """ table - the name of the SAS Data Set libref - the libref for the Data Set, defaults to WORK, or USER if assigned Returns True it the Data Set exists and False if it does not """ code = "data _null_; e = exist('" if len(libref): code += libref+"." code += table+"');\n" code += "v = exist('" if len(libref): code += libref+"." code += table+"', 'VIEW');\n if e or v then e = 1;\n" code += "te='TABLE_EXISTS='; put te e;run;" ll = self.submit(code, "text") l2 = ll['LOG'].rpartition("TABLE_EXISTS= ") l2 = l2[2].partition("\n") exists = int(l2[0]) return bool(exists)
[ "def", "exist", "(", "self", ",", "table", ":", "str", ",", "libref", ":", "str", "=", "\"\"", ")", "->", "bool", ":", "code", "=", "\"data _null_; e = exist('\"", "if", "len", "(", "libref", ")", ":", "code", "+=", "libref", "+", "\".\"", "code", "+=", "table", "+", "\"');\\n\"", "code", "+=", "\"v = exist('\"", "if", "len", "(", "libref", ")", ":", "code", "+=", "libref", "+", "\".\"", "code", "+=", "table", "+", "\"', 'VIEW');\\n if e or v then e = 1;\\n\"", "code", "+=", "\"te='TABLE_EXISTS='; put te e;run;\"", "ll", "=", "self", ".", "submit", "(", "code", ",", "\"text\"", ")", "l2", "=", "ll", "[", "'LOG'", "]", ".", "rpartition", "(", "\"TABLE_EXISTS= \"", ")", "l2", "=", "l2", "[", "2", "]", ".", "partition", "(", "\"\\n\"", ")", "exists", "=", "int", "(", "l2", "[", "0", "]", ")", "return", "bool", "(", "exists", ")" ]
table - the name of the SAS Data Set libref - the libref for the Data Set, defaults to WORK, or USER if assigned Returns True it the Data Set exists and False if it does not
[ "table", "-", "the", "name", "of", "the", "SAS", "Data", "Set", "libref", "-", "the", "libref", "for", "the", "Data", "Set", "defaults", "to", "WORK", "or", "USER", "if", "assigned" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasiostdio.py#L900-L923
228,101
sassoftware/saspy
saspy/sasdata.py
SASdata.set_results
def set_results(self, results: str): """ This method set the results attribute for the SASdata object; it stays in effect till changed results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'. :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :return: None """ if results.upper() == "HTML": self.HTML = 1 else: self.HTML = 0 self.results = results
python
def set_results(self, results: str): """ This method set the results attribute for the SASdata object; it stays in effect till changed results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'. :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :return: None """ if results.upper() == "HTML": self.HTML = 1 else: self.HTML = 0 self.results = results
[ "def", "set_results", "(", "self", ",", "results", ":", "str", ")", ":", "if", "results", ".", "upper", "(", ")", "==", "\"HTML\"", ":", "self", ".", "HTML", "=", "1", "else", ":", "self", ".", "HTML", "=", "0", "self", ".", "results", "=", "results" ]
This method set the results attribute for the SASdata object; it stays in effect till changed results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'. :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :return: None
[ "This", "method", "set", "the", "results", "attribute", "for", "the", "SASdata", "object", ";", "it", "stays", "in", "effect", "till", "changed", "results", "-", "set", "the", "default", "result", "type", "for", "this", "SASdata", "object", ".", "Pandas", "or", "HTML", "or", "TEXT", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L116-L128
228,102
sassoftware/saspy
saspy/sasdata.py
SASdata._returnPD
def _returnPD(self, code, tablename, **kwargs): """ private function to take a sas code normally to create a table, generate pandas data frame and cleanup. :param code: string of SAS code :param tablename: the name of the SAS Data Set :param kwargs: :return: Pandas Data Frame """ libref = kwargs.get('libref','work') ll = self.sas._io.submit(code) check, errorMsg = self._checkLogForError(ll['LOG']) if not check: raise ValueError("Internal code execution failed: " + errorMsg) if isinstance(tablename, str): pd = self.sas.sasdata2dataframe(tablename, libref) self.sas._io.submit("proc delete data=%s.%s; run;" % (libref, tablename)) elif isinstance(tablename, list): pd = dict() for t in tablename: # strip leading '_' from names and capitalize for dictionary labels if self.sas.exist(t, libref): pd[t.replace('_', '').capitalize()] = self.sas.sasdata2dataframe(t, libref) self.sas._io.submit("proc delete data=%s.%s; run;" % (libref, t)) else: raise SyntaxError("The tablename must be a string or list %s was submitted" % str(type(tablename))) return pd
python
def _returnPD(self, code, tablename, **kwargs): """ private function to take a sas code normally to create a table, generate pandas data frame and cleanup. :param code: string of SAS code :param tablename: the name of the SAS Data Set :param kwargs: :return: Pandas Data Frame """ libref = kwargs.get('libref','work') ll = self.sas._io.submit(code) check, errorMsg = self._checkLogForError(ll['LOG']) if not check: raise ValueError("Internal code execution failed: " + errorMsg) if isinstance(tablename, str): pd = self.sas.sasdata2dataframe(tablename, libref) self.sas._io.submit("proc delete data=%s.%s; run;" % (libref, tablename)) elif isinstance(tablename, list): pd = dict() for t in tablename: # strip leading '_' from names and capitalize for dictionary labels if self.sas.exist(t, libref): pd[t.replace('_', '').capitalize()] = self.sas.sasdata2dataframe(t, libref) self.sas._io.submit("proc delete data=%s.%s; run;" % (libref, t)) else: raise SyntaxError("The tablename must be a string or list %s was submitted" % str(type(tablename))) return pd
[ "def", "_returnPD", "(", "self", ",", "code", ",", "tablename", ",", "*", "*", "kwargs", ")", ":", "libref", "=", "kwargs", ".", "get", "(", "'libref'", ",", "'work'", ")", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ")", "check", ",", "errorMsg", "=", "self", ".", "_checkLogForError", "(", "ll", "[", "'LOG'", "]", ")", "if", "not", "check", ":", "raise", "ValueError", "(", "\"Internal code execution failed: \"", "+", "errorMsg", ")", "if", "isinstance", "(", "tablename", ",", "str", ")", ":", "pd", "=", "self", ".", "sas", ".", "sasdata2dataframe", "(", "tablename", ",", "libref", ")", "self", ".", "sas", ".", "_io", ".", "submit", "(", "\"proc delete data=%s.%s; run;\"", "%", "(", "libref", ",", "tablename", ")", ")", "elif", "isinstance", "(", "tablename", ",", "list", ")", ":", "pd", "=", "dict", "(", ")", "for", "t", "in", "tablename", ":", "# strip leading '_' from names and capitalize for dictionary labels", "if", "self", ".", "sas", ".", "exist", "(", "t", ",", "libref", ")", ":", "pd", "[", "t", ".", "replace", "(", "'_'", ",", "''", ")", ".", "capitalize", "(", ")", "]", "=", "self", ".", "sas", ".", "sasdata2dataframe", "(", "t", ",", "libref", ")", "self", ".", "sas", ".", "_io", ".", "submit", "(", "\"proc delete data=%s.%s; run;\"", "%", "(", "libref", ",", "t", ")", ")", "else", ":", "raise", "SyntaxError", "(", "\"The tablename must be a string or list %s was submitted\"", "%", "str", "(", "type", "(", "tablename", ")", ")", ")", "return", "pd" ]
private function to take a sas code normally to create a table, generate pandas data frame and cleanup. :param code: string of SAS code :param tablename: the name of the SAS Data Set :param kwargs: :return: Pandas Data Frame
[ "private", "function", "to", "take", "a", "sas", "code", "normally", "to", "create", "a", "table", "generate", "pandas", "data", "frame", "and", "cleanup", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L145-L172
228,103
sassoftware/saspy
saspy/sasdata.py
SASdata.where
def where(self, where: str) -> 'SASdata': """ This method returns a clone of the SASdata object, with the where attribute set. The original SASdata object is not affected. :param where: the where clause to apply :return: SAS data object """ sd = SASdata(self.sas, self.libref, self.table, dsopts=dict(self.dsopts)) sd.HTML = self.HTML sd.dsopts['where'] = where return sd
python
def where(self, where: str) -> 'SASdata': """ This method returns a clone of the SASdata object, with the where attribute set. The original SASdata object is not affected. :param where: the where clause to apply :return: SAS data object """ sd = SASdata(self.sas, self.libref, self.table, dsopts=dict(self.dsopts)) sd.HTML = self.HTML sd.dsopts['where'] = where return sd
[ "def", "where", "(", "self", ",", "where", ":", "str", ")", "->", "'SASdata'", ":", "sd", "=", "SASdata", "(", "self", ".", "sas", ",", "self", ".", "libref", ",", "self", ".", "table", ",", "dsopts", "=", "dict", "(", "self", ".", "dsopts", ")", ")", "sd", ".", "HTML", "=", "self", ".", "HTML", "sd", ".", "dsopts", "[", "'where'", "]", "=", "where", "return", "sd" ]
This method returns a clone of the SASdata object, with the where attribute set. The original SASdata object is not affected. :param where: the where clause to apply :return: SAS data object
[ "This", "method", "returns", "a", "clone", "of", "the", "SASdata", "object", "with", "the", "where", "attribute", "set", ".", "The", "original", "SASdata", "object", "is", "not", "affected", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L180-L190
228,104
sassoftware/saspy
saspy/sasdata.py
SASdata.head
def head(self, obs=5): """ display the first n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return: """ topts = dict(self.dsopts) topts['obs'] = obs code = "proc print data=" + self.libref + '.' + self.table + self.sas._dsopts(topts) + ";run;" if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "data _head ; set %s.%s %s; run;" % (self.libref, self.table, self.sas._dsopts(topts)) return self._returnPD(code, '_head') else: ll = self._is_valid() if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
python
def head(self, obs=5): """ display the first n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return: """ topts = dict(self.dsopts) topts['obs'] = obs code = "proc print data=" + self.libref + '.' + self.table + self.sas._dsopts(topts) + ";run;" if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "data _head ; set %s.%s %s; run;" % (self.libref, self.table, self.sas._dsopts(topts)) return self._returnPD(code, '_head') else: ll = self._is_valid() if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
[ "def", "head", "(", "self", ",", "obs", "=", "5", ")", ":", "topts", "=", "dict", "(", "self", ".", "dsopts", ")", "topts", "[", "'obs'", "]", "=", "obs", "code", "=", "\"proc print data=\"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "sas", ".", "_dsopts", "(", "topts", ")", "+", "\";run;\"", "if", "self", ".", "sas", ".", "nosub", ":", "print", "(", "code", ")", "return", "if", "self", ".", "results", ".", "upper", "(", ")", "==", "'PANDAS'", ":", "code", "=", "\"data _head ; set %s.%s %s; run;\"", "%", "(", "self", ".", "libref", ",", "self", ".", "table", ",", "self", ".", "sas", ".", "_dsopts", "(", "topts", ")", ")", "return", "self", ".", "_returnPD", "(", "code", ",", "'_head'", ")", "else", ":", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", "self", ".", "HTML", ":", "if", "not", "ll", ":", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ")", "if", "not", "self", ".", "sas", ".", "batch", ":", "self", ".", "sas", ".", "DISPLAY", "(", "self", ".", "sas", ".", "HTML", "(", "ll", "[", "'LST'", "]", ")", ")", "else", ":", "return", "ll", "else", ":", "if", "not", "ll", ":", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ",", "\"text\"", ")", "if", "not", "self", ".", "sas", ".", "batch", ":", "print", "(", "ll", "[", "'LST'", "]", ")", "else", ":", "return", "ll" ]
display the first n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return:
[ "display", "the", "first", "n", "rows", "of", "a", "table" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L192-L225
228,105
sassoftware/saspy
saspy/sasdata.py
SASdata.tail
def tail(self, obs=5): """ display the last n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return: """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" nosub = self.sas.nosub self.sas.nosub = False le = self._is_valid() if not le: ll = self.sas.submit(code, "text") lastobs = ll['LOG'].rpartition("lastobs=") lastobs = lastobs[2].partition(" tom") lastobs = int(lastobs[0]) else: lastobs = obs firstobs = lastobs - (obs - 1) if firstobs < 1: firstobs = 1 topts = dict(self.dsopts) topts['obs'] = lastobs topts['firstobs'] = firstobs code = "proc print data=" + self.libref + '.' + self.table + self.sas._dsopts(topts) + ";run;" self.sas.nosub = nosub if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "data _tail ; set %s.%s %s; run;" % (self.libref, self.table, self.sas._dsopts(topts)) return self._returnPD(code, '_tail') else: if self.HTML: if not le: ll = self.sas._io.submit(code) else: ll = le if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not le: ll = self.sas._io.submit(code, "text") else: ll = le if not self.sas.batch: print(ll['LST']) else: return ll
python
def tail(self, obs=5): """ display the last n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return: """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" nosub = self.sas.nosub self.sas.nosub = False le = self._is_valid() if not le: ll = self.sas.submit(code, "text") lastobs = ll['LOG'].rpartition("lastobs=") lastobs = lastobs[2].partition(" tom") lastobs = int(lastobs[0]) else: lastobs = obs firstobs = lastobs - (obs - 1) if firstobs < 1: firstobs = 1 topts = dict(self.dsopts) topts['obs'] = lastobs topts['firstobs'] = firstobs code = "proc print data=" + self.libref + '.' + self.table + self.sas._dsopts(topts) + ";run;" self.sas.nosub = nosub if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "data _tail ; set %s.%s %s; run;" % (self.libref, self.table, self.sas._dsopts(topts)) return self._returnPD(code, '_tail') else: if self.HTML: if not le: ll = self.sas._io.submit(code) else: ll = le if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not le: ll = self.sas._io.submit(code, "text") else: ll = le if not self.sas.batch: print(ll['LST']) else: return ll
[ "def", "tail", "(", "self", ",", "obs", "=", "5", ")", ":", "code", "=", "\"proc sql;select count(*) format best32. into :lastobs from \"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "_dsopts", "(", ")", "+", "\";%put lastobs=&lastobs tom;quit;\"", "nosub", "=", "self", ".", "sas", ".", "nosub", "self", ".", "sas", ".", "nosub", "=", "False", "le", "=", "self", ".", "_is_valid", "(", ")", "if", "not", "le", ":", "ll", "=", "self", ".", "sas", ".", "submit", "(", "code", ",", "\"text\"", ")", "lastobs", "=", "ll", "[", "'LOG'", "]", ".", "rpartition", "(", "\"lastobs=\"", ")", "lastobs", "=", "lastobs", "[", "2", "]", ".", "partition", "(", "\" tom\"", ")", "lastobs", "=", "int", "(", "lastobs", "[", "0", "]", ")", "else", ":", "lastobs", "=", "obs", "firstobs", "=", "lastobs", "-", "(", "obs", "-", "1", ")", "if", "firstobs", "<", "1", ":", "firstobs", "=", "1", "topts", "=", "dict", "(", "self", ".", "dsopts", ")", "topts", "[", "'obs'", "]", "=", "lastobs", "topts", "[", "'firstobs'", "]", "=", "firstobs", "code", "=", "\"proc print data=\"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "sas", ".", "_dsopts", "(", "topts", ")", "+", "\";run;\"", "self", ".", "sas", ".", "nosub", "=", "nosub", "if", "self", ".", "sas", ".", "nosub", ":", "print", "(", "code", ")", "return", "if", "self", ".", "results", ".", "upper", "(", ")", "==", "'PANDAS'", ":", "code", "=", "\"data _tail ; set %s.%s %s; run;\"", "%", "(", "self", ".", "libref", ",", "self", ".", "table", ",", "self", ".", "sas", ".", "_dsopts", "(", "topts", ")", ")", "return", "self", ".", "_returnPD", "(", "code", ",", "'_tail'", ")", "else", ":", "if", "self", ".", "HTML", ":", "if", "not", "le", ":", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ")", "else", ":", "ll", "=", "le", "if", "not", "self", ".", "sas", ".", "batch", ":", "self", ".", "sas", ".", "DISPLAY", "(", "self", ".", "sas", ".", "HTML", "(", "ll", "[", "'LST'", "]", ")", ")", "else", ":", "return", "ll", "else", ":", "if", "not", "le", ":", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ",", "\"text\"", ")", "else", ":", "ll", "=", "le", "if", "not", "self", ".", "sas", ".", "batch", ":", "print", "(", "ll", "[", "'LST'", "]", ")", "else", ":", "return", "ll" ]
display the last n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return:
[ "display", "the", "last", "n", "rows", "of", "a", "table" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L227-L285
228,106
sassoftware/saspy
saspy/sasdata.py
SASdata.obs
def obs(self): """ return the number of observations for your SASdata object """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" if self.sas.nosub: print(code) return le = self._is_valid() if not le: ll = self.sas.submit(code, "text") lastobs = ll['LOG'].rpartition("lastobs=") lastobs = lastobs[2].partition(" tom") lastobs = int(lastobs[0]) else: print("The SASdata object is not valid. The table doesn't exist in this SAS session at this time.") lastobs = None return lastobs
python
def obs(self): """ return the number of observations for your SASdata object """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" if self.sas.nosub: print(code) return le = self._is_valid() if not le: ll = self.sas.submit(code, "text") lastobs = ll['LOG'].rpartition("lastobs=") lastobs = lastobs[2].partition(" tom") lastobs = int(lastobs[0]) else: print("The SASdata object is not valid. The table doesn't exist in this SAS session at this time.") lastobs = None return lastobs
[ "def", "obs", "(", "self", ")", ":", "code", "=", "\"proc sql;select count(*) format best32. into :lastobs from \"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "_dsopts", "(", ")", "+", "\";%put lastobs=&lastobs tom;quit;\"", "if", "self", ".", "sas", ".", "nosub", ":", "print", "(", "code", ")", "return", "le", "=", "self", ".", "_is_valid", "(", ")", "if", "not", "le", ":", "ll", "=", "self", ".", "sas", ".", "submit", "(", "code", ",", "\"text\"", ")", "lastobs", "=", "ll", "[", "'LOG'", "]", ".", "rpartition", "(", "\"lastobs=\"", ")", "lastobs", "=", "lastobs", "[", "2", "]", ".", "partition", "(", "\" tom\"", ")", "lastobs", "=", "int", "(", "lastobs", "[", "0", "]", ")", "else", ":", "print", "(", "\"The SASdata object is not valid. The table doesn't exist in this SAS session at this time.\"", ")", "lastobs", "=", "None", "return", "lastobs" ]
return the number of observations for your SASdata object
[ "return", "the", "number", "of", "observations", "for", "your", "SASdata", "object" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L287-L308
228,107
sassoftware/saspy
saspy/sasdata.py
SASdata.contents
def contents(self): """ display metadata about the table. size, number of rows, columns and their data type ... :return: output """ code = "proc contents data=" + self.libref + '.' + self.table + self._dsopts() + ";run;" if self.sas.nosub: print(code) return ll = self._is_valid() if self.results.upper() == 'PANDAS': code = "proc contents data=%s.%s %s ;" % (self.libref, self.table, self._dsopts()) code += "ods output Attributes=work._attributes;" code += "ods output EngineHost=work._EngineHost;" code += "ods output Variables=work._Variables;" code += "ods output Sortedby=work._Sortedby;" code += "run;" return self._returnPD(code, ['_attributes', '_EngineHost', '_Variables', '_Sortedby']) else: if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
python
def contents(self): """ display metadata about the table. size, number of rows, columns and their data type ... :return: output """ code = "proc contents data=" + self.libref + '.' + self.table + self._dsopts() + ";run;" if self.sas.nosub: print(code) return ll = self._is_valid() if self.results.upper() == 'PANDAS': code = "proc contents data=%s.%s %s ;" % (self.libref, self.table, self._dsopts()) code += "ods output Attributes=work._attributes;" code += "ods output EngineHost=work._EngineHost;" code += "ods output Variables=work._Variables;" code += "ods output Sortedby=work._Sortedby;" code += "run;" return self._returnPD(code, ['_attributes', '_EngineHost', '_Variables', '_Sortedby']) else: if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
[ "def", "contents", "(", "self", ")", ":", "code", "=", "\"proc contents data=\"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "_dsopts", "(", ")", "+", "\";run;\"", "if", "self", ".", "sas", ".", "nosub", ":", "print", "(", "code", ")", "return", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", "self", ".", "results", ".", "upper", "(", ")", "==", "'PANDAS'", ":", "code", "=", "\"proc contents data=%s.%s %s ;\"", "%", "(", "self", ".", "libref", ",", "self", ".", "table", ",", "self", ".", "_dsopts", "(", ")", ")", "code", "+=", "\"ods output Attributes=work._attributes;\"", "code", "+=", "\"ods output EngineHost=work._EngineHost;\"", "code", "+=", "\"ods output Variables=work._Variables;\"", "code", "+=", "\"ods output Sortedby=work._Sortedby;\"", "code", "+=", "\"run;\"", "return", "self", ".", "_returnPD", "(", "code", ",", "[", "'_attributes'", ",", "'_EngineHost'", ",", "'_Variables'", ",", "'_Sortedby'", "]", ")", "else", ":", "if", "self", ".", "HTML", ":", "if", "not", "ll", ":", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ")", "if", "not", "self", ".", "sas", ".", "batch", ":", "self", ".", "sas", ".", "DISPLAY", "(", "self", ".", "sas", ".", "HTML", "(", "ll", "[", "'LST'", "]", ")", ")", "else", ":", "return", "ll", "else", ":", "if", "not", "ll", ":", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ",", "\"text\"", ")", "if", "not", "self", ".", "sas", ".", "batch", ":", "print", "(", "ll", "[", "'LST'", "]", ")", "else", ":", "return", "ll" ]
display metadata about the table. size, number of rows, columns and their data type ... :return: output
[ "display", "metadata", "about", "the", "table", ".", "size", "number", "of", "rows", "columns", "and", "their", "data", "type", "..." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L449-L485
228,108
sassoftware/saspy
saspy/sasdata.py
SASdata.columnInfo
def columnInfo(self): """ display metadata about the table, size, number of rows, columns and their data type """ code = "proc contents data=" + self.libref + '.' + self.table + ' ' + self._dsopts() + ";ods select Variables;run;" if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "proc contents data=%s.%s %s ;ods output Variables=work._variables ;run;" % (self.libref, self.table, self._dsopts()) pd = self._returnPD(code, '_variables') pd['Type'] = pd['Type'].str.rstrip() return pd else: ll = self._is_valid() if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
python
def columnInfo(self): """ display metadata about the table, size, number of rows, columns and their data type """ code = "proc contents data=" + self.libref + '.' + self.table + ' ' + self._dsopts() + ";ods select Variables;run;" if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "proc contents data=%s.%s %s ;ods output Variables=work._variables ;run;" % (self.libref, self.table, self._dsopts()) pd = self._returnPD(code, '_variables') pd['Type'] = pd['Type'].str.rstrip() return pd else: ll = self._is_valid() if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
[ "def", "columnInfo", "(", "self", ")", ":", "code", "=", "\"proc contents data=\"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "' '", "+", "self", ".", "_dsopts", "(", ")", "+", "\";ods select Variables;run;\"", "if", "self", ".", "sas", ".", "nosub", ":", "print", "(", "code", ")", "return", "if", "self", ".", "results", ".", "upper", "(", ")", "==", "'PANDAS'", ":", "code", "=", "\"proc contents data=%s.%s %s ;ods output Variables=work._variables ;run;\"", "%", "(", "self", ".", "libref", ",", "self", ".", "table", ",", "self", ".", "_dsopts", "(", ")", ")", "pd", "=", "self", ".", "_returnPD", "(", "code", ",", "'_variables'", ")", "pd", "[", "'Type'", "]", "=", "pd", "[", "'Type'", "]", ".", "str", ".", "rstrip", "(", ")", "return", "pd", "else", ":", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", "self", ".", "HTML", ":", "if", "not", "ll", ":", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ")", "if", "not", "self", ".", "sas", ".", "batch", ":", "self", ".", "sas", ".", "DISPLAY", "(", "self", ".", "sas", ".", "HTML", "(", "ll", "[", "'LST'", "]", ")", ")", "else", ":", "return", "ll", "else", ":", "if", "not", "ll", ":", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ",", "\"text\"", ")", "if", "not", "self", ".", "sas", ".", "batch", ":", "print", "(", "ll", "[", "'LST'", "]", ")", "else", ":", "return", "ll" ]
display metadata about the table, size, number of rows, columns and their data type
[ "display", "metadata", "about", "the", "table", "size", "number", "of", "rows", "columns", "and", "their", "data", "type" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L487-L518
228,109
sassoftware/saspy
saspy/sasdata.py
SASdata.sort
def sort(self, by: str, out: object = '', **kwargs) -> 'SASdata': """ Sort the SAS Data Set :param by: REQUIRED variable to sort by (BY <DESCENDING> variable-1 <<DESCENDING> variable-2 ...>;) :param out: OPTIONAL takes either a string 'libref.table' or 'table' which will go to WORK or USER if assigned or a sas data object'' will sort in place if allowed :param kwargs: :return: SASdata object if out= not specified, or a new SASdata object for out= when specified :Example: #. wkcars.sort('type') #. wkcars2 = sas.sasdata('cars2') #. wkcars.sort('cylinders', wkcars2) #. cars2=cars.sort('DESCENDING origin', out='foobar') #. cars.sort('type').head() #. stat_results = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type')) #. stat_results2 = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type','work.cars')) """ outstr = '' options = '' if out: if isinstance(out, str): fn = out.partition('.') if fn[1] == '.': libref = fn[0] table = fn[2] outstr = "out=%s.%s" % (libref, table) else: libref = '' table = fn[0] outstr = "out=" + table else: libref = out.libref table = out.table outstr = "out=%s.%s" % (out.libref, out.table) if 'options' in kwargs: options = kwargs['options'] code = "proc sort data=%s.%s%s %s %s ;\n" % (self.libref, self.table, self._dsopts(), outstr, options) code += "by %s;" % by code += "run\n;" runcode = True if self.sas.nosub: print(code) runcode = False ll = self._is_valid() if ll: runcode = False if runcode: ll = self.sas.submit(code, "text") elog = [] for line in ll['LOG'].splitlines(): if line.startswith('ERROR'): elog.append(line) if len(elog): raise RuntimeError("\n".join(elog)) if out: if not isinstance(out, str): return out else: return self.sas.sasdata(table, libref, self.results) else: return self
python
def sort(self, by: str, out: object = '', **kwargs) -> 'SASdata': """ Sort the SAS Data Set :param by: REQUIRED variable to sort by (BY <DESCENDING> variable-1 <<DESCENDING> variable-2 ...>;) :param out: OPTIONAL takes either a string 'libref.table' or 'table' which will go to WORK or USER if assigned or a sas data object'' will sort in place if allowed :param kwargs: :return: SASdata object if out= not specified, or a new SASdata object for out= when specified :Example: #. wkcars.sort('type') #. wkcars2 = sas.sasdata('cars2') #. wkcars.sort('cylinders', wkcars2) #. cars2=cars.sort('DESCENDING origin', out='foobar') #. cars.sort('type').head() #. stat_results = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type')) #. stat_results2 = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type','work.cars')) """ outstr = '' options = '' if out: if isinstance(out, str): fn = out.partition('.') if fn[1] == '.': libref = fn[0] table = fn[2] outstr = "out=%s.%s" % (libref, table) else: libref = '' table = fn[0] outstr = "out=" + table else: libref = out.libref table = out.table outstr = "out=%s.%s" % (out.libref, out.table) if 'options' in kwargs: options = kwargs['options'] code = "proc sort data=%s.%s%s %s %s ;\n" % (self.libref, self.table, self._dsopts(), outstr, options) code += "by %s;" % by code += "run\n;" runcode = True if self.sas.nosub: print(code) runcode = False ll = self._is_valid() if ll: runcode = False if runcode: ll = self.sas.submit(code, "text") elog = [] for line in ll['LOG'].splitlines(): if line.startswith('ERROR'): elog.append(line) if len(elog): raise RuntimeError("\n".join(elog)) if out: if not isinstance(out, str): return out else: return self.sas.sasdata(table, libref, self.results) else: return self
[ "def", "sort", "(", "self", ",", "by", ":", "str", ",", "out", ":", "object", "=", "''", ",", "*", "*", "kwargs", ")", "->", "'SASdata'", ":", "outstr", "=", "''", "options", "=", "''", "if", "out", ":", "if", "isinstance", "(", "out", ",", "str", ")", ":", "fn", "=", "out", ".", "partition", "(", "'.'", ")", "if", "fn", "[", "1", "]", "==", "'.'", ":", "libref", "=", "fn", "[", "0", "]", "table", "=", "fn", "[", "2", "]", "outstr", "=", "\"out=%s.%s\"", "%", "(", "libref", ",", "table", ")", "else", ":", "libref", "=", "''", "table", "=", "fn", "[", "0", "]", "outstr", "=", "\"out=\"", "+", "table", "else", ":", "libref", "=", "out", ".", "libref", "table", "=", "out", ".", "table", "outstr", "=", "\"out=%s.%s\"", "%", "(", "out", ".", "libref", ",", "out", ".", "table", ")", "if", "'options'", "in", "kwargs", ":", "options", "=", "kwargs", "[", "'options'", "]", "code", "=", "\"proc sort data=%s.%s%s %s %s ;\\n\"", "%", "(", "self", ".", "libref", ",", "self", ".", "table", ",", "self", ".", "_dsopts", "(", ")", ",", "outstr", ",", "options", ")", "code", "+=", "\"by %s;\"", "%", "by", "code", "+=", "\"run\\n;\"", "runcode", "=", "True", "if", "self", ".", "sas", ".", "nosub", ":", "print", "(", "code", ")", "runcode", "=", "False", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", "ll", ":", "runcode", "=", "False", "if", "runcode", ":", "ll", "=", "self", ".", "sas", ".", "submit", "(", "code", ",", "\"text\"", ")", "elog", "=", "[", "]", "for", "line", "in", "ll", "[", "'LOG'", "]", ".", "splitlines", "(", ")", ":", "if", "line", ".", "startswith", "(", "'ERROR'", ")", ":", "elog", ".", "append", "(", "line", ")", "if", "len", "(", "elog", ")", ":", "raise", "RuntimeError", "(", "\"\\n\"", ".", "join", "(", "elog", ")", ")", "if", "out", ":", "if", "not", "isinstance", "(", "out", ",", "str", ")", ":", "return", "out", "else", ":", "return", "self", ".", "sas", ".", "sasdata", "(", "table", ",", "libref", ",", "self", ".", "results", ")", "else", ":", "return", "self" ]
Sort the SAS Data Set :param by: REQUIRED variable to sort by (BY <DESCENDING> variable-1 <<DESCENDING> variable-2 ...>;) :param out: OPTIONAL takes either a string 'libref.table' or 'table' which will go to WORK or USER if assigned or a sas data object'' will sort in place if allowed :param kwargs: :return: SASdata object if out= not specified, or a new SASdata object for out= when specified :Example: #. wkcars.sort('type') #. wkcars2 = sas.sasdata('cars2') #. wkcars.sort('cylinders', wkcars2) #. cars2=cars.sort('DESCENDING origin', out='foobar') #. cars.sort('type').head() #. stat_results = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type')) #. stat_results2 = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type','work.cars'))
[ "Sort", "the", "SAS", "Data", "Set" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L733-L799
228,110
sassoftware/saspy
saspy/sasdata.py
SASdata.to_csv
def to_csv(self, file: str, opts: dict = None) -> str: """ This method will export a SAS Data Set to a file in CSV format. :param file: the OS filesystem path of the file to be created (exported from this SAS Data Set) :return: """ opts = opts if opts is not None else {} ll = self._is_valid() if ll: if not self.sas.batch: print(ll['LOG']) else: return ll else: return self.sas.write_csv(file, self.table, self.libref, self.dsopts, opts)
python
def to_csv(self, file: str, opts: dict = None) -> str: """ This method will export a SAS Data Set to a file in CSV format. :param file: the OS filesystem path of the file to be created (exported from this SAS Data Set) :return: """ opts = opts if opts is not None else {} ll = self._is_valid() if ll: if not self.sas.batch: print(ll['LOG']) else: return ll else: return self.sas.write_csv(file, self.table, self.libref, self.dsopts, opts)
[ "def", "to_csv", "(", "self", ",", "file", ":", "str", ",", "opts", ":", "dict", "=", "None", ")", "->", "str", ":", "opts", "=", "opts", "if", "opts", "is", "not", "None", "else", "{", "}", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", "ll", ":", "if", "not", "self", ".", "sas", ".", "batch", ":", "print", "(", "ll", "[", "'LOG'", "]", ")", "else", ":", "return", "ll", "else", ":", "return", "self", ".", "sas", ".", "write_csv", "(", "file", ",", "self", ".", "table", ",", "self", ".", "libref", ",", "self", ".", "dsopts", ",", "opts", ")" ]
This method will export a SAS Data Set to a file in CSV format. :param file: the OS filesystem path of the file to be created (exported from this SAS Data Set) :return:
[ "This", "method", "will", "export", "a", "SAS", "Data", "Set", "to", "a", "file", "in", "CSV", "format", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L912-L927
228,111
sassoftware/saspy
saspy/sasdata.py
SASdata.score
def score(self, file: str = '', code: str = '', out: 'SASdata' = None) -> 'SASdata': """ This method is meant to update a SAS Data object with a model score file. :param file: a file reference to the SAS score code :param code: a string of the valid SAS score code :param out: Where to the write the file. Defaults to update in place :return: The Scored SAS Data object. """ if out is not None: outTable = out.table outLibref = out.libref else: outTable = self.table outLibref = self.libref codestr = code code = "data %s.%s%s;" % (outLibref, outTable, self._dsopts()) code += "set %s.%s%s;" % (self.libref, self.table, self._dsopts()) if len(file)>0: code += '%%include "%s";' % file else: code += "%s;" %codestr code += "run;" if self.sas.nosub: print(code) return None ll = self._is_valid() if not ll: html = self.HTML self.HTML = 1 ll = self.sas._io.submit(code) self.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll
python
def score(self, file: str = '', code: str = '', out: 'SASdata' = None) -> 'SASdata': """ This method is meant to update a SAS Data object with a model score file. :param file: a file reference to the SAS score code :param code: a string of the valid SAS score code :param out: Where to the write the file. Defaults to update in place :return: The Scored SAS Data object. """ if out is not None: outTable = out.table outLibref = out.libref else: outTable = self.table outLibref = self.libref codestr = code code = "data %s.%s%s;" % (outLibref, outTable, self._dsopts()) code += "set %s.%s%s;" % (self.libref, self.table, self._dsopts()) if len(file)>0: code += '%%include "%s";' % file else: code += "%s;" %codestr code += "run;" if self.sas.nosub: print(code) return None ll = self._is_valid() if not ll: html = self.HTML self.HTML = 1 ll = self.sas._io.submit(code) self.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll
[ "def", "score", "(", "self", ",", "file", ":", "str", "=", "''", ",", "code", ":", "str", "=", "''", ",", "out", ":", "'SASdata'", "=", "None", ")", "->", "'SASdata'", ":", "if", "out", "is", "not", "None", ":", "outTable", "=", "out", ".", "table", "outLibref", "=", "out", ".", "libref", "else", ":", "outTable", "=", "self", ".", "table", "outLibref", "=", "self", ".", "libref", "codestr", "=", "code", "code", "=", "\"data %s.%s%s;\"", "%", "(", "outLibref", ",", "outTable", ",", "self", ".", "_dsopts", "(", ")", ")", "code", "+=", "\"set %s.%s%s;\"", "%", "(", "self", ".", "libref", ",", "self", ".", "table", ",", "self", ".", "_dsopts", "(", ")", ")", "if", "len", "(", "file", ")", ">", "0", ":", "code", "+=", "'%%include \"%s\";'", "%", "file", "else", ":", "code", "+=", "\"%s;\"", "%", "codestr", "code", "+=", "\"run;\"", "if", "self", ".", "sas", ".", "nosub", ":", "print", "(", "code", ")", "return", "None", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", "not", "ll", ":", "html", "=", "self", ".", "HTML", "self", ".", "HTML", "=", "1", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ")", "self", ".", "HTML", "=", "html", "if", "not", "self", ".", "sas", ".", "batch", ":", "self", ".", "sas", ".", "DISPLAY", "(", "self", ".", "sas", ".", "HTML", "(", "ll", "[", "'LST'", "]", ")", ")", "else", ":", "return", "ll" ]
This method is meant to update a SAS Data object with a model score file. :param file: a file reference to the SAS score code :param code: a string of the valid SAS score code :param out: Where to the write the file. Defaults to update in place :return: The Scored SAS Data object.
[ "This", "method", "is", "meant", "to", "update", "a", "SAS", "Data", "object", "with", "a", "model", "score", "file", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L929-L966
228,112
sassoftware/saspy
saspy/sasdata.py
SASdata.to_df
def to_df(self, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame': """ Export this SAS Data Set to a Pandas Data Frame :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: :return: Pandas data frame """ ll = self._is_valid() if ll: print(ll['LOG']) return None else: return self.sas.sasdata2dataframe(self.table, self.libref, self.dsopts, method, **kwargs)
python
def to_df(self, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame': """ Export this SAS Data Set to a Pandas Data Frame :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: :return: Pandas data frame """ ll = self._is_valid() if ll: print(ll['LOG']) return None else: return self.sas.sasdata2dataframe(self.table, self.libref, self.dsopts, method, **kwargs)
[ "def", "to_df", "(", "self", ",", "method", ":", "str", "=", "'MEMORY'", ",", "*", "*", "kwargs", ")", "->", "'pd.DataFrame'", ":", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", "ll", ":", "print", "(", "ll", "[", "'LOG'", "]", ")", "return", "None", "else", ":", "return", "self", ".", "sas", ".", "sasdata2dataframe", "(", "self", ".", "table", ",", "self", ".", "libref", ",", "self", ".", "dsopts", ",", "method", ",", "*", "*", "kwargs", ")" ]
Export this SAS Data Set to a Pandas Data Frame :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: :return: Pandas data frame
[ "Export", "this", "SAS", "Data", "Set", "to", "a", "Pandas", "Data", "Frame" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L978-L991
228,113
sassoftware/saspy
saspy/sasdata.py
SASdata.to_df_CSV
def to_df_CSV(self, tempfile: str=None, tempkeep: bool=False, **kwargs) -> 'pd.DataFrame': """ Export this SAS Data Set to a Pandas Data Frame via CSV file :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it :param kwargs: :return: Pandas data frame :rtype: 'pd.DataFrame' """ return self.to_df(method='CSV', tempfile=tempfile, tempkeep=tempkeep, **kwargs)
python
def to_df_CSV(self, tempfile: str=None, tempkeep: bool=False, **kwargs) -> 'pd.DataFrame': """ Export this SAS Data Set to a Pandas Data Frame via CSV file :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it :param kwargs: :return: Pandas data frame :rtype: 'pd.DataFrame' """ return self.to_df(method='CSV', tempfile=tempfile, tempkeep=tempkeep, **kwargs)
[ "def", "to_df_CSV", "(", "self", ",", "tempfile", ":", "str", "=", "None", ",", "tempkeep", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", "->", "'pd.DataFrame'", ":", "return", "self", ".", "to_df", "(", "method", "=", "'CSV'", ",", "tempfile", "=", "tempfile", ",", "tempkeep", "=", "tempkeep", ",", "*", "*", "kwargs", ")" ]
Export this SAS Data Set to a Pandas Data Frame via CSV file :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it :param kwargs: :return: Pandas data frame :rtype: 'pd.DataFrame'
[ "Export", "this", "SAS", "Data", "Set", "to", "a", "Pandas", "Data", "Frame", "via", "CSV", "file" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L993-L1003
228,114
sassoftware/saspy
saspy/sasdata.py
SASdata.series
def series(self, x: str, y: list, title: str = '') -> object: """ This method plots a series of x,y coordinates. You can provide a list of y columns for multiple line plots. :param x: the x axis variable; generally a time or continuous variable. :param y: the y axis variable(s), you can specify a single column or a list of columns :param title: an optional Title for the chart :return: graph object """ code = "proc sgplot data=" + self.libref + '.' + self.table + self._dsopts() + ";\n" if len(title) > 0: code += '\ttitle "' + title + '";\n' if isinstance(y, list): num = len(y) else: num = 1 y = [y] for i in range(num): code += "\tseries x=" + x + " y=" + str(y[i]) + ";\n" code += 'run;\n' + 'title;' if self.sas.nosub: print(code) return ll = self._is_valid() if not ll: html = self.HTML self.HTML = 1 ll = self.sas._io.submit(code) self.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll
python
def series(self, x: str, y: list, title: str = '') -> object: """ This method plots a series of x,y coordinates. You can provide a list of y columns for multiple line plots. :param x: the x axis variable; generally a time or continuous variable. :param y: the y axis variable(s), you can specify a single column or a list of columns :param title: an optional Title for the chart :return: graph object """ code = "proc sgplot data=" + self.libref + '.' + self.table + self._dsopts() + ";\n" if len(title) > 0: code += '\ttitle "' + title + '";\n' if isinstance(y, list): num = len(y) else: num = 1 y = [y] for i in range(num): code += "\tseries x=" + x + " y=" + str(y[i]) + ";\n" code += 'run;\n' + 'title;' if self.sas.nosub: print(code) return ll = self._is_valid() if not ll: html = self.HTML self.HTML = 1 ll = self.sas._io.submit(code) self.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll
[ "def", "series", "(", "self", ",", "x", ":", "str", ",", "y", ":", "list", ",", "title", ":", "str", "=", "''", ")", "->", "object", ":", "code", "=", "\"proc sgplot data=\"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "_dsopts", "(", ")", "+", "\";\\n\"", "if", "len", "(", "title", ")", ">", "0", ":", "code", "+=", "'\\ttitle \"'", "+", "title", "+", "'\";\\n'", "if", "isinstance", "(", "y", ",", "list", ")", ":", "num", "=", "len", "(", "y", ")", "else", ":", "num", "=", "1", "y", "=", "[", "y", "]", "for", "i", "in", "range", "(", "num", ")", ":", "code", "+=", "\"\\tseries x=\"", "+", "x", "+", "\" y=\"", "+", "str", "(", "y", "[", "i", "]", ")", "+", "\";\\n\"", "code", "+=", "'run;\\n'", "+", "'title;'", "if", "self", ".", "sas", ".", "nosub", ":", "print", "(", "code", ")", "return", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", "not", "ll", ":", "html", "=", "self", ".", "HTML", "self", ".", "HTML", "=", "1", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ")", "self", ".", "HTML", "=", "html", "if", "not", "self", ".", "sas", ".", "batch", ":", "self", ".", "sas", ".", "DISPLAY", "(", "self", ".", "sas", ".", "HTML", "(", "ll", "[", "'LST'", "]", ")", ")", "else", ":", "return", "ll" ]
This method plots a series of x,y coordinates. You can provide a list of y columns for multiple line plots. :param x: the x axis variable; generally a time or continuous variable. :param y: the y axis variable(s), you can specify a single column or a list of columns :param title: an optional Title for the chart :return: graph object
[ "This", "method", "plots", "a", "series", "of", "x", "y", "coordinates", ".", "You", "can", "provide", "a", "list", "of", "y", "columns", "for", "multiple", "line", "plots", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L1201-L1239
228,115
sassoftware/saspy
saspy/sasproccommons.py
SASProcCommons._charlist
def _charlist(self, data) -> list: """ Private method to return the variables in a SAS Data set that are of type char :param data: SAS Data object to process :return: list of character variables :rtype: list """ # Get list of character variables to add to nominal list char_string = """ data _null_; file LOG; d = open('{0}.{1}'); nvars = attrn(d, 'NVARS'); put 'VARLIST='; do i = 1 to nvars; vart = vartype(d, i); var = varname(d, i); if vart eq 'C' then put var; end; put 'VARLISTend='; run; """ # ignore teach_me_SAS mode to run contents nosub = self.sas.nosub self.sas.nosub = False ll = self.sas.submit(char_string.format(data.libref, data.table + data._dsopts())) self.sas.nosub = nosub l2 = ll['LOG'].partition("VARLIST=\n") l2 = l2[2].rpartition("VARLISTend=\n") charlist1 = l2[0].split("\n") del charlist1[len(charlist1) - 1] charlist1 = [x.casefold() for x in charlist1] return charlist1
python
def _charlist(self, data) -> list: """ Private method to return the variables in a SAS Data set that are of type char :param data: SAS Data object to process :return: list of character variables :rtype: list """ # Get list of character variables to add to nominal list char_string = """ data _null_; file LOG; d = open('{0}.{1}'); nvars = attrn(d, 'NVARS'); put 'VARLIST='; do i = 1 to nvars; vart = vartype(d, i); var = varname(d, i); if vart eq 'C' then put var; end; put 'VARLISTend='; run; """ # ignore teach_me_SAS mode to run contents nosub = self.sas.nosub self.sas.nosub = False ll = self.sas.submit(char_string.format(data.libref, data.table + data._dsopts())) self.sas.nosub = nosub l2 = ll['LOG'].partition("VARLIST=\n") l2 = l2[2].rpartition("VARLISTend=\n") charlist1 = l2[0].split("\n") del charlist1[len(charlist1) - 1] charlist1 = [x.casefold() for x in charlist1] return charlist1
[ "def", "_charlist", "(", "self", ",", "data", ")", "->", "list", ":", "# Get list of character variables to add to nominal list", "char_string", "=", "\"\"\"\n data _null_; file LOG;\n d = open('{0}.{1}');\n nvars = attrn(d, 'NVARS');\n put 'VARLIST=';\n do i = 1 to nvars;\n vart = vartype(d, i);\n var = varname(d, i);\n if vart eq 'C' then\n put var; end;\n put 'VARLISTend=';\n run;\n \"\"\"", "# ignore teach_me_SAS mode to run contents", "nosub", "=", "self", ".", "sas", ".", "nosub", "self", ".", "sas", ".", "nosub", "=", "False", "ll", "=", "self", ".", "sas", ".", "submit", "(", "char_string", ".", "format", "(", "data", ".", "libref", ",", "data", ".", "table", "+", "data", ".", "_dsopts", "(", ")", ")", ")", "self", ".", "sas", ".", "nosub", "=", "nosub", "l2", "=", "ll", "[", "'LOG'", "]", ".", "partition", "(", "\"VARLIST=\\n\"", ")", "l2", "=", "l2", "[", "2", "]", ".", "rpartition", "(", "\"VARLISTend=\\n\"", ")", "charlist1", "=", "l2", "[", "0", "]", ".", "split", "(", "\"\\n\"", ")", "del", "charlist1", "[", "len", "(", "charlist1", ")", "-", "1", "]", "charlist1", "=", "[", "x", ".", "casefold", "(", ")", "for", "x", "in", "charlist1", "]", "return", "charlist1" ]
Private method to return the variables in a SAS Data set that are of type char :param data: SAS Data object to process :return: list of character variables :rtype: list
[ "Private", "method", "to", "return", "the", "variables", "in", "a", "SAS", "Data", "set", "that", "are", "of", "type", "char" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasproccommons.py#L328-L360
228,116
sassoftware/saspy
saspy/sasioiom.py
SASsessionIOM.disconnect
def disconnect(self): """ This method disconnects an IOM session to allow for reconnecting when switching networks """ if not self.sascfg.reconnect: return "Disconnecting and then reconnecting to this workspaceserver has been disabled. Did not disconnect" pgm = b'\n'+b'tom says EOL=DISCONNECT \n' self.stdin[0].send(pgm) while True: try: log = self.stderr[0].recv(4096).decode(errors='replace') except (BlockingIOError): log = b'' if len(log) > 0: if log.count("DISCONNECT") >= 1: break return log.rstrip("DISCONNECT")
python
def disconnect(self): """ This method disconnects an IOM session to allow for reconnecting when switching networks """ if not self.sascfg.reconnect: return "Disconnecting and then reconnecting to this workspaceserver has been disabled. Did not disconnect" pgm = b'\n'+b'tom says EOL=DISCONNECT \n' self.stdin[0].send(pgm) while True: try: log = self.stderr[0].recv(4096).decode(errors='replace') except (BlockingIOError): log = b'' if len(log) > 0: if log.count("DISCONNECT") >= 1: break return log.rstrip("DISCONNECT")
[ "def", "disconnect", "(", "self", ")", ":", "if", "not", "self", ".", "sascfg", ".", "reconnect", ":", "return", "\"Disconnecting and then reconnecting to this workspaceserver has been disabled. Did not disconnect\"", "pgm", "=", "b'\\n'", "+", "b'tom says EOL=DISCONNECT \\n'", "self", ".", "stdin", "[", "0", "]", ".", "send", "(", "pgm", ")", "while", "True", ":", "try", ":", "log", "=", "self", ".", "stderr", "[", "0", "]", ".", "recv", "(", "4096", ")", ".", "decode", "(", "errors", "=", "'replace'", ")", "except", "(", "BlockingIOError", ")", ":", "log", "=", "b''", "if", "len", "(", "log", ")", ">", "0", ":", "if", "log", ".", "count", "(", "\"DISCONNECT\"", ")", ">=", "1", ":", "break", "return", "log", ".", "rstrip", "(", "\"DISCONNECT\"", ")" ]
This method disconnects an IOM session to allow for reconnecting when switching networks
[ "This", "method", "disconnects", "an", "IOM", "session", "to", "allow", "for", "reconnecting", "when", "switching", "networks" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasioiom.py#L1034-L1055
228,117
sassoftware/saspy
saspy/sasdecorator.py
procDecorator.proc_decorator
def proc_decorator(req_set): """ Decorator that provides the wrapped function with an attribute 'actual_kwargs' containing just those keyword arguments actually passed in to the function. """ def decorator(func): @wraps(func) def inner(self, *args, **kwargs): proc = func.__name__.lower() inner.proc_decorator = kwargs self.logger.debug("processing proc:{}".format(func.__name__)) self.logger.debug(req_set) self.logger.debug("kwargs type: " + str(type(kwargs))) if proc in ['hplogistic', 'hpreg']: kwargs['ODSGraphics'] = kwargs.get('ODSGraphics', False) if proc == 'hpcluster': proc = 'hpclus' legal_set = set(kwargs.keys()) self.logger.debug(legal_set) return SASProcCommons._run_proc(self, proc, req_set, legal_set, **kwargs) return inner return decorator
python
def proc_decorator(req_set): """ Decorator that provides the wrapped function with an attribute 'actual_kwargs' containing just those keyword arguments actually passed in to the function. """ def decorator(func): @wraps(func) def inner(self, *args, **kwargs): proc = func.__name__.lower() inner.proc_decorator = kwargs self.logger.debug("processing proc:{}".format(func.__name__)) self.logger.debug(req_set) self.logger.debug("kwargs type: " + str(type(kwargs))) if proc in ['hplogistic', 'hpreg']: kwargs['ODSGraphics'] = kwargs.get('ODSGraphics', False) if proc == 'hpcluster': proc = 'hpclus' legal_set = set(kwargs.keys()) self.logger.debug(legal_set) return SASProcCommons._run_proc(self, proc, req_set, legal_set, **kwargs) return inner return decorator
[ "def", "proc_decorator", "(", "req_set", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "proc", "=", "func", ".", "__name__", ".", "lower", "(", ")", "inner", ".", "proc_decorator", "=", "kwargs", "self", ".", "logger", ".", "debug", "(", "\"processing proc:{}\"", ".", "format", "(", "func", ".", "__name__", ")", ")", "self", ".", "logger", ".", "debug", "(", "req_set", ")", "self", ".", "logger", ".", "debug", "(", "\"kwargs type: \"", "+", "str", "(", "type", "(", "kwargs", ")", ")", ")", "if", "proc", "in", "[", "'hplogistic'", ",", "'hpreg'", "]", ":", "kwargs", "[", "'ODSGraphics'", "]", "=", "kwargs", ".", "get", "(", "'ODSGraphics'", ",", "False", ")", "if", "proc", "==", "'hpcluster'", ":", "proc", "=", "'hpclus'", "legal_set", "=", "set", "(", "kwargs", ".", "keys", "(", ")", ")", "self", ".", "logger", ".", "debug", "(", "legal_set", ")", "return", "SASProcCommons", ".", "_run_proc", "(", "self", ",", "proc", ",", "req_set", ",", "legal_set", ",", "*", "*", "kwargs", ")", "return", "inner", "return", "decorator" ]
Decorator that provides the wrapped function with an attribute 'actual_kwargs' containing just those keyword arguments actually passed in to the function.
[ "Decorator", "that", "provides", "the", "wrapped", "function", "with", "an", "attribute", "actual_kwargs", "containing", "just", "those", "keyword", "arguments", "actually", "passed", "in", "to", "the", "function", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdecorator.py#L15-L37
228,118
sassoftware/saspy
saspy/sasresults.py
SASresults.ALL
def ALL(self): """ This method shows all the results attributes for a given object """ if not self.sas.batch: for i in self._names: if i.upper()!='LOG': x = self.__getattr__(i) if isinstance(x, pd.DataFrame): if self.sas.sascfg.display.lower() == 'zeppelin': print("%text "+i+"\n"+str(x)+"\n") else: self.sas.DISPLAY(x) else: ret = [] for i in self._names: if i.upper()!='LOG': ret.append(self.__getattr__(i)) return ret
python
def ALL(self): """ This method shows all the results attributes for a given object """ if not self.sas.batch: for i in self._names: if i.upper()!='LOG': x = self.__getattr__(i) if isinstance(x, pd.DataFrame): if self.sas.sascfg.display.lower() == 'zeppelin': print("%text "+i+"\n"+str(x)+"\n") else: self.sas.DISPLAY(x) else: ret = [] for i in self._names: if i.upper()!='LOG': ret.append(self.__getattr__(i)) return ret
[ "def", "ALL", "(", "self", ")", ":", "if", "not", "self", ".", "sas", ".", "batch", ":", "for", "i", "in", "self", ".", "_names", ":", "if", "i", ".", "upper", "(", ")", "!=", "'LOG'", ":", "x", "=", "self", ".", "__getattr__", "(", "i", ")", "if", "isinstance", "(", "x", ",", "pd", ".", "DataFrame", ")", ":", "if", "self", ".", "sas", ".", "sascfg", ".", "display", ".", "lower", "(", ")", "==", "'zeppelin'", ":", "print", "(", "\"%text \"", "+", "i", "+", "\"\\n\"", "+", "str", "(", "x", ")", "+", "\"\\n\"", ")", "else", ":", "self", ".", "sas", ".", "DISPLAY", "(", "x", ")", "else", ":", "ret", "=", "[", "]", "for", "i", "in", "self", ".", "_names", ":", "if", "i", ".", "upper", "(", ")", "!=", "'LOG'", ":", "ret", ".", "append", "(", "self", ".", "__getattr__", "(", "i", ")", ")", "return", "ret" ]
This method shows all the results attributes for a given object
[ "This", "method", "shows", "all", "the", "results", "attributes", "for", "a", "given", "object" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasresults.py#L108-L126
228,119
sassoftware/saspy
saspy/sastabulate.py
Tabulate.execute_table
def execute_table(self, _output_type, **kwargs: dict) -> 'SASresults': """ executes a PROC TABULATE statement You must specify an output type to use this method, of 'HTML', 'text', or 'Pandas'. There are three convenience functions for generating specific output; see: .text_table() .table() .to_dataframe() :param _output_type: style of output to use :param left: the query for the left side of the table :param top: the query for the top of the table :return: """ left = kwargs.pop('left', None) top = kwargs.pop('top', None) sets = dict(classes=set(), vars=set()) left._gather(sets) if top: top._gather(sets) table = top \ and '%s, %s' % (str(left), str(top)) \ or str(left) proc_kwargs = dict( cls=' '.join(sets['classes']), var=' '.join(sets['vars']), table=table ) # permit additional valid options if passed; for now, just 'where' proc_kwargs.update(kwargs) # we can't easily use the SASProcCommons approach for submiting, # since this is merely an output / display proc for us; # but we can at least use it to check valid options in the canonical saspy way required_options = {'cls', 'var', 'table'} allowed_options = {'cls', 'var', 'table', 'where'} verifiedKwargs = sp.sasproccommons.SASProcCommons._stmt_check(self, required_options, allowed_options, proc_kwargs) if (_output_type == 'Pandas'): # for pandas, use the out= directive code = "proc tabulate data=%s.%s %s out=temptab;\n" % ( self.data.libref, self.data.table, self.data._dsopts()) else: code = "proc tabulate data=%s.%s %s;\n" % (self.data.libref, self.data.table, self.data._dsopts()) # build the code for arg, value in verifiedKwargs.items(): code += " %s %s;\n" % (arg == 'cls' and 'class' or arg, value) code += "run;" # teach_me_SAS if self.sas.nosub: print(code) return # submit the code ll = self.data._is_valid() if _output_type == 'HTML': if not ll: html = self.data.HTML self.data.HTML = 1 ll = self.sas._io.submit(code) self.data.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) check, errorMsg = self.data._checkLogForError(ll['LOG']) if not check: raise ValueError("Internal code execution failed: " + errorMsg) else: return ll elif _output_type == 'text': if not ll: html = self.data.HTML self.data.HTML = 1 ll = self.sas._io.submit(code, 'text') self.data.HTML = html print(ll['LST']) return elif _output_type == 'Pandas': return self.to_nested_dataframe(code)
python
def execute_table(self, _output_type, **kwargs: dict) -> 'SASresults': """ executes a PROC TABULATE statement You must specify an output type to use this method, of 'HTML', 'text', or 'Pandas'. There are three convenience functions for generating specific output; see: .text_table() .table() .to_dataframe() :param _output_type: style of output to use :param left: the query for the left side of the table :param top: the query for the top of the table :return: """ left = kwargs.pop('left', None) top = kwargs.pop('top', None) sets = dict(classes=set(), vars=set()) left._gather(sets) if top: top._gather(sets) table = top \ and '%s, %s' % (str(left), str(top)) \ or str(left) proc_kwargs = dict( cls=' '.join(sets['classes']), var=' '.join(sets['vars']), table=table ) # permit additional valid options if passed; for now, just 'where' proc_kwargs.update(kwargs) # we can't easily use the SASProcCommons approach for submiting, # since this is merely an output / display proc for us; # but we can at least use it to check valid options in the canonical saspy way required_options = {'cls', 'var', 'table'} allowed_options = {'cls', 'var', 'table', 'where'} verifiedKwargs = sp.sasproccommons.SASProcCommons._stmt_check(self, required_options, allowed_options, proc_kwargs) if (_output_type == 'Pandas'): # for pandas, use the out= directive code = "proc tabulate data=%s.%s %s out=temptab;\n" % ( self.data.libref, self.data.table, self.data._dsopts()) else: code = "proc tabulate data=%s.%s %s;\n" % (self.data.libref, self.data.table, self.data._dsopts()) # build the code for arg, value in verifiedKwargs.items(): code += " %s %s;\n" % (arg == 'cls' and 'class' or arg, value) code += "run;" # teach_me_SAS if self.sas.nosub: print(code) return # submit the code ll = self.data._is_valid() if _output_type == 'HTML': if not ll: html = self.data.HTML self.data.HTML = 1 ll = self.sas._io.submit(code) self.data.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) check, errorMsg = self.data._checkLogForError(ll['LOG']) if not check: raise ValueError("Internal code execution failed: " + errorMsg) else: return ll elif _output_type == 'text': if not ll: html = self.data.HTML self.data.HTML = 1 ll = self.sas._io.submit(code, 'text') self.data.HTML = html print(ll['LST']) return elif _output_type == 'Pandas': return self.to_nested_dataframe(code)
[ "def", "execute_table", "(", "self", ",", "_output_type", ",", "*", "*", "kwargs", ":", "dict", ")", "->", "'SASresults'", ":", "left", "=", "kwargs", ".", "pop", "(", "'left'", ",", "None", ")", "top", "=", "kwargs", ".", "pop", "(", "'top'", ",", "None", ")", "sets", "=", "dict", "(", "classes", "=", "set", "(", ")", ",", "vars", "=", "set", "(", ")", ")", "left", ".", "_gather", "(", "sets", ")", "if", "top", ":", "top", ".", "_gather", "(", "sets", ")", "table", "=", "top", "and", "'%s, %s'", "%", "(", "str", "(", "left", ")", ",", "str", "(", "top", ")", ")", "or", "str", "(", "left", ")", "proc_kwargs", "=", "dict", "(", "cls", "=", "' '", ".", "join", "(", "sets", "[", "'classes'", "]", ")", ",", "var", "=", "' '", ".", "join", "(", "sets", "[", "'vars'", "]", ")", ",", "table", "=", "table", ")", "# permit additional valid options if passed; for now, just 'where'", "proc_kwargs", ".", "update", "(", "kwargs", ")", "# we can't easily use the SASProcCommons approach for submiting, ", "# since this is merely an output / display proc for us;", "# but we can at least use it to check valid options in the canonical saspy way", "required_options", "=", "{", "'cls'", ",", "'var'", ",", "'table'", "}", "allowed_options", "=", "{", "'cls'", ",", "'var'", ",", "'table'", ",", "'where'", "}", "verifiedKwargs", "=", "sp", ".", "sasproccommons", ".", "SASProcCommons", ".", "_stmt_check", "(", "self", ",", "required_options", ",", "allowed_options", ",", "proc_kwargs", ")", "if", "(", "_output_type", "==", "'Pandas'", ")", ":", "# for pandas, use the out= directive", "code", "=", "\"proc tabulate data=%s.%s %s out=temptab;\\n\"", "%", "(", "self", ".", "data", ".", "libref", ",", "self", ".", "data", ".", "table", ",", "self", ".", "data", ".", "_dsopts", "(", ")", ")", "else", ":", "code", "=", "\"proc tabulate data=%s.%s %s;\\n\"", "%", "(", "self", ".", "data", ".", "libref", ",", "self", ".", "data", ".", "table", ",", "self", ".", "data", ".", "_dsopts", "(", ")", ")", "# build the code", "for", "arg", ",", "value", "in", "verifiedKwargs", ".", "items", "(", ")", ":", "code", "+=", "\" %s %s;\\n\"", "%", "(", "arg", "==", "'cls'", "and", "'class'", "or", "arg", ",", "value", ")", "code", "+=", "\"run;\"", "# teach_me_SAS", "if", "self", ".", "sas", ".", "nosub", ":", "print", "(", "code", ")", "return", "# submit the code", "ll", "=", "self", ".", "data", ".", "_is_valid", "(", ")", "if", "_output_type", "==", "'HTML'", ":", "if", "not", "ll", ":", "html", "=", "self", ".", "data", ".", "HTML", "self", ".", "data", ".", "HTML", "=", "1", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ")", "self", ".", "data", ".", "HTML", "=", "html", "if", "not", "self", ".", "sas", ".", "batch", ":", "self", ".", "sas", ".", "DISPLAY", "(", "self", ".", "sas", ".", "HTML", "(", "ll", "[", "'LST'", "]", ")", ")", "check", ",", "errorMsg", "=", "self", ".", "data", ".", "_checkLogForError", "(", "ll", "[", "'LOG'", "]", ")", "if", "not", "check", ":", "raise", "ValueError", "(", "\"Internal code execution failed: \"", "+", "errorMsg", ")", "else", ":", "return", "ll", "elif", "_output_type", "==", "'text'", ":", "if", "not", "ll", ":", "html", "=", "self", ".", "data", ".", "HTML", "self", ".", "data", ".", "HTML", "=", "1", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ",", "'text'", ")", "self", ".", "data", ".", "HTML", "=", "html", "print", "(", "ll", "[", "'LST'", "]", ")", "return", "elif", "_output_type", "==", "'Pandas'", ":", "return", "self", ".", "to_nested_dataframe", "(", "code", ")" ]
executes a PROC TABULATE statement You must specify an output type to use this method, of 'HTML', 'text', or 'Pandas'. There are three convenience functions for generating specific output; see: .text_table() .table() .to_dataframe() :param _output_type: style of output to use :param left: the query for the left side of the table :param top: the query for the top of the table :return:
[ "executes", "a", "PROC", "TABULATE", "statement" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sastabulate.py#L243-L330
228,120
JelteF/PyLaTeX
pylatex/base_classes/containers.py
Container.dumps_content
def dumps_content(self, **kwargs): r"""Represent the container as a string in LaTeX syntax. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the container """ return dumps_list(self, escape=self.escape, token=self.content_separator, **kwargs)
python
def dumps_content(self, **kwargs): r"""Represent the container as a string in LaTeX syntax. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the container """ return dumps_list(self, escape=self.escape, token=self.content_separator, **kwargs)
[ "def", "dumps_content", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "dumps_list", "(", "self", ",", "escape", "=", "self", ".", "escape", ",", "token", "=", "self", ".", "content_separator", ",", "*", "*", "kwargs", ")" ]
r"""Represent the container as a string in LaTeX syntax. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the container
[ "r", "Represent", "the", "container", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L53-L69
228,121
JelteF/PyLaTeX
pylatex/base_classes/containers.py
Container._propagate_packages
def _propagate_packages(self): """Make sure packages get propagated.""" for item in self.data: if isinstance(item, LatexObject): if isinstance(item, Container): item._propagate_packages() for p in item.packages: self.packages.add(p)
python
def _propagate_packages(self): """Make sure packages get propagated.""" for item in self.data: if isinstance(item, LatexObject): if isinstance(item, Container): item._propagate_packages() for p in item.packages: self.packages.add(p)
[ "def", "_propagate_packages", "(", "self", ")", ":", "for", "item", "in", "self", ".", "data", ":", "if", "isinstance", "(", "item", ",", "LatexObject", ")", ":", "if", "isinstance", "(", "item", ",", "Container", ")", ":", "item", ".", "_propagate_packages", "(", ")", "for", "p", "in", "item", ".", "packages", ":", "self", ".", "packages", ".", "add", "(", "p", ")" ]
Make sure packages get propagated.
[ "Make", "sure", "packages", "get", "propagated", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L71-L79
228,122
JelteF/PyLaTeX
pylatex/base_classes/containers.py
Container.create
def create(self, child): """Add a LaTeX object to current container, context-manager style. Args ---- child: `~.Container` An object to be added to the current container """ prev_data = self.data self.data = child.data # This way append works appends to the child yield child # allows with ... as to be used as well self.data = prev_data self.append(child)
python
def create(self, child): """Add a LaTeX object to current container, context-manager style. Args ---- child: `~.Container` An object to be added to the current container """ prev_data = self.data self.data = child.data # This way append works appends to the child yield child # allows with ... as to be used as well self.data = prev_data self.append(child)
[ "def", "create", "(", "self", ",", "child", ")", ":", "prev_data", "=", "self", ".", "data", "self", ".", "data", "=", "child", ".", "data", "# This way append works appends to the child", "yield", "child", "# allows with ... as to be used as well", "self", ".", "data", "=", "prev_data", "self", ".", "append", "(", "child", ")" ]
Add a LaTeX object to current container, context-manager style. Args ---- child: `~.Container` An object to be added to the current container
[ "Add", "a", "LaTeX", "object", "to", "current", "container", "context", "-", "manager", "style", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L95-L110
228,123
JelteF/PyLaTeX
pylatex/base_classes/containers.py
Environment.dumps
def dumps(self): """Represent the environment as a string in LaTeX syntax. Returns ------- str A LaTeX string representing the environment. """ content = self.dumps_content() if not content.strip() and self.omit_if_empty: return '' string = '' # Something other than None needs to be used as extra arguments, that # way the options end up behind the latex_name argument. if self.arguments is None: extra_arguments = Arguments() else: extra_arguments = self.arguments begin = Command('begin', self.start_arguments, self.options, extra_arguments=extra_arguments) begin.arguments._positional_args.insert(0, self.latex_name) string += begin.dumps() + self.content_separator string += content + self.content_separator string += Command('end', self.latex_name).dumps() return string
python
def dumps(self): """Represent the environment as a string in LaTeX syntax. Returns ------- str A LaTeX string representing the environment. """ content = self.dumps_content() if not content.strip() and self.omit_if_empty: return '' string = '' # Something other than None needs to be used as extra arguments, that # way the options end up behind the latex_name argument. if self.arguments is None: extra_arguments = Arguments() else: extra_arguments = self.arguments begin = Command('begin', self.start_arguments, self.options, extra_arguments=extra_arguments) begin.arguments._positional_args.insert(0, self.latex_name) string += begin.dumps() + self.content_separator string += content + self.content_separator string += Command('end', self.latex_name).dumps() return string
[ "def", "dumps", "(", "self", ")", ":", "content", "=", "self", ".", "dumps_content", "(", ")", "if", "not", "content", ".", "strip", "(", ")", "and", "self", ".", "omit_if_empty", ":", "return", "''", "string", "=", "''", "# Something other than None needs to be used as extra arguments, that", "# way the options end up behind the latex_name argument.", "if", "self", ".", "arguments", "is", "None", ":", "extra_arguments", "=", "Arguments", "(", ")", "else", ":", "extra_arguments", "=", "self", ".", "arguments", "begin", "=", "Command", "(", "'begin'", ",", "self", ".", "start_arguments", ",", "self", ".", "options", ",", "extra_arguments", "=", "extra_arguments", ")", "begin", ".", "arguments", ".", "_positional_args", ".", "insert", "(", "0", ",", "self", ".", "latex_name", ")", "string", "+=", "begin", ".", "dumps", "(", ")", "+", "self", ".", "content_separator", "string", "+=", "content", "+", "self", ".", "content_separator", "string", "+=", "Command", "(", "'end'", ",", "self", ".", "latex_name", ")", ".", "dumps", "(", ")", "return", "string" ]
Represent the environment as a string in LaTeX syntax. Returns ------- str A LaTeX string representing the environment.
[ "Represent", "the", "environment", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L157-L188
228,124
JelteF/PyLaTeX
pylatex/base_classes/containers.py
ContainerCommand.dumps
def dumps(self): r"""Convert the container to a string in latex syntax.""" content = self.dumps_content() if not content.strip() and self.omit_if_empty: return '' string = '' start = Command(self.latex_name, arguments=self.arguments, options=self.options) string += start.dumps() + '{ \n' if content != '': string += content + '\n}' else: string += '}' return string
python
def dumps(self): r"""Convert the container to a string in latex syntax.""" content = self.dumps_content() if not content.strip() and self.omit_if_empty: return '' string = '' start = Command(self.latex_name, arguments=self.arguments, options=self.options) string += start.dumps() + '{ \n' if content != '': string += content + '\n}' else: string += '}' return string
[ "def", "dumps", "(", "self", ")", ":", "content", "=", "self", ".", "dumps_content", "(", ")", "if", "not", "content", ".", "strip", "(", ")", "and", "self", ".", "omit_if_empty", ":", "return", "''", "string", "=", "''", "start", "=", "Command", "(", "self", ".", "latex_name", ",", "arguments", "=", "self", ".", "arguments", ",", "options", "=", "self", ".", "options", ")", "string", "+=", "start", ".", "dumps", "(", ")", "+", "'{ \\n'", "if", "content", "!=", "''", ":", "string", "+=", "content", "+", "'\\n}'", "else", ":", "string", "+=", "'}'", "return", "string" ]
r"""Convert the container to a string in latex syntax.
[ "r", "Convert", "the", "container", "to", "a", "string", "in", "latex", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L223-L243
228,125
JelteF/PyLaTeX
pylatex/section.py
Section.dumps
def dumps(self): """Represent the section as a string in LaTeX syntax. Returns ------- str """ if not self.numbering: num = '*' else: num = '' string = Command(self.latex_name + num, self.title).dumps() if self.label is not None: string += '%\n' + self.label.dumps() string += '%\n' + self.dumps_content() return string
python
def dumps(self): """Represent the section as a string in LaTeX syntax. Returns ------- str """ if not self.numbering: num = '*' else: num = '' string = Command(self.latex_name + num, self.title).dumps() if self.label is not None: string += '%\n' + self.label.dumps() string += '%\n' + self.dumps_content() return string
[ "def", "dumps", "(", "self", ")", ":", "if", "not", "self", ".", "numbering", ":", "num", "=", "'*'", "else", ":", "num", "=", "''", "string", "=", "Command", "(", "self", ".", "latex_name", "+", "num", ",", "self", ".", "title", ")", ".", "dumps", "(", ")", "if", "self", ".", "label", "is", "not", "None", ":", "string", "+=", "'%\\n'", "+", "self", ".", "label", ".", "dumps", "(", ")", "string", "+=", "'%\\n'", "+", "self", ".", "dumps_content", "(", ")", "return", "string" ]
Represent the section as a string in LaTeX syntax. Returns ------- str
[ "Represent", "the", "section", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/section.py#L60-L79
228,126
JelteF/PyLaTeX
pylatex/table.py
_get_table_width
def _get_table_width(table_spec): """Calculate the width of a table based on its spec. Args ---- table_spec: str The LaTeX column specification for a table. Returns ------- int The width of a table which uses the specification supplied. """ # Remove things like {\bfseries} cleaner_spec = re.sub(r'{[^}]*}', '', table_spec) # Remove X[] in tabu environments so they dont interfere with column count cleaner_spec = re.sub(r'X\[(.*?(.))\]', r'\2', cleaner_spec) spec_counter = Counter(cleaner_spec) return sum(spec_counter[l] for l in COLUMN_LETTERS)
python
def _get_table_width(table_spec): """Calculate the width of a table based on its spec. Args ---- table_spec: str The LaTeX column specification for a table. Returns ------- int The width of a table which uses the specification supplied. """ # Remove things like {\bfseries} cleaner_spec = re.sub(r'{[^}]*}', '', table_spec) # Remove X[] in tabu environments so they dont interfere with column count cleaner_spec = re.sub(r'X\[(.*?(.))\]', r'\2', cleaner_spec) spec_counter = Counter(cleaner_spec) return sum(spec_counter[l] for l in COLUMN_LETTERS)
[ "def", "_get_table_width", "(", "table_spec", ")", ":", "# Remove things like {\\bfseries}", "cleaner_spec", "=", "re", ".", "sub", "(", "r'{[^}]*}'", ",", "''", ",", "table_spec", ")", "# Remove X[] in tabu environments so they dont interfere with column count", "cleaner_spec", "=", "re", ".", "sub", "(", "r'X\\[(.*?(.))\\]'", ",", "r'\\2'", ",", "cleaner_spec", ")", "spec_counter", "=", "Counter", "(", "cleaner_spec", ")", "return", "sum", "(", "spec_counter", "[", "l", "]", "for", "l", "in", "COLUMN_LETTERS", ")" ]
Calculate the width of a table based on its spec. Args ---- table_spec: str The LaTeX column specification for a table. Returns ------- int The width of a table which uses the specification supplied.
[ "Calculate", "the", "width", "of", "a", "table", "based", "on", "its", "spec", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L24-L46
228,127
JelteF/PyLaTeX
pylatex/table.py
Tabular.dumps
def dumps(self): r"""Turn the Latex Object into a string in Latex format.""" string = "" if self.row_height is not None: row_height = Command('renewcommand', arguments=[ NoEscape(r'\arraystretch'), self.row_height]) string += row_height.dumps() + '%\n' if self.col_space is not None: col_space = Command('setlength', arguments=[ NoEscape(r'\tabcolsep'), self.col_space]) string += col_space.dumps() + '%\n' return string + super().dumps()
python
def dumps(self): r"""Turn the Latex Object into a string in Latex format.""" string = "" if self.row_height is not None: row_height = Command('renewcommand', arguments=[ NoEscape(r'\arraystretch'), self.row_height]) string += row_height.dumps() + '%\n' if self.col_space is not None: col_space = Command('setlength', arguments=[ NoEscape(r'\tabcolsep'), self.col_space]) string += col_space.dumps() + '%\n' return string + super().dumps()
[ "def", "dumps", "(", "self", ")", ":", "string", "=", "\"\"", "if", "self", ".", "row_height", "is", "not", "None", ":", "row_height", "=", "Command", "(", "'renewcommand'", ",", "arguments", "=", "[", "NoEscape", "(", "r'\\arraystretch'", ")", ",", "self", ".", "row_height", "]", ")", "string", "+=", "row_height", ".", "dumps", "(", ")", "+", "'%\\n'", "if", "self", ".", "col_space", "is", "not", "None", ":", "col_space", "=", "Command", "(", "'setlength'", ",", "arguments", "=", "[", "NoEscape", "(", "r'\\tabcolsep'", ")", ",", "self", ".", "col_space", "]", ")", "string", "+=", "col_space", ".", "dumps", "(", ")", "+", "'%\\n'", "return", "string", "+", "super", "(", ")", ".", "dumps", "(", ")" ]
r"""Turn the Latex Object into a string in Latex format.
[ "r", "Turn", "the", "Latex", "Object", "into", "a", "string", "in", "Latex", "format", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L112-L129
228,128
JelteF/PyLaTeX
pylatex/table.py
Tabular.dumps_content
def dumps_content(self, **kwargs): r"""Represent the content of the tabular in LaTeX syntax. This adds the top and bottomrule when using a booktabs style tabular. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the """ content = '' if self.booktabs: content += '\\toprule%\n' content += super().dumps_content(**kwargs) if self.booktabs: content += '\\bottomrule%\n' return NoEscape(content)
python
def dumps_content(self, **kwargs): r"""Represent the content of the tabular in LaTeX syntax. This adds the top and bottomrule when using a booktabs style tabular. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the """ content = '' if self.booktabs: content += '\\toprule%\n' content += super().dumps_content(**kwargs) if self.booktabs: content += '\\bottomrule%\n' return NoEscape(content)
[ "def", "dumps_content", "(", "self", ",", "*", "*", "kwargs", ")", ":", "content", "=", "''", "if", "self", ".", "booktabs", ":", "content", "+=", "'\\\\toprule%\\n'", "content", "+=", "super", "(", ")", ".", "dumps_content", "(", "*", "*", "kwargs", ")", "if", "self", ".", "booktabs", ":", "content", "+=", "'\\\\bottomrule%\\n'", "return", "NoEscape", "(", "content", ")" ]
r"""Represent the content of the tabular in LaTeX syntax. This adds the top and bottomrule when using a booktabs style tabular. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the
[ "r", "Represent", "the", "content", "of", "the", "tabular", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L131-L156
228,129
JelteF/PyLaTeX
pylatex/table.py
Tabular.add_hline
def add_hline(self, start=None, end=None, *, color=None, cmidruleoption=None): r"""Add a horizontal line to the table. Args ---- start: int At what cell the line should begin end: int At what cell the line should end color: str The hline color. cmidruleoption: str The option to be used for the booktabs cmidrule, i.e. the ``x`` in ``\cmidrule(x){1-3}``. """ if self.booktabs: hline = 'midrule' cline = 'cmidrule' if cmidruleoption is not None: cline += '(' + cmidruleoption + ')' else: hline = 'hline' cline = 'cline' if color is not None: if not self.color: self.packages.append(Package('xcolor', options='table')) self.color = True color_command = Command(command="arrayrulecolor", arguments=color) self.append(color_command) if start is None and end is None: self.append(Command(hline)) else: if start is None: start = 1 elif end is None: end = self.width self.append(Command(cline, dumps_list([start, NoEscape('-'), end])))
python
def add_hline(self, start=None, end=None, *, color=None, cmidruleoption=None): r"""Add a horizontal line to the table. Args ---- start: int At what cell the line should begin end: int At what cell the line should end color: str The hline color. cmidruleoption: str The option to be used for the booktabs cmidrule, i.e. the ``x`` in ``\cmidrule(x){1-3}``. """ if self.booktabs: hline = 'midrule' cline = 'cmidrule' if cmidruleoption is not None: cline += '(' + cmidruleoption + ')' else: hline = 'hline' cline = 'cline' if color is not None: if not self.color: self.packages.append(Package('xcolor', options='table')) self.color = True color_command = Command(command="arrayrulecolor", arguments=color) self.append(color_command) if start is None and end is None: self.append(Command(hline)) else: if start is None: start = 1 elif end is None: end = self.width self.append(Command(cline, dumps_list([start, NoEscape('-'), end])))
[ "def", "add_hline", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "*", ",", "color", "=", "None", ",", "cmidruleoption", "=", "None", ")", ":", "if", "self", ".", "booktabs", ":", "hline", "=", "'midrule'", "cline", "=", "'cmidrule'", "if", "cmidruleoption", "is", "not", "None", ":", "cline", "+=", "'('", "+", "cmidruleoption", "+", "')'", "else", ":", "hline", "=", "'hline'", "cline", "=", "'cline'", "if", "color", "is", "not", "None", ":", "if", "not", "self", ".", "color", ":", "self", ".", "packages", ".", "append", "(", "Package", "(", "'xcolor'", ",", "options", "=", "'table'", ")", ")", "self", ".", "color", "=", "True", "color_command", "=", "Command", "(", "command", "=", "\"arrayrulecolor\"", ",", "arguments", "=", "color", ")", "self", ".", "append", "(", "color_command", ")", "if", "start", "is", "None", "and", "end", "is", "None", ":", "self", ".", "append", "(", "Command", "(", "hline", ")", ")", "else", ":", "if", "start", "is", "None", ":", "start", "=", "1", "elif", "end", "is", "None", ":", "end", "=", "self", ".", "width", "self", ".", "append", "(", "Command", "(", "cline", ",", "dumps_list", "(", "[", "start", ",", "NoEscape", "(", "'-'", ")", ",", "end", "]", ")", ")", ")" ]
r"""Add a horizontal line to the table. Args ---- start: int At what cell the line should begin end: int At what cell the line should end color: str The hline color. cmidruleoption: str The option to be used for the booktabs cmidrule, i.e. the ``x`` in ``\cmidrule(x){1-3}``.
[ "r", "Add", "a", "horizontal", "line", "to", "the", "table", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L158-L199
228,130
JelteF/PyLaTeX
pylatex/table.py
Tabular.add_row
def add_row(self, *cells, color=None, escape=None, mapper=None, strict=True): """Add a row of cells to the table. Args ---- cells: iterable, such as a `list` or `tuple` There's two ways to use this method. The first method is to pass the content of each cell as a separate argument. The second method is to pass a single argument that is an iterable that contains each contents. color: str The name of the color used to highlight the row mapper: callable or `list` A function or a list of functions that should be called on all entries of the list after converting them to a string, for instance bold strict: bool Check for correct count of cells in row or not. """ if len(cells) == 1 and _is_iterable(cells): cells = cells[0] if escape is None: escape = self.escape # Propagate packages used in cells for c in cells: if isinstance(c, LatexObject): for p in c.packages: self.packages.add(p) # Count cell contents cell_count = 0 for c in cells: if isinstance(c, MultiColumn): cell_count += c.size else: cell_count += 1 if strict and cell_count != self.width: msg = "Number of cells added to table ({}) " \ "did not match table width ({})".format(cell_count, self.width) raise TableRowSizeError(msg) if color is not None: if not self.color: self.packages.append(Package("xcolor", options='table')) self.color = True color_command = Command(command="rowcolor", arguments=color) self.append(color_command) self.append(dumps_list(cells, escape=escape, token='&', mapper=mapper) + NoEscape(r'\\'))
python
def add_row(self, *cells, color=None, escape=None, mapper=None, strict=True): """Add a row of cells to the table. Args ---- cells: iterable, such as a `list` or `tuple` There's two ways to use this method. The first method is to pass the content of each cell as a separate argument. The second method is to pass a single argument that is an iterable that contains each contents. color: str The name of the color used to highlight the row mapper: callable or `list` A function or a list of functions that should be called on all entries of the list after converting them to a string, for instance bold strict: bool Check for correct count of cells in row or not. """ if len(cells) == 1 and _is_iterable(cells): cells = cells[0] if escape is None: escape = self.escape # Propagate packages used in cells for c in cells: if isinstance(c, LatexObject): for p in c.packages: self.packages.add(p) # Count cell contents cell_count = 0 for c in cells: if isinstance(c, MultiColumn): cell_count += c.size else: cell_count += 1 if strict and cell_count != self.width: msg = "Number of cells added to table ({}) " \ "did not match table width ({})".format(cell_count, self.width) raise TableRowSizeError(msg) if color is not None: if not self.color: self.packages.append(Package("xcolor", options='table')) self.color = True color_command = Command(command="rowcolor", arguments=color) self.append(color_command) self.append(dumps_list(cells, escape=escape, token='&', mapper=mapper) + NoEscape(r'\\'))
[ "def", "add_row", "(", "self", ",", "*", "cells", ",", "color", "=", "None", ",", "escape", "=", "None", ",", "mapper", "=", "None", ",", "strict", "=", "True", ")", ":", "if", "len", "(", "cells", ")", "==", "1", "and", "_is_iterable", "(", "cells", ")", ":", "cells", "=", "cells", "[", "0", "]", "if", "escape", "is", "None", ":", "escape", "=", "self", ".", "escape", "# Propagate packages used in cells", "for", "c", "in", "cells", ":", "if", "isinstance", "(", "c", ",", "LatexObject", ")", ":", "for", "p", "in", "c", ".", "packages", ":", "self", ".", "packages", ".", "add", "(", "p", ")", "# Count cell contents", "cell_count", "=", "0", "for", "c", "in", "cells", ":", "if", "isinstance", "(", "c", ",", "MultiColumn", ")", ":", "cell_count", "+=", "c", ".", "size", "else", ":", "cell_count", "+=", "1", "if", "strict", "and", "cell_count", "!=", "self", ".", "width", ":", "msg", "=", "\"Number of cells added to table ({}) \"", "\"did not match table width ({})\"", ".", "format", "(", "cell_count", ",", "self", ".", "width", ")", "raise", "TableRowSizeError", "(", "msg", ")", "if", "color", "is", "not", "None", ":", "if", "not", "self", ".", "color", ":", "self", ".", "packages", ".", "append", "(", "Package", "(", "\"xcolor\"", ",", "options", "=", "'table'", ")", ")", "self", ".", "color", "=", "True", "color_command", "=", "Command", "(", "command", "=", "\"rowcolor\"", ",", "arguments", "=", "color", ")", "self", ".", "append", "(", "color_command", ")", "self", ".", "append", "(", "dumps_list", "(", "cells", ",", "escape", "=", "escape", ",", "token", "=", "'&'", ",", "mapper", "=", "mapper", ")", "+", "NoEscape", "(", "r'\\\\'", ")", ")" ]
Add a row of cells to the table. Args ---- cells: iterable, such as a `list` or `tuple` There's two ways to use this method. The first method is to pass the content of each cell as a separate argument. The second method is to pass a single argument that is an iterable that contains each contents. color: str The name of the color used to highlight the row mapper: callable or `list` A function or a list of functions that should be called on all entries of the list after converting them to a string, for instance bold strict: bool Check for correct count of cells in row or not.
[ "Add", "a", "row", "of", "cells", "to", "the", "table", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L206-L261
228,131
JelteF/PyLaTeX
pylatex/table.py
MultiColumn.dumps
def dumps(self): """Represent the multicolumn as a string in LaTeX syntax. Returns ------- str """ args = [self.size, self.align, self.dumps_content()] string = Command(self.latex_name, args).dumps() return string
python
def dumps(self): """Represent the multicolumn as a string in LaTeX syntax. Returns ------- str """ args = [self.size, self.align, self.dumps_content()] string = Command(self.latex_name, args).dumps() return string
[ "def", "dumps", "(", "self", ")", ":", "args", "=", "[", "self", ".", "size", ",", "self", ".", "align", ",", "self", ".", "dumps_content", "(", ")", "]", "string", "=", "Command", "(", "self", ".", "latex_name", ",", "args", ")", ".", "dumps", "(", ")", "return", "string" ]
Represent the multicolumn as a string in LaTeX syntax. Returns ------- str
[ "Represent", "the", "multicolumn", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L311-L322
228,132
JelteF/PyLaTeX
pylatex/table.py
Tabu.dumps
def dumps(self): """Turn the tabu object into a string in Latex format.""" _s = super().dumps() # Tabu tables support a unusual syntax: # \begin{tabu} spread 0pt {<col format...>} # # Since this syntax isn't common, it doesn't make # sense to support it in the baseclass (e.g., Environment) # rather, here we fix the LaTeX string post-hoc if self._preamble: if _s.startswith(r"\begin{longtabu}"): _s = _s[:16] + self._preamble + _s[16:] elif _s.startswith(r"\begin{tabu}"): _s = _s[:12] + self._preamble + _s[12:] else: raise TableError("Can't apply preamble to Tabu table " "(unexpected initial command sequence)") return _s
python
def dumps(self): """Turn the tabu object into a string in Latex format.""" _s = super().dumps() # Tabu tables support a unusual syntax: # \begin{tabu} spread 0pt {<col format...>} # # Since this syntax isn't common, it doesn't make # sense to support it in the baseclass (e.g., Environment) # rather, here we fix the LaTeX string post-hoc if self._preamble: if _s.startswith(r"\begin{longtabu}"): _s = _s[:16] + self._preamble + _s[16:] elif _s.startswith(r"\begin{tabu}"): _s = _s[:12] + self._preamble + _s[12:] else: raise TableError("Can't apply preamble to Tabu table " "(unexpected initial command sequence)") return _s
[ "def", "dumps", "(", "self", ")", ":", "_s", "=", "super", "(", ")", ".", "dumps", "(", ")", "# Tabu tables support a unusual syntax:", "# \\begin{tabu} spread 0pt {<col format...>}", "#", "# Since this syntax isn't common, it doesn't make", "# sense to support it in the baseclass (e.g., Environment)", "# rather, here we fix the LaTeX string post-hoc", "if", "self", ".", "_preamble", ":", "if", "_s", ".", "startswith", "(", "r\"\\begin{longtabu}\"", ")", ":", "_s", "=", "_s", "[", ":", "16", "]", "+", "self", ".", "_preamble", "+", "_s", "[", "16", ":", "]", "elif", "_s", ".", "startswith", "(", "r\"\\begin{tabu}\"", ")", ":", "_s", "=", "_s", "[", ":", "12", "]", "+", "self", ".", "_preamble", "+", "_s", "[", "12", ":", "]", "else", ":", "raise", "TableError", "(", "\"Can't apply preamble to Tabu table \"", "\"(unexpected initial command sequence)\"", ")", "return", "_s" ]
Turn the tabu object into a string in Latex format.
[ "Turn", "the", "tabu", "object", "into", "a", "string", "in", "Latex", "format", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L428-L448
228,133
JelteF/PyLaTeX
pylatex/table.py
LongTable.end_table_header
def end_table_header(self): r"""End the table header which will appear on every page.""" if self.header: msg = "Table already has a header" raise TableError(msg) self.header = True self.append(Command(r'endhead'))
python
def end_table_header(self): r"""End the table header which will appear on every page.""" if self.header: msg = "Table already has a header" raise TableError(msg) self.header = True self.append(Command(r'endhead'))
[ "def", "end_table_header", "(", "self", ")", ":", "if", "self", ".", "header", ":", "msg", "=", "\"Table already has a header\"", "raise", "TableError", "(", "msg", ")", "self", ".", "header", "=", "True", "self", ".", "append", "(", "Command", "(", "r'endhead'", ")", ")" ]
r"""End the table header which will appear on every page.
[ "r", "End", "the", "table", "header", "which", "will", "appear", "on", "every", "page", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L460-L469
228,134
JelteF/PyLaTeX
pylatex/table.py
LongTable.end_table_footer
def end_table_footer(self): r"""End the table foot which will appear on every page.""" if self.foot: msg = "Table already has a foot" raise TableError(msg) self.foot = True self.append(Command('endfoot'))
python
def end_table_footer(self): r"""End the table foot which will appear on every page.""" if self.foot: msg = "Table already has a foot" raise TableError(msg) self.foot = True self.append(Command('endfoot'))
[ "def", "end_table_footer", "(", "self", ")", ":", "if", "self", ".", "foot", ":", "msg", "=", "\"Table already has a foot\"", "raise", "TableError", "(", "msg", ")", "self", ".", "foot", "=", "True", "self", ".", "append", "(", "Command", "(", "'endfoot'", ")", ")" ]
r"""End the table foot which will appear on every page.
[ "r", "End", "the", "table", "foot", "which", "will", "appear", "on", "every", "page", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L471-L480
228,135
JelteF/PyLaTeX
pylatex/table.py
LongTable.end_table_last_footer
def end_table_last_footer(self): r"""End the table foot which will appear on the last page.""" if self.lastFoot: msg = "Table already has a last foot" raise TableError(msg) self.lastFoot = True self.append(Command('endlastfoot'))
python
def end_table_last_footer(self): r"""End the table foot which will appear on the last page.""" if self.lastFoot: msg = "Table already has a last foot" raise TableError(msg) self.lastFoot = True self.append(Command('endlastfoot'))
[ "def", "end_table_last_footer", "(", "self", ")", ":", "if", "self", ".", "lastFoot", ":", "msg", "=", "\"Table already has a last foot\"", "raise", "TableError", "(", "msg", ")", "self", ".", "lastFoot", "=", "True", "self", ".", "append", "(", "Command", "(", "'endlastfoot'", ")", ")" ]
r"""End the table foot which will appear on the last page.
[ "r", "End", "the", "table", "foot", "which", "will", "appear", "on", "the", "last", "page", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L482-L491
228,136
JelteF/PyLaTeX
pylatex/utils.py
escape_latex
def escape_latex(s): r"""Escape characters that are special in latex. Args ---- s : `str`, `NoEscape` or anything that can be converted to string The string to be escaped. If this is not a string, it will be converted to a string using `str`. If it is a `NoEscape` string, it will pass through unchanged. Returns ------- NoEscape The string, with special characters in latex escaped. Examples -------- >>> escape_latex("Total cost: $30,000") 'Total cost: \$30,000' >>> escape_latex("Issue #5 occurs in 30% of all cases") 'Issue \#5 occurs in 30\% of all cases' >>> print(escape_latex("Total cost: $30,000")) References ---------- * http://tex.stackexchange.com/a/34586/43228 * http://stackoverflow.com/a/16264094/2570866 """ if isinstance(s, NoEscape): return s return NoEscape(''.join(_latex_special_chars.get(c, c) for c in str(s)))
python
def escape_latex(s): r"""Escape characters that are special in latex. Args ---- s : `str`, `NoEscape` or anything that can be converted to string The string to be escaped. If this is not a string, it will be converted to a string using `str`. If it is a `NoEscape` string, it will pass through unchanged. Returns ------- NoEscape The string, with special characters in latex escaped. Examples -------- >>> escape_latex("Total cost: $30,000") 'Total cost: \$30,000' >>> escape_latex("Issue #5 occurs in 30% of all cases") 'Issue \#5 occurs in 30\% of all cases' >>> print(escape_latex("Total cost: $30,000")) References ---------- * http://tex.stackexchange.com/a/34586/43228 * http://stackoverflow.com/a/16264094/2570866 """ if isinstance(s, NoEscape): return s return NoEscape(''.join(_latex_special_chars.get(c, c) for c in str(s)))
[ "def", "escape_latex", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "NoEscape", ")", ":", "return", "s", "return", "NoEscape", "(", "''", ".", "join", "(", "_latex_special_chars", ".", "get", "(", "c", ",", "c", ")", "for", "c", "in", "str", "(", "s", ")", ")", ")" ]
r"""Escape characters that are special in latex. Args ---- s : `str`, `NoEscape` or anything that can be converted to string The string to be escaped. If this is not a string, it will be converted to a string using `str`. If it is a `NoEscape` string, it will pass through unchanged. Returns ------- NoEscape The string, with special characters in latex escaped. Examples -------- >>> escape_latex("Total cost: $30,000") 'Total cost: \$30,000' >>> escape_latex("Issue #5 occurs in 30% of all cases") 'Issue \#5 occurs in 30\% of all cases' >>> print(escape_latex("Total cost: $30,000")) References ---------- * http://tex.stackexchange.com/a/34586/43228 * http://stackoverflow.com/a/16264094/2570866
[ "r", "Escape", "characters", "that", "are", "special", "in", "latex", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L68-L100
228,137
JelteF/PyLaTeX
pylatex/utils.py
fix_filename
def fix_filename(path): r"""Fix filenames for use in LaTeX. Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg' Args ---- filename : str The filen name to be changed. Returns ------- str The new filename. Examples -------- >>> fix_filename("foo.bar.pdf") '{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.pdf") '/etc/local/{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.baz/document.pdf") '/etc/local/foo.bar.baz/document.pdf' >>> fix_filename("/etc/local/foo.bar.baz/foo~1/document.pdf") '\detokenize{/etc/local/foo.bar.baz/foo~1/document.pdf}' """ path_parts = path.split('/' if os.name == 'posix' else '\\') dir_parts = path_parts[:-1] filename = path_parts[-1] file_parts = filename.split('.') if len(file_parts) > 2: filename = '{' + '.'.join(file_parts[0:-1]) + '}.' + file_parts[-1] dir_parts.append(filename) fixed_path = '/'.join(dir_parts) if '~' in fixed_path: fixed_path = r'\detokenize{' + fixed_path + '}' return fixed_path
python
def fix_filename(path): r"""Fix filenames for use in LaTeX. Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg' Args ---- filename : str The filen name to be changed. Returns ------- str The new filename. Examples -------- >>> fix_filename("foo.bar.pdf") '{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.pdf") '/etc/local/{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.baz/document.pdf") '/etc/local/foo.bar.baz/document.pdf' >>> fix_filename("/etc/local/foo.bar.baz/foo~1/document.pdf") '\detokenize{/etc/local/foo.bar.baz/foo~1/document.pdf}' """ path_parts = path.split('/' if os.name == 'posix' else '\\') dir_parts = path_parts[:-1] filename = path_parts[-1] file_parts = filename.split('.') if len(file_parts) > 2: filename = '{' + '.'.join(file_parts[0:-1]) + '}.' + file_parts[-1] dir_parts.append(filename) fixed_path = '/'.join(dir_parts) if '~' in fixed_path: fixed_path = r'\detokenize{' + fixed_path + '}' return fixed_path
[ "def", "fix_filename", "(", "path", ")", ":", "path_parts", "=", "path", ".", "split", "(", "'/'", "if", "os", ".", "name", "==", "'posix'", "else", "'\\\\'", ")", "dir_parts", "=", "path_parts", "[", ":", "-", "1", "]", "filename", "=", "path_parts", "[", "-", "1", "]", "file_parts", "=", "filename", ".", "split", "(", "'.'", ")", "if", "len", "(", "file_parts", ")", ">", "2", ":", "filename", "=", "'{'", "+", "'.'", ".", "join", "(", "file_parts", "[", "0", ":", "-", "1", "]", ")", "+", "'}.'", "+", "file_parts", "[", "-", "1", "]", "dir_parts", ".", "append", "(", "filename", ")", "fixed_path", "=", "'/'", ".", "join", "(", "dir_parts", ")", "if", "'~'", "in", "fixed_path", ":", "fixed_path", "=", "r'\\detokenize{'", "+", "fixed_path", "+", "'}'", "return", "fixed_path" ]
r"""Fix filenames for use in LaTeX. Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg' Args ---- filename : str The filen name to be changed. Returns ------- str The new filename. Examples -------- >>> fix_filename("foo.bar.pdf") '{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.pdf") '/etc/local/{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.baz/document.pdf") '/etc/local/foo.bar.baz/document.pdf' >>> fix_filename("/etc/local/foo.bar.baz/foo~1/document.pdf") '\detokenize{/etc/local/foo.bar.baz/foo~1/document.pdf}'
[ "r", "Fix", "filenames", "for", "use", "in", "LaTeX", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L103-L146
228,138
JelteF/PyLaTeX
pylatex/utils.py
dumps_list
def dumps_list(l, *, escape=True, token='%\n', mapper=None, as_content=True): r"""Try to generate a LaTeX string of a list that can contain anything. Args ---- l : list A list of objects to be converted into a single string. escape : bool Whether to escape special LaTeX characters in converted text. token : str The token (default is a newline) to separate objects in the list. mapper: callable or `list` A function, class or a list of functions/classes that should be called on all entries of the list after converting them to a string, for instance `~.bold` or `~.MediumText`. as_content: bool Indicates whether the items in the list should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape A single LaTeX string. Examples -------- >>> dumps_list([r"\textbf{Test}", r"\nth{4}"]) '\\textbf{Test}%\n\\nth{4}' >>> print(dumps_list([r"\textbf{Test}", r"\nth{4}"])) \textbf{Test} \nth{4} >>> print(pylatex.utils.dumps_list(["There are", 4, "lights!"])) There are 4 lights! >>> print(dumps_list(["$100%", "True"], escape=True)) \$100\% True """ strings = (_latex_item_to_string(i, escape=escape, as_content=as_content) for i in l) if mapper is not None: if not isinstance(mapper, list): mapper = [mapper] for m in mapper: strings = [m(s) for s in strings] strings = [_latex_item_to_string(s) for s in strings] return NoEscape(token.join(strings))
python
def dumps_list(l, *, escape=True, token='%\n', mapper=None, as_content=True): r"""Try to generate a LaTeX string of a list that can contain anything. Args ---- l : list A list of objects to be converted into a single string. escape : bool Whether to escape special LaTeX characters in converted text. token : str The token (default is a newline) to separate objects in the list. mapper: callable or `list` A function, class or a list of functions/classes that should be called on all entries of the list after converting them to a string, for instance `~.bold` or `~.MediumText`. as_content: bool Indicates whether the items in the list should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape A single LaTeX string. Examples -------- >>> dumps_list([r"\textbf{Test}", r"\nth{4}"]) '\\textbf{Test}%\n\\nth{4}' >>> print(dumps_list([r"\textbf{Test}", r"\nth{4}"])) \textbf{Test} \nth{4} >>> print(pylatex.utils.dumps_list(["There are", 4, "lights!"])) There are 4 lights! >>> print(dumps_list(["$100%", "True"], escape=True)) \$100\% True """ strings = (_latex_item_to_string(i, escape=escape, as_content=as_content) for i in l) if mapper is not None: if not isinstance(mapper, list): mapper = [mapper] for m in mapper: strings = [m(s) for s in strings] strings = [_latex_item_to_string(s) for s in strings] return NoEscape(token.join(strings))
[ "def", "dumps_list", "(", "l", ",", "*", ",", "escape", "=", "True", ",", "token", "=", "'%\\n'", ",", "mapper", "=", "None", ",", "as_content", "=", "True", ")", ":", "strings", "=", "(", "_latex_item_to_string", "(", "i", ",", "escape", "=", "escape", ",", "as_content", "=", "as_content", ")", "for", "i", "in", "l", ")", "if", "mapper", "is", "not", "None", ":", "if", "not", "isinstance", "(", "mapper", ",", "list", ")", ":", "mapper", "=", "[", "mapper", "]", "for", "m", "in", "mapper", ":", "strings", "=", "[", "m", "(", "s", ")", "for", "s", "in", "strings", "]", "strings", "=", "[", "_latex_item_to_string", "(", "s", ")", "for", "s", "in", "strings", "]", "return", "NoEscape", "(", "token", ".", "join", "(", "strings", ")", ")" ]
r"""Try to generate a LaTeX string of a list that can contain anything. Args ---- l : list A list of objects to be converted into a single string. escape : bool Whether to escape special LaTeX characters in converted text. token : str The token (default is a newline) to separate objects in the list. mapper: callable or `list` A function, class or a list of functions/classes that should be called on all entries of the list after converting them to a string, for instance `~.bold` or `~.MediumText`. as_content: bool Indicates whether the items in the list should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape A single LaTeX string. Examples -------- >>> dumps_list([r"\textbf{Test}", r"\nth{4}"]) '\\textbf{Test}%\n\\nth{4}' >>> print(dumps_list([r"\textbf{Test}", r"\nth{4}"])) \textbf{Test} \nth{4} >>> print(pylatex.utils.dumps_list(["There are", 4, "lights!"])) There are 4 lights! >>> print(dumps_list(["$100%", "True"], escape=True)) \$100\% True
[ "r", "Try", "to", "generate", "a", "LaTeX", "string", "of", "a", "list", "that", "can", "contain", "anything", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L149-L199
228,139
JelteF/PyLaTeX
pylatex/utils.py
_latex_item_to_string
def _latex_item_to_string(item, *, escape=False, as_content=False): """Use the render method when possible, otherwise uses str. Args ---- item: object An object that needs to be converted to a string escape: bool Flag that indicates if escaping is needed as_content: bool Indicates whether the item should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape Latex """ if isinstance(item, pylatex.base_classes.LatexObject): if as_content: return item.dumps_as_content() else: return item.dumps() elif not isinstance(item, str): item = str(item) if escape: item = escape_latex(item) return item
python
def _latex_item_to_string(item, *, escape=False, as_content=False): """Use the render method when possible, otherwise uses str. Args ---- item: object An object that needs to be converted to a string escape: bool Flag that indicates if escaping is needed as_content: bool Indicates whether the item should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape Latex """ if isinstance(item, pylatex.base_classes.LatexObject): if as_content: return item.dumps_as_content() else: return item.dumps() elif not isinstance(item, str): item = str(item) if escape: item = escape_latex(item) return item
[ "def", "_latex_item_to_string", "(", "item", ",", "*", ",", "escape", "=", "False", ",", "as_content", "=", "False", ")", ":", "if", "isinstance", "(", "item", ",", "pylatex", ".", "base_classes", ".", "LatexObject", ")", ":", "if", "as_content", ":", "return", "item", ".", "dumps_as_content", "(", ")", "else", ":", "return", "item", ".", "dumps", "(", ")", "elif", "not", "isinstance", "(", "item", ",", "str", ")", ":", "item", "=", "str", "(", "item", ")", "if", "escape", ":", "item", "=", "escape_latex", "(", "item", ")", "return", "item" ]
Use the render method when possible, otherwise uses str. Args ---- item: object An object that needs to be converted to a string escape: bool Flag that indicates if escaping is needed as_content: bool Indicates whether the item should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape Latex
[ "Use", "the", "render", "method", "when", "possible", "otherwise", "uses", "str", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L202-L232
228,140
JelteF/PyLaTeX
pylatex/utils.py
bold
def bold(s, *, escape=True): r"""Make a string appear bold in LaTeX formatting. bold() wraps a given string in the LaTeX command \textbf{}. Args ---- s : str The string to be formatted. escape: bool If true the bold text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> bold("hello") '\\textbf{hello}' >>> print(bold("hello")) \textbf{hello} """ if escape: s = escape_latex(s) return NoEscape(r'\textbf{' + s + '}')
python
def bold(s, *, escape=True): r"""Make a string appear bold in LaTeX formatting. bold() wraps a given string in the LaTeX command \textbf{}. Args ---- s : str The string to be formatted. escape: bool If true the bold text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> bold("hello") '\\textbf{hello}' >>> print(bold("hello")) \textbf{hello} """ if escape: s = escape_latex(s) return NoEscape(r'\textbf{' + s + '}')
[ "def", "bold", "(", "s", ",", "*", ",", "escape", "=", "True", ")", ":", "if", "escape", ":", "s", "=", "escape_latex", "(", "s", ")", "return", "NoEscape", "(", "r'\\textbf{'", "+", "s", "+", "'}'", ")" ]
r"""Make a string appear bold in LaTeX formatting. bold() wraps a given string in the LaTeX command \textbf{}. Args ---- s : str The string to be formatted. escape: bool If true the bold text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> bold("hello") '\\textbf{hello}' >>> print(bold("hello")) \textbf{hello}
[ "r", "Make", "a", "string", "appear", "bold", "in", "LaTeX", "formatting", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L235-L263
228,141
JelteF/PyLaTeX
pylatex/utils.py
italic
def italic(s, *, escape=True): r"""Make a string appear italicized in LaTeX formatting. italic() wraps a given string in the LaTeX command \textit{}. Args ---- s : str The string to be formatted. escape: bool If true the italic text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> italic("hello") '\\textit{hello}' >>> print(italic("hello")) \textit{hello} """ if escape: s = escape_latex(s) return NoEscape(r'\textit{' + s + '}')
python
def italic(s, *, escape=True): r"""Make a string appear italicized in LaTeX formatting. italic() wraps a given string in the LaTeX command \textit{}. Args ---- s : str The string to be formatted. escape: bool If true the italic text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> italic("hello") '\\textit{hello}' >>> print(italic("hello")) \textit{hello} """ if escape: s = escape_latex(s) return NoEscape(r'\textit{' + s + '}')
[ "def", "italic", "(", "s", ",", "*", ",", "escape", "=", "True", ")", ":", "if", "escape", ":", "s", "=", "escape_latex", "(", "s", ")", "return", "NoEscape", "(", "r'\\textit{'", "+", "s", "+", "'}'", ")" ]
r"""Make a string appear italicized in LaTeX formatting. italic() wraps a given string in the LaTeX command \textit{}. Args ---- s : str The string to be formatted. escape: bool If true the italic text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> italic("hello") '\\textit{hello}' >>> print(italic("hello")) \textit{hello}
[ "r", "Make", "a", "string", "appear", "italicized", "in", "LaTeX", "formatting", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L266-L293
228,142
JelteF/PyLaTeX
docs/source/conf.py
auto_change_docstring
def auto_change_docstring(app, what, name, obj, options, lines): r"""Make some automatic changes to docstrings. Things this function does are: - Add a title to module docstrings - Merge lines that end with a '\' with the next line. """ if what == 'module' and name.startswith('pylatex'): lines.insert(0, len(name) * '=') lines.insert(0, name) hits = 0 for i, line in enumerate(lines.copy()): if line.endswith('\\'): lines[i - hits] += lines.pop(i + 1 - hits) hits += 1
python
def auto_change_docstring(app, what, name, obj, options, lines): r"""Make some automatic changes to docstrings. Things this function does are: - Add a title to module docstrings - Merge lines that end with a '\' with the next line. """ if what == 'module' and name.startswith('pylatex'): lines.insert(0, len(name) * '=') lines.insert(0, name) hits = 0 for i, line in enumerate(lines.copy()): if line.endswith('\\'): lines[i - hits] += lines.pop(i + 1 - hits) hits += 1
[ "def", "auto_change_docstring", "(", "app", ",", "what", ",", "name", ",", "obj", ",", "options", ",", "lines", ")", ":", "if", "what", "==", "'module'", "and", "name", ".", "startswith", "(", "'pylatex'", ")", ":", "lines", ".", "insert", "(", "0", ",", "len", "(", "name", ")", "*", "'='", ")", "lines", ".", "insert", "(", "0", ",", "name", ")", "hits", "=", "0", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ".", "copy", "(", ")", ")", ":", "if", "line", ".", "endswith", "(", "'\\\\'", ")", ":", "lines", "[", "i", "-", "hits", "]", "+=", "lines", ".", "pop", "(", "i", "+", "1", "-", "hits", ")", "hits", "+=", "1" ]
r"""Make some automatic changes to docstrings. Things this function does are: - Add a title to module docstrings - Merge lines that end with a '\' with the next line.
[ "r", "Make", "some", "automatic", "changes", "to", "docstrings", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/docs/source/conf.py#L100-L116
228,143
JelteF/PyLaTeX
pylatex/labelref.py
_remove_invalid_char
def _remove_invalid_char(s): """Remove invalid and dangerous characters from a string.""" s = ''.join([i if ord(i) >= 32 and ord(i) < 127 else '' for i in s]) s = s.translate(dict.fromkeys(map(ord, "_%~#\\{}\":"))) return s
python
def _remove_invalid_char(s): """Remove invalid and dangerous characters from a string.""" s = ''.join([i if ord(i) >= 32 and ord(i) < 127 else '' for i in s]) s = s.translate(dict.fromkeys(map(ord, "_%~#\\{}\":"))) return s
[ "def", "_remove_invalid_char", "(", "s", ")", ":", "s", "=", "''", ".", "join", "(", "[", "i", "if", "ord", "(", "i", ")", ">=", "32", "and", "ord", "(", "i", ")", "<", "127", "else", "''", "for", "i", "in", "s", "]", ")", "s", "=", "s", ".", "translate", "(", "dict", ".", "fromkeys", "(", "map", "(", "ord", ",", "\"_%~#\\\\{}\\\":\"", ")", ")", ")", "return", "s" ]
Remove invalid and dangerous characters from a string.
[ "Remove", "invalid", "and", "dangerous", "characters", "from", "a", "string", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/labelref.py#L9-L14
228,144
JelteF/PyLaTeX
pylatex/figure.py
Figure.add_image
def add_image(self, filename, *, width=NoEscape(r'0.8\textwidth'), placement=NoEscape(r'\centering')): """Add an image to the figure. Args ---- filename: str Filename of the image. width: str The width of the image placement: str Placement of the figure, `None` is also accepted. """ if width is not None: if self.escape: width = escape_latex(width) width = 'width=' + str(width) if placement is not None: self.append(placement) self.append(StandAloneGraphic(image_options=width, filename=fix_filename(filename)))
python
def add_image(self, filename, *, width=NoEscape(r'0.8\textwidth'), placement=NoEscape(r'\centering')): """Add an image to the figure. Args ---- filename: str Filename of the image. width: str The width of the image placement: str Placement of the figure, `None` is also accepted. """ if width is not None: if self.escape: width = escape_latex(width) width = 'width=' + str(width) if placement is not None: self.append(placement) self.append(StandAloneGraphic(image_options=width, filename=fix_filename(filename)))
[ "def", "add_image", "(", "self", ",", "filename", ",", "*", ",", "width", "=", "NoEscape", "(", "r'0.8\\textwidth'", ")", ",", "placement", "=", "NoEscape", "(", "r'\\centering'", ")", ")", ":", "if", "width", "is", "not", "None", ":", "if", "self", ".", "escape", ":", "width", "=", "escape_latex", "(", "width", ")", "width", "=", "'width='", "+", "str", "(", "width", ")", "if", "placement", "is", "not", "None", ":", "self", ".", "append", "(", "placement", ")", "self", ".", "append", "(", "StandAloneGraphic", "(", "image_options", "=", "width", ",", "filename", "=", "fix_filename", "(", "filename", ")", ")", ")" ]
Add an image to the figure. Args ---- filename: str Filename of the image. width: str The width of the image placement: str Placement of the figure, `None` is also accepted.
[ "Add", "an", "image", "to", "the", "figure", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/figure.py#L20-L45
228,145
JelteF/PyLaTeX
pylatex/figure.py
Figure._save_plot
def _save_plot(self, *args, extension='pdf', **kwargs): """Save the plot. Returns ------- str The basename with which the plot has been saved. """ import matplotlib.pyplot as plt tmp_path = make_temp_dir() filename = '{}.{}'.format(str(uuid.uuid4()), extension.strip('.')) filepath = posixpath.join(tmp_path, filename) plt.savefig(filepath, *args, **kwargs) return filepath
python
def _save_plot(self, *args, extension='pdf', **kwargs): """Save the plot. Returns ------- str The basename with which the plot has been saved. """ import matplotlib.pyplot as plt tmp_path = make_temp_dir() filename = '{}.{}'.format(str(uuid.uuid4()), extension.strip('.')) filepath = posixpath.join(tmp_path, filename) plt.savefig(filepath, *args, **kwargs) return filepath
[ "def", "_save_plot", "(", "self", ",", "*", "args", ",", "extension", "=", "'pdf'", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "tmp_path", "=", "make_temp_dir", "(", ")", "filename", "=", "'{}.{}'", ".", "format", "(", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ",", "extension", ".", "strip", "(", "'.'", ")", ")", "filepath", "=", "posixpath", ".", "join", "(", "tmp_path", ",", "filename", ")", "plt", ".", "savefig", "(", "filepath", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "filepath" ]
Save the plot. Returns ------- str The basename with which the plot has been saved.
[ "Save", "the", "plot", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/figure.py#L47-L62
228,146
JelteF/PyLaTeX
pylatex/figure.py
Figure.add_plot
def add_plot(self, *args, extension='pdf', **kwargs): """Add the current Matplotlib plot to the figure. The plot that gets added is the one that would normally be shown when using ``plt.show()``. Args ---- args: Arguments passed to plt.savefig for displaying the plot. extension : str extension of image file indicating figure file type kwargs: Keyword arguments passed to plt.savefig for displaying the plot. In case these contain ``width`` or ``placement``, they will be used for the same purpose as in the add_image command. Namely the width and placement of the generated plot in the LaTeX document. """ add_image_kwargs = {} for key in ('width', 'placement'): if key in kwargs: add_image_kwargs[key] = kwargs.pop(key) filename = self._save_plot(*args, extension=extension, **kwargs) self.add_image(filename, **add_image_kwargs)
python
def add_plot(self, *args, extension='pdf', **kwargs): """Add the current Matplotlib plot to the figure. The plot that gets added is the one that would normally be shown when using ``plt.show()``. Args ---- args: Arguments passed to plt.savefig for displaying the plot. extension : str extension of image file indicating figure file type kwargs: Keyword arguments passed to plt.savefig for displaying the plot. In case these contain ``width`` or ``placement``, they will be used for the same purpose as in the add_image command. Namely the width and placement of the generated plot in the LaTeX document. """ add_image_kwargs = {} for key in ('width', 'placement'): if key in kwargs: add_image_kwargs[key] = kwargs.pop(key) filename = self._save_plot(*args, extension=extension, **kwargs) self.add_image(filename, **add_image_kwargs)
[ "def", "add_plot", "(", "self", ",", "*", "args", ",", "extension", "=", "'pdf'", ",", "*", "*", "kwargs", ")", ":", "add_image_kwargs", "=", "{", "}", "for", "key", "in", "(", "'width'", ",", "'placement'", ")", ":", "if", "key", "in", "kwargs", ":", "add_image_kwargs", "[", "key", "]", "=", "kwargs", ".", "pop", "(", "key", ")", "filename", "=", "self", ".", "_save_plot", "(", "*", "args", ",", "extension", "=", "extension", ",", "*", "*", "kwargs", ")", "self", ".", "add_image", "(", "filename", ",", "*", "*", "add_image_kwargs", ")" ]
Add the current Matplotlib plot to the figure. The plot that gets added is the one that would normally be shown when using ``plt.show()``. Args ---- args: Arguments passed to plt.savefig for displaying the plot. extension : str extension of image file indicating figure file type kwargs: Keyword arguments passed to plt.savefig for displaying the plot. In case these contain ``width`` or ``placement``, they will be used for the same purpose as in the add_image command. Namely the width and placement of the generated plot in the LaTeX document.
[ "Add", "the", "current", "Matplotlib", "plot", "to", "the", "figure", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/figure.py#L64-L91
228,147
JelteF/PyLaTeX
pylatex/figure.py
SubFigure.add_image
def add_image(self, filename, *, width=NoEscape(r'\linewidth'), placement=None): """Add an image to the subfigure. Args ---- filename: str Filename of the image. width: str Width of the image in LaTeX terms. placement: str Placement of the figure, `None` is also accepted. """ super().add_image(filename, width=width, placement=placement)
python
def add_image(self, filename, *, width=NoEscape(r'\linewidth'), placement=None): """Add an image to the subfigure. Args ---- filename: str Filename of the image. width: str Width of the image in LaTeX terms. placement: str Placement of the figure, `None` is also accepted. """ super().add_image(filename, width=width, placement=placement)
[ "def", "add_image", "(", "self", ",", "filename", ",", "*", ",", "width", "=", "NoEscape", "(", "r'\\linewidth'", ")", ",", "placement", "=", "None", ")", ":", "super", "(", ")", ".", "add_image", "(", "filename", ",", "width", "=", "width", ",", "placement", "=", "placement", ")" ]
Add an image to the subfigure. Args ---- filename: str Filename of the image. width: str Width of the image in LaTeX terms. placement: str Placement of the figure, `None` is also accepted.
[ "Add", "an", "image", "to", "the", "subfigure", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/figure.py#L119-L133
228,148
JelteF/PyLaTeX
pylatex/base_classes/latex_object.py
LatexObject.escape
def escape(self): """Determine whether or not to escape content of this class. This defaults to `True` for most classes. """ if self._escape is not None: return self._escape if self._default_escape is not None: return self._default_escape return True
python
def escape(self): """Determine whether or not to escape content of this class. This defaults to `True` for most classes. """ if self._escape is not None: return self._escape if self._default_escape is not None: return self._default_escape return True
[ "def", "escape", "(", "self", ")", ":", "if", "self", ".", "_escape", "is", "not", "None", ":", "return", "self", ".", "_escape", "if", "self", ".", "_default_escape", "is", "not", "None", ":", "return", "self", ".", "_default_escape", "return", "True" ]
Determine whether or not to escape content of this class. This defaults to `True` for most classes.
[ "Determine", "whether", "or", "not", "to", "escape", "content", "of", "this", "class", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L58-L67
228,149
JelteF/PyLaTeX
pylatex/base_classes/latex_object.py
LatexObject._repr_values
def _repr_values(self): """Return values that are to be shown in repr string.""" def getattr_better(obj, field): try: return getattr(obj, field) except AttributeError as e: try: return getattr(obj, '_' + field) except AttributeError: raise e return (getattr_better(self, attr) for attr in self._repr_attributes)
python
def _repr_values(self): """Return values that are to be shown in repr string.""" def getattr_better(obj, field): try: return getattr(obj, field) except AttributeError as e: try: return getattr(obj, '_' + field) except AttributeError: raise e return (getattr_better(self, attr) for attr in self._repr_attributes)
[ "def", "_repr_values", "(", "self", ")", ":", "def", "getattr_better", "(", "obj", ",", "field", ")", ":", "try", ":", "return", "getattr", "(", "obj", ",", "field", ")", "except", "AttributeError", "as", "e", ":", "try", ":", "return", "getattr", "(", "obj", ",", "'_'", "+", "field", ")", "except", "AttributeError", ":", "raise", "e", "return", "(", "getattr_better", "(", "self", ",", "attr", ")", "for", "attr", "in", "self", ".", "_repr_attributes", ")" ]
Return values that are to be shown in repr string.
[ "Return", "values", "that", "are", "to", "be", "shown", "in", "repr", "string", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L98-L109
228,150
JelteF/PyLaTeX
pylatex/base_classes/latex_object.py
LatexObject._repr_attributes
def _repr_attributes(self): """Return attributes that should be part of the repr string.""" if self._repr_attributes_override is None: # Default to init arguments attrs = getfullargspec(self.__init__).args[1:] mapping = self._repr_attributes_mapping if mapping: attrs = [mapping[a] if a in mapping else a for a in attrs] return attrs return self._repr_attributes_override
python
def _repr_attributes(self): """Return attributes that should be part of the repr string.""" if self._repr_attributes_override is None: # Default to init arguments attrs = getfullargspec(self.__init__).args[1:] mapping = self._repr_attributes_mapping if mapping: attrs = [mapping[a] if a in mapping else a for a in attrs] return attrs return self._repr_attributes_override
[ "def", "_repr_attributes", "(", "self", ")", ":", "if", "self", ".", "_repr_attributes_override", "is", "None", ":", "# Default to init arguments", "attrs", "=", "getfullargspec", "(", "self", ".", "__init__", ")", ".", "args", "[", "1", ":", "]", "mapping", "=", "self", ".", "_repr_attributes_mapping", "if", "mapping", ":", "attrs", "=", "[", "mapping", "[", "a", "]", "if", "a", "in", "mapping", "else", "a", "for", "a", "in", "attrs", "]", "return", "attrs", "return", "self", ".", "_repr_attributes_override" ]
Return attributes that should be part of the repr string.
[ "Return", "attributes", "that", "should", "be", "part", "of", "the", "repr", "string", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L112-L122
228,151
JelteF/PyLaTeX
pylatex/base_classes/latex_object.py
LatexObject.latex_name
def latex_name(self): """Return the name of the class used in LaTeX. It can be `None` when the class doesn't have a name. """ star = ('*' if self._star_latex_name else '') if self._latex_name is not None: return self._latex_name + star return self.__class__.__name__.lower() + star
python
def latex_name(self): """Return the name of the class used in LaTeX. It can be `None` when the class doesn't have a name. """ star = ('*' if self._star_latex_name else '') if self._latex_name is not None: return self._latex_name + star return self.__class__.__name__.lower() + star
[ "def", "latex_name", "(", "self", ")", ":", "star", "=", "(", "'*'", "if", "self", ".", "_star_latex_name", "else", "''", ")", "if", "self", ".", "_latex_name", "is", "not", "None", ":", "return", "self", ".", "_latex_name", "+", "star", "return", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", "+", "star" ]
Return the name of the class used in LaTeX. It can be `None` when the class doesn't have a name.
[ "Return", "the", "name", "of", "the", "class", "used", "in", "LaTeX", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L125-L133
228,152
JelteF/PyLaTeX
pylatex/base_classes/latex_object.py
LatexObject.generate_tex
def generate_tex(self, filepath): """Generate a .tex file. Args ---- filepath: str The name of the file (without .tex) """ with open(filepath + '.tex', 'w', encoding='utf-8') as newf: self.dump(newf)
python
def generate_tex(self, filepath): """Generate a .tex file. Args ---- filepath: str The name of the file (without .tex) """ with open(filepath + '.tex', 'w', encoding='utf-8') as newf: self.dump(newf)
[ "def", "generate_tex", "(", "self", ",", "filepath", ")", ":", "with", "open", "(", "filepath", "+", "'.tex'", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "newf", ":", "self", ".", "dump", "(", "newf", ")" ]
Generate a .tex file. Args ---- filepath: str The name of the file (without .tex)
[ "Generate", "a", ".", "tex", "file", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L159-L169
228,153
JelteF/PyLaTeX
pylatex/base_classes/latex_object.py
LatexObject.dumps_as_content
def dumps_as_content(self): """Create a string representation of the object as content. This is currently only used to add new lines before and after the output of the dumps function. These can be added or removed by changing the `begin_paragraph`, `end_paragraph` and `separate_paragraph` attributes of the class. """ string = self.dumps() if self.separate_paragraph or self.begin_paragraph: string = '\n\n' + string.lstrip('\n') if self.separate_paragraph or self.end_paragraph: string = string.rstrip('\n') + '\n\n' return string
python
def dumps_as_content(self): """Create a string representation of the object as content. This is currently only used to add new lines before and after the output of the dumps function. These can be added or removed by changing the `begin_paragraph`, `end_paragraph` and `separate_paragraph` attributes of the class. """ string = self.dumps() if self.separate_paragraph or self.begin_paragraph: string = '\n\n' + string.lstrip('\n') if self.separate_paragraph or self.end_paragraph: string = string.rstrip('\n') + '\n\n' return string
[ "def", "dumps_as_content", "(", "self", ")", ":", "string", "=", "self", ".", "dumps", "(", ")", "if", "self", ".", "separate_paragraph", "or", "self", ".", "begin_paragraph", ":", "string", "=", "'\\n\\n'", "+", "string", ".", "lstrip", "(", "'\\n'", ")", "if", "self", ".", "separate_paragraph", "or", "self", ".", "end_paragraph", ":", "string", "=", "string", ".", "rstrip", "(", "'\\n'", ")", "+", "'\\n\\n'", "return", "string" ]
Create a string representation of the object as content. This is currently only used to add new lines before and after the output of the dumps function. These can be added or removed by changing the `begin_paragraph`, `end_paragraph` and `separate_paragraph` attributes of the class.
[ "Create", "a", "string", "representation", "of", "the", "object", "as", "content", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L193-L210
228,154
JelteF/PyLaTeX
pylatex/document.py
Document._propagate_packages
def _propagate_packages(self): r"""Propogate packages. Make sure that all the packages included in the previous containers are part of the full list of packages. """ super()._propagate_packages() for item in (self.preamble): if isinstance(item, LatexObject): if isinstance(item, Container): item._propagate_packages() for p in item.packages: self.packages.add(p)
python
def _propagate_packages(self): r"""Propogate packages. Make sure that all the packages included in the previous containers are part of the full list of packages. """ super()._propagate_packages() for item in (self.preamble): if isinstance(item, LatexObject): if isinstance(item, Container): item._propagate_packages() for p in item.packages: self.packages.add(p)
[ "def", "_propagate_packages", "(", "self", ")", ":", "super", "(", ")", ".", "_propagate_packages", "(", ")", "for", "item", "in", "(", "self", ".", "preamble", ")", ":", "if", "isinstance", "(", "item", ",", "LatexObject", ")", ":", "if", "isinstance", "(", "item", ",", "Container", ")", ":", "item", ".", "_propagate_packages", "(", ")", "for", "p", "in", "item", ".", "packages", ":", "self", ".", "packages", ".", "add", "(", "p", ")" ]
r"""Propogate packages. Make sure that all the packages included in the previous containers are part of the full list of packages.
[ "r", "Propogate", "packages", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L129-L143
228,155
JelteF/PyLaTeX
pylatex/document.py
Document.dumps
def dumps(self): """Represent the document as a string in LaTeX syntax. Returns ------- str """ head = self.documentclass.dumps() + '%\n' head += self.dumps_packages() + '%\n' head += dumps_list(self.variables) + '%\n' head += dumps_list(self.preamble) + '%\n' return head + '%\n' + super().dumps()
python
def dumps(self): """Represent the document as a string in LaTeX syntax. Returns ------- str """ head = self.documentclass.dumps() + '%\n' head += self.dumps_packages() + '%\n' head += dumps_list(self.variables) + '%\n' head += dumps_list(self.preamble) + '%\n' return head + '%\n' + super().dumps()
[ "def", "dumps", "(", "self", ")", ":", "head", "=", "self", ".", "documentclass", ".", "dumps", "(", ")", "+", "'%\\n'", "head", "+=", "self", ".", "dumps_packages", "(", ")", "+", "'%\\n'", "head", "+=", "dumps_list", "(", "self", ".", "variables", ")", "+", "'%\\n'", "head", "+=", "dumps_list", "(", "self", ".", "preamble", ")", "+", "'%\\n'", "return", "head", "+", "'%\\n'", "+", "super", "(", ")", ".", "dumps", "(", ")" ]
Represent the document as a string in LaTeX syntax. Returns ------- str
[ "Represent", "the", "document", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L145-L158
228,156
JelteF/PyLaTeX
pylatex/document.py
Document.generate_pdf
def generate_pdf(self, filepath=None, *, clean=True, clean_tex=True, compiler=None, compiler_args=None, silent=True): """Generate a pdf file from the document. Args ---- filepath: str The name of the file (without .pdf), if it is `None` the ``default_filepath`` attribute will be used. clean: bool Whether non-pdf files created that are created during compilation should be removed. clean_tex: bool Also remove the generated tex file. compiler: `str` or `None` The name of the LaTeX compiler to use. If it is None, PyLaTeX will choose a fitting one on its own. Starting with ``latexmk`` and then ``pdflatex``. compiler_args: `list` or `None` Extra arguments that should be passed to the LaTeX compiler. If this is None it defaults to an empty list. silent: bool Whether to hide compiler output """ if compiler_args is None: compiler_args = [] filepath = self._select_filepath(filepath) filepath = os.path.join('.', filepath) cur_dir = os.getcwd() dest_dir = os.path.dirname(filepath) basename = os.path.basename(filepath) if basename == '': basename = 'default_basename' os.chdir(dest_dir) self.generate_tex(basename) if compiler is not None: compilers = ((compiler, []),) else: latexmk_args = ['--pdf'] compilers = ( ('latexmk', latexmk_args), ('pdflatex', []) ) main_arguments = ['--interaction=nonstopmode', basename + '.tex'] os_error = None for compiler, arguments in compilers: command = [compiler] + arguments + compiler_args + main_arguments try: output = subprocess.check_output(command, stderr=subprocess.STDOUT) except (OSError, IOError) as e: # Use FileNotFoundError when python 2 is dropped os_error = e if os_error.errno == errno.ENOENT: # If compiler does not exist, try next in the list continue raise except subprocess.CalledProcessError as e: # For all other errors print the output and raise the error print(e.output.decode()) raise else: if not silent: print(output.decode()) if clean: try: # Try latexmk cleaning first subprocess.check_output(['latexmk', '-c', basename], stderr=subprocess.STDOUT) except (OSError, IOError, subprocess.CalledProcessError) as e: # Otherwise just remove some file extensions. extensions = ['aux', 'log', 'out', 'fls', 'fdb_latexmk'] for ext in extensions: try: os.remove(basename + '.' + ext) except (OSError, IOError) as e: # Use FileNotFoundError when python 2 is dropped if e.errno != errno.ENOENT: raise rm_temp_dir() if clean_tex: os.remove(basename + '.tex') # Remove generated tex file # Compilation has finished, so no further compilers have to be # tried break else: # Notify user that none of the compilers worked. raise(CompilerError( 'No LaTex compiler was found\n' + 'Either specify a LaTex compiler ' + 'or make sure you have latexmk or pdfLaTex installed.' )) os.chdir(cur_dir)
python
def generate_pdf(self, filepath=None, *, clean=True, clean_tex=True, compiler=None, compiler_args=None, silent=True): """Generate a pdf file from the document. Args ---- filepath: str The name of the file (without .pdf), if it is `None` the ``default_filepath`` attribute will be used. clean: bool Whether non-pdf files created that are created during compilation should be removed. clean_tex: bool Also remove the generated tex file. compiler: `str` or `None` The name of the LaTeX compiler to use. If it is None, PyLaTeX will choose a fitting one on its own. Starting with ``latexmk`` and then ``pdflatex``. compiler_args: `list` or `None` Extra arguments that should be passed to the LaTeX compiler. If this is None it defaults to an empty list. silent: bool Whether to hide compiler output """ if compiler_args is None: compiler_args = [] filepath = self._select_filepath(filepath) filepath = os.path.join('.', filepath) cur_dir = os.getcwd() dest_dir = os.path.dirname(filepath) basename = os.path.basename(filepath) if basename == '': basename = 'default_basename' os.chdir(dest_dir) self.generate_tex(basename) if compiler is not None: compilers = ((compiler, []),) else: latexmk_args = ['--pdf'] compilers = ( ('latexmk', latexmk_args), ('pdflatex', []) ) main_arguments = ['--interaction=nonstopmode', basename + '.tex'] os_error = None for compiler, arguments in compilers: command = [compiler] + arguments + compiler_args + main_arguments try: output = subprocess.check_output(command, stderr=subprocess.STDOUT) except (OSError, IOError) as e: # Use FileNotFoundError when python 2 is dropped os_error = e if os_error.errno == errno.ENOENT: # If compiler does not exist, try next in the list continue raise except subprocess.CalledProcessError as e: # For all other errors print the output and raise the error print(e.output.decode()) raise else: if not silent: print(output.decode()) if clean: try: # Try latexmk cleaning first subprocess.check_output(['latexmk', '-c', basename], stderr=subprocess.STDOUT) except (OSError, IOError, subprocess.CalledProcessError) as e: # Otherwise just remove some file extensions. extensions = ['aux', 'log', 'out', 'fls', 'fdb_latexmk'] for ext in extensions: try: os.remove(basename + '.' + ext) except (OSError, IOError) as e: # Use FileNotFoundError when python 2 is dropped if e.errno != errno.ENOENT: raise rm_temp_dir() if clean_tex: os.remove(basename + '.tex') # Remove generated tex file # Compilation has finished, so no further compilers have to be # tried break else: # Notify user that none of the compilers worked. raise(CompilerError( 'No LaTex compiler was found\n' + 'Either specify a LaTex compiler ' + 'or make sure you have latexmk or pdfLaTex installed.' )) os.chdir(cur_dir)
[ "def", "generate_pdf", "(", "self", ",", "filepath", "=", "None", ",", "*", ",", "clean", "=", "True", ",", "clean_tex", "=", "True", ",", "compiler", "=", "None", ",", "compiler_args", "=", "None", ",", "silent", "=", "True", ")", ":", "if", "compiler_args", "is", "None", ":", "compiler_args", "=", "[", "]", "filepath", "=", "self", ".", "_select_filepath", "(", "filepath", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "'.'", ",", "filepath", ")", "cur_dir", "=", "os", ".", "getcwd", "(", ")", "dest_dir", "=", "os", ".", "path", ".", "dirname", "(", "filepath", ")", "basename", "=", "os", ".", "path", ".", "basename", "(", "filepath", ")", "if", "basename", "==", "''", ":", "basename", "=", "'default_basename'", "os", ".", "chdir", "(", "dest_dir", ")", "self", ".", "generate_tex", "(", "basename", ")", "if", "compiler", "is", "not", "None", ":", "compilers", "=", "(", "(", "compiler", ",", "[", "]", ")", ",", ")", "else", ":", "latexmk_args", "=", "[", "'--pdf'", "]", "compilers", "=", "(", "(", "'latexmk'", ",", "latexmk_args", ")", ",", "(", "'pdflatex'", ",", "[", "]", ")", ")", "main_arguments", "=", "[", "'--interaction=nonstopmode'", ",", "basename", "+", "'.tex'", "]", "os_error", "=", "None", "for", "compiler", ",", "arguments", "in", "compilers", ":", "command", "=", "[", "compiler", "]", "+", "arguments", "+", "compiler_args", "+", "main_arguments", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "command", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "# Use FileNotFoundError when python 2 is dropped", "os_error", "=", "e", "if", "os_error", ".", "errno", "==", "errno", ".", "ENOENT", ":", "# If compiler does not exist, try next in the list", "continue", "raise", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "# For all other errors print the output and raise the error", "print", "(", "e", ".", "output", ".", "decode", "(", ")", ")", "raise", "else", ":", "if", "not", "silent", ":", "print", "(", "output", ".", "decode", "(", ")", ")", "if", "clean", ":", "try", ":", "# Try latexmk cleaning first", "subprocess", ".", "check_output", "(", "[", "'latexmk'", ",", "'-c'", ",", "basename", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "except", "(", "OSError", ",", "IOError", ",", "subprocess", ".", "CalledProcessError", ")", "as", "e", ":", "# Otherwise just remove some file extensions.", "extensions", "=", "[", "'aux'", ",", "'log'", ",", "'out'", ",", "'fls'", ",", "'fdb_latexmk'", "]", "for", "ext", "in", "extensions", ":", "try", ":", "os", ".", "remove", "(", "basename", "+", "'.'", "+", "ext", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "# Use FileNotFoundError when python 2 is dropped", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise", "rm_temp_dir", "(", ")", "if", "clean_tex", ":", "os", ".", "remove", "(", "basename", "+", "'.tex'", ")", "# Remove generated tex file", "# Compilation has finished, so no further compilers have to be", "# tried", "break", "else", ":", "# Notify user that none of the compilers worked.", "raise", "(", "CompilerError", "(", "'No LaTex compiler was found\\n'", "+", "'Either specify a LaTex compiler '", "+", "'or make sure you have latexmk or pdfLaTex installed.'", ")", ")", "os", ".", "chdir", "(", "cur_dir", ")" ]
Generate a pdf file from the document. Args ---- filepath: str The name of the file (without .pdf), if it is `None` the ``default_filepath`` attribute will be used. clean: bool Whether non-pdf files created that are created during compilation should be removed. clean_tex: bool Also remove the generated tex file. compiler: `str` or `None` The name of the LaTeX compiler to use. If it is None, PyLaTeX will choose a fitting one on its own. Starting with ``latexmk`` and then ``pdflatex``. compiler_args: `list` or `None` Extra arguments that should be passed to the LaTeX compiler. If this is None it defaults to an empty list. silent: bool Whether to hide compiler output
[ "Generate", "a", "pdf", "file", "from", "the", "document", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L172-L284
228,157
JelteF/PyLaTeX
pylatex/document.py
Document._select_filepath
def _select_filepath(self, filepath): """Make a choice between ``filepath`` and ``self.default_filepath``. Args ---- filepath: str the filepath to be compared with ``self.default_filepath`` Returns ------- str The selected filepath """ if filepath is None: return self.default_filepath else: if os.path.basename(filepath) == '': filepath = os.path.join(filepath, os.path.basename( self.default_filepath)) return filepath
python
def _select_filepath(self, filepath): """Make a choice between ``filepath`` and ``self.default_filepath``. Args ---- filepath: str the filepath to be compared with ``self.default_filepath`` Returns ------- str The selected filepath """ if filepath is None: return self.default_filepath else: if os.path.basename(filepath) == '': filepath = os.path.join(filepath, os.path.basename( self.default_filepath)) return filepath
[ "def", "_select_filepath", "(", "self", ",", "filepath", ")", ":", "if", "filepath", "is", "None", ":", "return", "self", ".", "default_filepath", "else", ":", "if", "os", ".", "path", ".", "basename", "(", "filepath", ")", "==", "''", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "filepath", ",", "os", ".", "path", ".", "basename", "(", "self", ".", "default_filepath", ")", ")", "return", "filepath" ]
Make a choice between ``filepath`` and ``self.default_filepath``. Args ---- filepath: str the filepath to be compared with ``self.default_filepath`` Returns ------- str The selected filepath
[ "Make", "a", "choice", "between", "filepath", "and", "self", ".", "default_filepath", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L286-L306
228,158
JelteF/PyLaTeX
pylatex/document.py
Document.add_color
def add_color(self, name, model, description): r"""Add a color that can be used throughout the document. Args ---- name: str Name to set for the color model: str The color model to use when defining the color description: str The values to use to define the color """ if self.color is False: self.packages.append(Package("color")) self.color = True self.preamble.append(Command("definecolor", arguments=[name, model, description]))
python
def add_color(self, name, model, description): r"""Add a color that can be used throughout the document. Args ---- name: str Name to set for the color model: str The color model to use when defining the color description: str The values to use to define the color """ if self.color is False: self.packages.append(Package("color")) self.color = True self.preamble.append(Command("definecolor", arguments=[name, model, description]))
[ "def", "add_color", "(", "self", ",", "name", ",", "model", ",", "description", ")", ":", "if", "self", ".", "color", "is", "False", ":", "self", ".", "packages", ".", "append", "(", "Package", "(", "\"color\"", ")", ")", "self", ".", "color", "=", "True", "self", ".", "preamble", ".", "append", "(", "Command", "(", "\"definecolor\"", ",", "arguments", "=", "[", "name", ",", "model", ",", "description", "]", ")", ")" ]
r"""Add a color that can be used throughout the document. Args ---- name: str Name to set for the color model: str The color model to use when defining the color description: str The values to use to define the color
[ "r", "Add", "a", "color", "that", "can", "be", "used", "throughout", "the", "document", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L330-L349
228,159
JelteF/PyLaTeX
pylatex/document.py
Document.change_length
def change_length(self, parameter, value): r"""Change the length of a certain parameter to a certain value. Args ---- parameter: str The name of the parameter to change the length for value: str The value to set the parameter to """ self.preamble.append(UnsafeCommand('setlength', arguments=[parameter, value]))
python
def change_length(self, parameter, value): r"""Change the length of a certain parameter to a certain value. Args ---- parameter: str The name of the parameter to change the length for value: str The value to set the parameter to """ self.preamble.append(UnsafeCommand('setlength', arguments=[parameter, value]))
[ "def", "change_length", "(", "self", ",", "parameter", ",", "value", ")", ":", "self", ".", "preamble", ".", "append", "(", "UnsafeCommand", "(", "'setlength'", ",", "arguments", "=", "[", "parameter", ",", "value", "]", ")", ")" ]
r"""Change the length of a certain parameter to a certain value. Args ---- parameter: str The name of the parameter to change the length for value: str The value to set the parameter to
[ "r", "Change", "the", "length", "of", "a", "certain", "parameter", "to", "a", "certain", "value", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L351-L363
228,160
JelteF/PyLaTeX
pylatex/document.py
Document.set_variable
def set_variable(self, name, value): r"""Add a variable which can be used inside the document. Variables are defined before the preamble. If a variable with that name has already been set, the new value will override it for future uses. This is done by appending ``\renewcommand`` to the document. Args ---- name: str The name to set for the variable value: str The value to set for the variable """ name_arg = "\\" + name variable_exists = False for variable in self.variables: if name_arg == variable.arguments._positional_args[0]: variable_exists = True break if variable_exists: renew = Command(command="renewcommand", arguments=[NoEscape(name_arg), value]) self.append(renew) else: new = Command(command="newcommand", arguments=[NoEscape(name_arg), value]) self.variables.append(new)
python
def set_variable(self, name, value): r"""Add a variable which can be used inside the document. Variables are defined before the preamble. If a variable with that name has already been set, the new value will override it for future uses. This is done by appending ``\renewcommand`` to the document. Args ---- name: str The name to set for the variable value: str The value to set for the variable """ name_arg = "\\" + name variable_exists = False for variable in self.variables: if name_arg == variable.arguments._positional_args[0]: variable_exists = True break if variable_exists: renew = Command(command="renewcommand", arguments=[NoEscape(name_arg), value]) self.append(renew) else: new = Command(command="newcommand", arguments=[NoEscape(name_arg), value]) self.variables.append(new)
[ "def", "set_variable", "(", "self", ",", "name", ",", "value", ")", ":", "name_arg", "=", "\"\\\\\"", "+", "name", "variable_exists", "=", "False", "for", "variable", "in", "self", ".", "variables", ":", "if", "name_arg", "==", "variable", ".", "arguments", ".", "_positional_args", "[", "0", "]", ":", "variable_exists", "=", "True", "break", "if", "variable_exists", ":", "renew", "=", "Command", "(", "command", "=", "\"renewcommand\"", ",", "arguments", "=", "[", "NoEscape", "(", "name_arg", ")", ",", "value", "]", ")", "self", ".", "append", "(", "renew", ")", "else", ":", "new", "=", "Command", "(", "command", "=", "\"newcommand\"", ",", "arguments", "=", "[", "NoEscape", "(", "name_arg", ")", ",", "value", "]", ")", "self", ".", "variables", ".", "append", "(", "new", ")" ]
r"""Add a variable which can be used inside the document. Variables are defined before the preamble. If a variable with that name has already been set, the new value will override it for future uses. This is done by appending ``\renewcommand`` to the document. Args ---- name: str The name to set for the variable value: str The value to set for the variable
[ "r", "Add", "a", "variable", "which", "can", "be", "used", "inside", "the", "document", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L365-L395
228,161
JelteF/PyLaTeX
pylatex/config.py
Version1.change
def change(self, **kwargs): """Override some attributes of the config in a specific context. A simple usage example:: with pylatex.config.active.change(indent=False): # Do stuff where indent should be False ... Args ---- kwargs: Key value pairs of the default attributes that should be overridden """ old_attrs = {} for k, v in kwargs.items(): old_attrs[k] = getattr(self, k, v) setattr(self, k, v) yield self # allows with ... as ... for k, v in old_attrs.items(): setattr(self, k, v)
python
def change(self, **kwargs): """Override some attributes of the config in a specific context. A simple usage example:: with pylatex.config.active.change(indent=False): # Do stuff where indent should be False ... Args ---- kwargs: Key value pairs of the default attributes that should be overridden """ old_attrs = {} for k, v in kwargs.items(): old_attrs[k] = getattr(self, k, v) setattr(self, k, v) yield self # allows with ... as ... for k, v in old_attrs.items(): setattr(self, k, v)
[ "def", "change", "(", "self", ",", "*", "*", "kwargs", ")", ":", "old_attrs", "=", "{", "}", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "old_attrs", "[", "k", "]", "=", "getattr", "(", "self", ",", "k", ",", "v", ")", "setattr", "(", "self", ",", "k", ",", "v", ")", "yield", "self", "# allows with ... as ...", "for", "k", ",", "v", "in", "old_attrs", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "k", ",", "v", ")" ]
Override some attributes of the config in a specific context. A simple usage example:: with pylatex.config.active.change(indent=False): # Do stuff where indent should be False ... Args ---- kwargs: Key value pairs of the default attributes that should be overridden
[ "Override", "some", "attributes", "of", "the", "config", "in", "a", "specific", "context", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/config.py#L63-L87
228,162
JelteF/PyLaTeX
pylatex/base_classes/command.py
CommandBase.__key
def __key(self): """Return a hashable key, representing the command. Returns ------- tuple """ return (self.latex_name, self.arguments, self.options, self.extra_arguments)
python
def __key(self): """Return a hashable key, representing the command. Returns ------- tuple """ return (self.latex_name, self.arguments, self.options, self.extra_arguments)
[ "def", "__key", "(", "self", ")", ":", "return", "(", "self", ".", "latex_name", ",", "self", ".", "arguments", ",", "self", ".", "options", ",", "self", ".", "extra_arguments", ")" ]
Return a hashable key, representing the command. Returns ------- tuple
[ "Return", "a", "hashable", "key", "representing", "the", "command", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/command.py#L65-L74
228,163
JelteF/PyLaTeX
pylatex/base_classes/command.py
CommandBase.dumps
def dumps(self): """Represent the command as a string in LaTeX syntax. Returns ------- str The LaTeX formatted command """ options = self.options.dumps() arguments = self.arguments.dumps() if self.extra_arguments is None: return r'\{command}{options}{arguments}'\ .format(command=self.latex_name, options=options, arguments=arguments) extra_arguments = self.extra_arguments.dumps() return r'\{command}{arguments}{options}{extra_arguments}'\ .format(command=self.latex_name, arguments=arguments, options=options, extra_arguments=extra_arguments)
python
def dumps(self): """Represent the command as a string in LaTeX syntax. Returns ------- str The LaTeX formatted command """ options = self.options.dumps() arguments = self.arguments.dumps() if self.extra_arguments is None: return r'\{command}{options}{arguments}'\ .format(command=self.latex_name, options=options, arguments=arguments) extra_arguments = self.extra_arguments.dumps() return r'\{command}{arguments}{options}{extra_arguments}'\ .format(command=self.latex_name, arguments=arguments, options=options, extra_arguments=extra_arguments)
[ "def", "dumps", "(", "self", ")", ":", "options", "=", "self", ".", "options", ".", "dumps", "(", ")", "arguments", "=", "self", ".", "arguments", ".", "dumps", "(", ")", "if", "self", ".", "extra_arguments", "is", "None", ":", "return", "r'\\{command}{options}{arguments}'", ".", "format", "(", "command", "=", "self", ".", "latex_name", ",", "options", "=", "options", ",", "arguments", "=", "arguments", ")", "extra_arguments", "=", "self", ".", "extra_arguments", ".", "dumps", "(", ")", "return", "r'\\{command}{arguments}{options}{extra_arguments}'", ".", "format", "(", "command", "=", "self", ".", "latex_name", ",", "arguments", "=", "arguments", ",", "options", "=", "options", ",", "extra_arguments", "=", "extra_arguments", ")" ]
Represent the command as a string in LaTeX syntax. Returns ------- str The LaTeX formatted command
[ "Represent", "the", "command", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/command.py#L107-L128
228,164
JelteF/PyLaTeX
pylatex/base_classes/command.py
Parameters._format_contents
def _format_contents(self, prefix, separator, suffix): """Format the parameters. The formatting is done using the three arguments suplied to this function. Arguments --------- prefix: str separator: str suffix: str Returns ------- str """ params = self._list_args_kwargs() if len(params) <= 0: return '' string = prefix + dumps_list(params, escape=self.escape, token=separator) + suffix return string
python
def _format_contents(self, prefix, separator, suffix): """Format the parameters. The formatting is done using the three arguments suplied to this function. Arguments --------- prefix: str separator: str suffix: str Returns ------- str """ params = self._list_args_kwargs() if len(params) <= 0: return '' string = prefix + dumps_list(params, escape=self.escape, token=separator) + suffix return string
[ "def", "_format_contents", "(", "self", ",", "prefix", ",", "separator", ",", "suffix", ")", ":", "params", "=", "self", ".", "_list_args_kwargs", "(", ")", "if", "len", "(", "params", ")", "<=", "0", ":", "return", "''", "string", "=", "prefix", "+", "dumps_list", "(", "params", ",", "escape", "=", "self", ".", "escape", ",", "token", "=", "separator", ")", "+", "suffix", "return", "string" ]
Format the parameters. The formatting is done using the three arguments suplied to this function. Arguments --------- prefix: str separator: str suffix: str Returns ------- str
[ "Format", "the", "parameters", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/command.py#L264-L289
228,165
JelteF/PyLaTeX
pylatex/base_classes/command.py
Parameters._list_args_kwargs
def _list_args_kwargs(self): """Make a list of strings representing al parameters. Returns ------- list """ params = [] params.extend(self._positional_args) params.extend(['{k}={v}'.format(k=k, v=v) for k, v in self._key_value_args.items()]) return params
python
def _list_args_kwargs(self): """Make a list of strings representing al parameters. Returns ------- list """ params = [] params.extend(self._positional_args) params.extend(['{k}={v}'.format(k=k, v=v) for k, v in self._key_value_args.items()]) return params
[ "def", "_list_args_kwargs", "(", "self", ")", ":", "params", "=", "[", "]", "params", ".", "extend", "(", "self", ".", "_positional_args", ")", "params", ".", "extend", "(", "[", "'{k}={v}'", ".", "format", "(", "k", "=", "k", ",", "v", "=", "v", ")", "for", "k", ",", "v", "in", "self", ".", "_key_value_args", ".", "items", "(", ")", "]", ")", "return", "params" ]
Make a list of strings representing al parameters. Returns ------- list
[ "Make", "a", "list", "of", "strings", "representing", "al", "parameters", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/command.py#L291-L304
228,166
JelteF/PyLaTeX
pylatex/math.py
Matrix.dumps_content
def dumps_content(self): """Return a string representing the matrix in LaTeX syntax. Returns ------- str """ import numpy as np string = '' shape = self.matrix.shape for (y, x), value in np.ndenumerate(self.matrix): if x: string += '&' string += str(value) if x == shape[1] - 1 and y != shape[0] - 1: string += r'\\' + '%\n' super().dumps_content() return string
python
def dumps_content(self): """Return a string representing the matrix in LaTeX syntax. Returns ------- str """ import numpy as np string = '' shape = self.matrix.shape for (y, x), value in np.ndenumerate(self.matrix): if x: string += '&' string += str(value) if x == shape[1] - 1 and y != shape[0] - 1: string += r'\\' + '%\n' super().dumps_content() return string
[ "def", "dumps_content", "(", "self", ")", ":", "import", "numpy", "as", "np", "string", "=", "''", "shape", "=", "self", ".", "matrix", ".", "shape", "for", "(", "y", ",", "x", ")", ",", "value", "in", "np", ".", "ndenumerate", "(", "self", ".", "matrix", ")", ":", "if", "x", ":", "string", "+=", "'&'", "string", "+=", "str", "(", "value", ")", "if", "x", "==", "shape", "[", "1", "]", "-", "1", "and", "y", "!=", "shape", "[", "0", "]", "-", "1", ":", "string", "+=", "r'\\\\'", "+", "'%\\n'", "super", "(", ")", ".", "dumps_content", "(", ")", "return", "string" ]
Return a string representing the matrix in LaTeX syntax. Returns ------- str
[ "Return", "a", "string", "representing", "the", "matrix", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/math.py#L133-L156
228,167
JelteF/PyLaTeX
pylatex/headfoot.py
PageStyle.change_thickness
def change_thickness(self, element, thickness): r"""Change line thickness. Changes the thickness of the line under/over the header/footer to the specified thickness. Args ---- element: str the name of the element to change thickness for: header, footer thickness: float the thickness to set the line to """ if element == "header": self.data.append(Command("renewcommand", arguments=[NoEscape(r"\headrulewidth"), str(thickness) + 'pt'])) elif element == "footer": self.data.append(Command("renewcommand", arguments=[ NoEscape(r"\footrulewidth"), str(thickness) + 'pt']))
python
def change_thickness(self, element, thickness): r"""Change line thickness. Changes the thickness of the line under/over the header/footer to the specified thickness. Args ---- element: str the name of the element to change thickness for: header, footer thickness: float the thickness to set the line to """ if element == "header": self.data.append(Command("renewcommand", arguments=[NoEscape(r"\headrulewidth"), str(thickness) + 'pt'])) elif element == "footer": self.data.append(Command("renewcommand", arguments=[ NoEscape(r"\footrulewidth"), str(thickness) + 'pt']))
[ "def", "change_thickness", "(", "self", ",", "element", ",", "thickness", ")", ":", "if", "element", "==", "\"header\"", ":", "self", ".", "data", ".", "append", "(", "Command", "(", "\"renewcommand\"", ",", "arguments", "=", "[", "NoEscape", "(", "r\"\\headrulewidth\"", ")", ",", "str", "(", "thickness", ")", "+", "'pt'", "]", ")", ")", "elif", "element", "==", "\"footer\"", ":", "self", ".", "data", ".", "append", "(", "Command", "(", "\"renewcommand\"", ",", "arguments", "=", "[", "NoEscape", "(", "r\"\\footrulewidth\"", ")", ",", "str", "(", "thickness", ")", "+", "'pt'", "]", ")", ")" ]
r"""Change line thickness. Changes the thickness of the line under/over the header/footer to the specified thickness. Args ---- element: str the name of the element to change thickness for: header, footer thickness: float the thickness to set the line to
[ "r", "Change", "line", "thickness", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/headfoot.py#L47-L67
228,168
JelteF/PyLaTeX
pylatex/tikz.py
TikZCoordinate.from_str
def from_str(cls, coordinate): """Build a TikZCoordinate object from a string.""" m = cls._coordinate_str_regex.match(coordinate) if m is None: raise ValueError('invalid coordinate string') if m.group(1) == '++': relative = True else: relative = False return TikZCoordinate( float(m.group(2)), float(m.group(4)), relative=relative)
python
def from_str(cls, coordinate): """Build a TikZCoordinate object from a string.""" m = cls._coordinate_str_regex.match(coordinate) if m is None: raise ValueError('invalid coordinate string') if m.group(1) == '++': relative = True else: relative = False return TikZCoordinate( float(m.group(2)), float(m.group(4)), relative=relative)
[ "def", "from_str", "(", "cls", ",", "coordinate", ")", ":", "m", "=", "cls", ".", "_coordinate_str_regex", ".", "match", "(", "coordinate", ")", "if", "m", "is", "None", ":", "raise", "ValueError", "(", "'invalid coordinate string'", ")", "if", "m", ".", "group", "(", "1", ")", "==", "'++'", ":", "relative", "=", "True", "else", ":", "relative", "=", "False", "return", "TikZCoordinate", "(", "float", "(", "m", ".", "group", "(", "2", ")", ")", ",", "float", "(", "m", ".", "group", "(", "4", ")", ")", ",", "relative", "=", "relative", ")" ]
Build a TikZCoordinate object from a string.
[ "Build", "a", "TikZCoordinate", "object", "from", "a", "string", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L89-L103
228,169
JelteF/PyLaTeX
pylatex/tikz.py
TikZCoordinate.distance_to
def distance_to(self, other): """Euclidean distance between two coordinates.""" other_coord = self._arith_check(other) return math.sqrt(math.pow(self._x - other_coord._x, 2) + math.pow(self._y - other_coord._y, 2))
python
def distance_to(self, other): """Euclidean distance between two coordinates.""" other_coord = self._arith_check(other) return math.sqrt(math.pow(self._x - other_coord._x, 2) + math.pow(self._y - other_coord._y, 2))
[ "def", "distance_to", "(", "self", ",", "other", ")", ":", "other_coord", "=", "self", ".", "_arith_check", "(", "other", ")", "return", "math", ".", "sqrt", "(", "math", ".", "pow", "(", "self", ".", "_x", "-", "other_coord", ".", "_x", ",", "2", ")", "+", "math", ".", "pow", "(", "self", ".", "_y", "-", "other_coord", ".", "_y", ",", "2", ")", ")" ]
Euclidean distance between two coordinates.
[ "Euclidean", "distance", "between", "two", "coordinates", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L151-L156
228,170
JelteF/PyLaTeX
pylatex/tikz.py
TikZNode.dumps
def dumps(self): """Return string representation of the node.""" ret_str = [] ret_str.append(Command('node', options=self.options).dumps()) if self.handle is not None: ret_str.append('({})'.format(self.handle)) if self._node_position is not None: ret_str.append('at {}'.format(str(self._position))) if self._node_text is not None: ret_str.append('{{{text}}};'.format(text=self._node_text)) else: ret_str.append('{};') return ' '.join(ret_str)
python
def dumps(self): """Return string representation of the node.""" ret_str = [] ret_str.append(Command('node', options=self.options).dumps()) if self.handle is not None: ret_str.append('({})'.format(self.handle)) if self._node_position is not None: ret_str.append('at {}'.format(str(self._position))) if self._node_text is not None: ret_str.append('{{{text}}};'.format(text=self._node_text)) else: ret_str.append('{};') return ' '.join(ret_str)
[ "def", "dumps", "(", "self", ")", ":", "ret_str", "=", "[", "]", "ret_str", ".", "append", "(", "Command", "(", "'node'", ",", "options", "=", "self", ".", "options", ")", ".", "dumps", "(", ")", ")", "if", "self", ".", "handle", "is", "not", "None", ":", "ret_str", ".", "append", "(", "'({})'", ".", "format", "(", "self", ".", "handle", ")", ")", "if", "self", ".", "_node_position", "is", "not", "None", ":", "ret_str", ".", "append", "(", "'at {}'", ".", "format", "(", "str", "(", "self", ".", "_position", ")", ")", ")", "if", "self", ".", "_node_text", "is", "not", "None", ":", "ret_str", ".", "append", "(", "'{{{text}}};'", ".", "format", "(", "text", "=", "self", ".", "_node_text", ")", ")", "else", ":", "ret_str", ".", "append", "(", "'{};'", ")", "return", "' '", ".", "join", "(", "ret_str", ")" ]
Return string representation of the node.
[ "Return", "string", "representation", "of", "the", "node", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L230-L247
228,171
JelteF/PyLaTeX
pylatex/tikz.py
TikZNode.get_anchor_point
def get_anchor_point(self, anchor_name): """Return an anchor point of the node, if it exists.""" if anchor_name in self._possible_anchors: return TikZNodeAnchor(self.handle, anchor_name) else: try: anchor = int(anchor_name.split('_')[1]) except: anchor = None if anchor is not None: return TikZNodeAnchor(self.handle, str(anchor)) raise ValueError('Invalid anchor name: "{}"'.format(anchor_name))
python
def get_anchor_point(self, anchor_name): """Return an anchor point of the node, if it exists.""" if anchor_name in self._possible_anchors: return TikZNodeAnchor(self.handle, anchor_name) else: try: anchor = int(anchor_name.split('_')[1]) except: anchor = None if anchor is not None: return TikZNodeAnchor(self.handle, str(anchor)) raise ValueError('Invalid anchor name: "{}"'.format(anchor_name))
[ "def", "get_anchor_point", "(", "self", ",", "anchor_name", ")", ":", "if", "anchor_name", "in", "self", ".", "_possible_anchors", ":", "return", "TikZNodeAnchor", "(", "self", ".", "handle", ",", "anchor_name", ")", "else", ":", "try", ":", "anchor", "=", "int", "(", "anchor_name", ".", "split", "(", "'_'", ")", "[", "1", "]", ")", "except", ":", "anchor", "=", "None", "if", "anchor", "is", "not", "None", ":", "return", "TikZNodeAnchor", "(", "self", ".", "handle", ",", "str", "(", "anchor", ")", ")", "raise", "ValueError", "(", "'Invalid anchor name: \"{}\"'", ".", "format", "(", "anchor_name", ")", ")" ]
Return an anchor point of the node, if it exists.
[ "Return", "an", "anchor", "point", "of", "the", "node", "if", "it", "exists", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L249-L263
228,172
JelteF/PyLaTeX
pylatex/tikz.py
TikZUserPath.dumps
def dumps(self): """Return path command representation.""" ret_str = self.path_type if self.options is not None: ret_str += self.options.dumps() return ret_str
python
def dumps(self): """Return path command representation.""" ret_str = self.path_type if self.options is not None: ret_str += self.options.dumps() return ret_str
[ "def", "dumps", "(", "self", ")", ":", "ret_str", "=", "self", ".", "path_type", "if", "self", ".", "options", "is", "not", "None", ":", "ret_str", "+=", "self", ".", "options", ".", "dumps", "(", ")", "return", "ret_str" ]
Return path command representation.
[ "Return", "path", "command", "representation", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L292-L300
228,173
JelteF/PyLaTeX
pylatex/tikz.py
TikZPathList.dumps
def dumps(self): """Return representation of the path command.""" ret_str = [] for item in self._arg_list: if isinstance(item, TikZUserPath): ret_str.append(item.dumps()) elif isinstance(item, TikZCoordinate): ret_str.append(item.dumps()) elif isinstance(item, str): ret_str.append(item) return ' '.join(ret_str)
python
def dumps(self): """Return representation of the path command.""" ret_str = [] for item in self._arg_list: if isinstance(item, TikZUserPath): ret_str.append(item.dumps()) elif isinstance(item, TikZCoordinate): ret_str.append(item.dumps()) elif isinstance(item, str): ret_str.append(item) return ' '.join(ret_str)
[ "def", "dumps", "(", "self", ")", ":", "ret_str", "=", "[", "]", "for", "item", "in", "self", ".", "_arg_list", ":", "if", "isinstance", "(", "item", ",", "TikZUserPath", ")", ":", "ret_str", ".", "append", "(", "item", ".", "dumps", "(", ")", ")", "elif", "isinstance", "(", "item", ",", "TikZCoordinate", ")", ":", "ret_str", ".", "append", "(", "item", ".", "dumps", "(", ")", ")", "elif", "isinstance", "(", "item", ",", "str", ")", ":", "ret_str", ".", "append", "(", "item", ")", "return", "' '", ".", "join", "(", "ret_str", ")" ]
Return representation of the path command.
[ "Return", "representation", "of", "the", "path", "command", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L423-L435
228,174
JelteF/PyLaTeX
pylatex/tikz.py
TikZPath.dumps
def dumps(self): """Return a representation for the command.""" ret_str = [Command('path', options=self.options).dumps()] ret_str.append(self.path.dumps()) return ' '.join(ret_str) + ';'
python
def dumps(self): """Return a representation for the command.""" ret_str = [Command('path', options=self.options).dumps()] ret_str.append(self.path.dumps()) return ' '.join(ret_str) + ';'
[ "def", "dumps", "(", "self", ")", ":", "ret_str", "=", "[", "Command", "(", "'path'", ",", "options", "=", "self", ".", "options", ")", ".", "dumps", "(", ")", "]", "ret_str", ".", "append", "(", "self", ".", "path", ".", "dumps", "(", ")", ")", "return", "' '", ".", "join", "(", "ret_str", ")", "+", "';'" ]
Return a representation for the command.
[ "Return", "a", "representation", "for", "the", "command", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L467-L474
228,175
JelteF/PyLaTeX
pylatex/tikz.py
Plot.dumps
def dumps(self): """Represent the plot as a string in LaTeX syntax. Returns ------- str """ string = Command('addplot', options=self.options).dumps() if self.coordinates is not None: string += ' coordinates {%\n' if self.error_bar is None: for x, y in self.coordinates: # ie: "(x,y)" string += '(' + str(x) + ',' + str(y) + ')%\n' else: for (x, y), (e_x, e_y) in zip(self.coordinates, self.error_bar): # ie: "(x,y) +- (e_x,e_y)" string += '(' + str(x) + ',' + str(y) + \ ') +- (' + str(e_x) + ',' + str(e_y) + ')%\n' string += '};%\n%\n' elif self.func is not None: string += '{' + self.func + '};%\n%\n' if self.name is not None: string += Command('addlegendentry', self.name).dumps() super().dumps() return string
python
def dumps(self): """Represent the plot as a string in LaTeX syntax. Returns ------- str """ string = Command('addplot', options=self.options).dumps() if self.coordinates is not None: string += ' coordinates {%\n' if self.error_bar is None: for x, y in self.coordinates: # ie: "(x,y)" string += '(' + str(x) + ',' + str(y) + ')%\n' else: for (x, y), (e_x, e_y) in zip(self.coordinates, self.error_bar): # ie: "(x,y) +- (e_x,e_y)" string += '(' + str(x) + ',' + str(y) + \ ') +- (' + str(e_x) + ',' + str(e_y) + ')%\n' string += '};%\n%\n' elif self.func is not None: string += '{' + self.func + '};%\n%\n' if self.name is not None: string += Command('addlegendentry', self.name).dumps() super().dumps() return string
[ "def", "dumps", "(", "self", ")", ":", "string", "=", "Command", "(", "'addplot'", ",", "options", "=", "self", ".", "options", ")", ".", "dumps", "(", ")", "if", "self", ".", "coordinates", "is", "not", "None", ":", "string", "+=", "' coordinates {%\\n'", "if", "self", ".", "error_bar", "is", "None", ":", "for", "x", ",", "y", "in", "self", ".", "coordinates", ":", "# ie: \"(x,y)\"", "string", "+=", "'('", "+", "str", "(", "x", ")", "+", "','", "+", "str", "(", "y", ")", "+", "')%\\n'", "else", ":", "for", "(", "x", ",", "y", ")", ",", "(", "e_x", ",", "e_y", ")", "in", "zip", "(", "self", ".", "coordinates", ",", "self", ".", "error_bar", ")", ":", "# ie: \"(x,y) +- (e_x,e_y)\"", "string", "+=", "'('", "+", "str", "(", "x", ")", "+", "','", "+", "str", "(", "y", ")", "+", "') +- ('", "+", "str", "(", "e_x", ")", "+", "','", "+", "str", "(", "e_y", ")", "+", "')%\\n'", "string", "+=", "'};%\\n%\\n'", "elif", "self", ".", "func", "is", "not", "None", ":", "string", "+=", "'{'", "+", "self", ".", "func", "+", "'};%\\n%\\n'", "if", "self", ".", "name", "is", "not", "None", ":", "string", "+=", "Command", "(", "'addlegendentry'", ",", "self", ".", "name", ")", ".", "dumps", "(", ")", "super", "(", ")", ".", "dumps", "(", ")", "return", "string" ]
Represent the plot as a string in LaTeX syntax. Returns ------- str
[ "Represent", "the", "plot", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L530-L565
228,176
SheffieldML/GPyOpt
GPyOpt/core/task/cost.py
CostModel._cost_gp
def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m)
python
def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m)
[ "def", "_cost_gp", "(", "self", ",", "x", ")", ":", "m", ",", "_", ",", "_", ",", "_", "=", "self", ".", "cost_model", ".", "predict_withGradients", "(", "x", ")", "return", "np", ".", "exp", "(", "m", ")" ]
Predicts the time cost of evaluating the function at x.
[ "Predicts", "the", "time", "cost", "of", "evaluating", "the", "function", "at", "x", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/cost.py#L41-L46
228,177
SheffieldML/GPyOpt
GPyOpt/core/task/cost.py
CostModel._cost_gp_withGradients
def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx
python
def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx
[ "def", "_cost_gp_withGradients", "(", "self", ",", "x", ")", ":", "m", ",", "_", ",", "dmdx", ",", "_", "=", "self", ".", "cost_model", ".", "predict_withGradients", "(", "x", ")", "return", "np", ".", "exp", "(", "m", ")", ",", "np", ".", "exp", "(", "m", ")", "*", "dmdx" ]
Predicts the time cost and its gradient of evaluating the function at x.
[ "Predicts", "the", "time", "cost", "and", "its", "gradient", "of", "evaluating", "the", "function", "at", "x", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/cost.py#L48-L53
228,178
SheffieldML/GPyOpt
GPyOpt/core/task/cost.py
CostModel.update_cost_model
def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None)
python
def update_cost_model(self, x, cost_x): """ Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """ if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None)
[ "def", "update_cost_model", "(", "self", ",", "x", ",", "cost_x", ")", ":", "if", "self", ".", "cost_type", "==", "'evaluation_time'", ":", "cost_evals", "=", "np", ".", "log", "(", "np", ".", "atleast_2d", "(", "np", ".", "asarray", "(", "cost_x", ")", ")", ".", "T", ")", "if", "self", ".", "num_updates", "==", "0", ":", "X_all", "=", "x", "costs_all", "=", "cost_evals", "else", ":", "X_all", "=", "np", ".", "vstack", "(", "(", "self", ".", "cost_model", ".", "model", ".", "X", ",", "x", ")", ")", "costs_all", "=", "np", ".", "vstack", "(", "(", "self", ".", "cost_model", ".", "model", ".", "Y", ",", "cost_evals", ")", ")", "self", ".", "num_updates", "+=", "1", "self", ".", "cost_model", ".", "updateModel", "(", "X_all", ",", "costs_all", ",", "None", ",", "None", ")" ]
Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations.
[ "Updates", "the", "GP", "used", "to", "handle", "the", "cost", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/cost.py#L55-L74
228,179
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
AcquisitionLP.update_batches
def update_batches(self, X_batch, L, Min): """ Updates the batches internally and pre-computes the """ self.X_batch = X_batch if X_batch is not None: self.r_x0, self.s_x0 = self._hammer_function_precompute(X_batch, L, Min, self.model)
python
def update_batches(self, X_batch, L, Min): """ Updates the batches internally and pre-computes the """ self.X_batch = X_batch if X_batch is not None: self.r_x0, self.s_x0 = self._hammer_function_precompute(X_batch, L, Min, self.model)
[ "def", "update_batches", "(", "self", ",", "X_batch", ",", "L", ",", "Min", ")", ":", "self", ".", "X_batch", "=", "X_batch", "if", "X_batch", "is", "not", "None", ":", "self", ".", "r_x0", ",", "self", ".", "s_x0", "=", "self", ".", "_hammer_function_precompute", "(", "X_batch", ",", "L", ",", "Min", ",", "self", ".", "model", ")" ]
Updates the batches internally and pre-computes the
[ "Updates", "the", "batches", "internally", "and", "pre", "-", "computes", "the" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L40-L46
228,180
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
AcquisitionLP._hammer_function_precompute
def _hammer_function_precompute(self,x0, L, Min, model): """ Pre-computes the parameters of a penalizer centered at x0. """ if x0 is None: return None, None if len(x0.shape)==1: x0 = x0[None,:] m = model.predict(x0)[0] pred = model.predict(x0)[1].copy() pred[pred<1e-16] = 1e-16 s = np.sqrt(pred) r_x0 = (m-Min)/L s_x0 = s/L r_x0 = r_x0.flatten() s_x0 = s_x0.flatten() return r_x0, s_x0
python
def _hammer_function_precompute(self,x0, L, Min, model): """ Pre-computes the parameters of a penalizer centered at x0. """ if x0 is None: return None, None if len(x0.shape)==1: x0 = x0[None,:] m = model.predict(x0)[0] pred = model.predict(x0)[1].copy() pred[pred<1e-16] = 1e-16 s = np.sqrt(pred) r_x0 = (m-Min)/L s_x0 = s/L r_x0 = r_x0.flatten() s_x0 = s_x0.flatten() return r_x0, s_x0
[ "def", "_hammer_function_precompute", "(", "self", ",", "x0", ",", "L", ",", "Min", ",", "model", ")", ":", "if", "x0", "is", "None", ":", "return", "None", ",", "None", "if", "len", "(", "x0", ".", "shape", ")", "==", "1", ":", "x0", "=", "x0", "[", "None", ",", ":", "]", "m", "=", "model", ".", "predict", "(", "x0", ")", "[", "0", "]", "pred", "=", "model", ".", "predict", "(", "x0", ")", "[", "1", "]", ".", "copy", "(", ")", "pred", "[", "pred", "<", "1e-16", "]", "=", "1e-16", "s", "=", "np", ".", "sqrt", "(", "pred", ")", "r_x0", "=", "(", "m", "-", "Min", ")", "/", "L", "s_x0", "=", "s", "/", "L", "r_x0", "=", "r_x0", ".", "flatten", "(", ")", "s_x0", "=", "s_x0", ".", "flatten", "(", ")", "return", "r_x0", ",", "s_x0" ]
Pre-computes the parameters of a penalizer centered at x0.
[ "Pre", "-", "computes", "the", "parameters", "of", "a", "penalizer", "centered", "at", "x0", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L48-L62
228,181
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
AcquisitionLP._hammer_function
def _hammer_function(self, x,x0,r_x0, s_x0): ''' Creates the function to define the exclusion zones ''' return norm.logcdf((np.sqrt((np.square(np.atleast_2d(x)[:,None,:]-np.atleast_2d(x0)[None,:,:])).sum(-1))- r_x0)/s_x0)
python
def _hammer_function(self, x,x0,r_x0, s_x0): ''' Creates the function to define the exclusion zones ''' return norm.logcdf((np.sqrt((np.square(np.atleast_2d(x)[:,None,:]-np.atleast_2d(x0)[None,:,:])).sum(-1))- r_x0)/s_x0)
[ "def", "_hammer_function", "(", "self", ",", "x", ",", "x0", ",", "r_x0", ",", "s_x0", ")", ":", "return", "norm", ".", "logcdf", "(", "(", "np", ".", "sqrt", "(", "(", "np", ".", "square", "(", "np", ".", "atleast_2d", "(", "x", ")", "[", ":", ",", "None", ",", ":", "]", "-", "np", ".", "atleast_2d", "(", "x0", ")", "[", "None", ",", ":", ",", ":", "]", ")", ")", ".", "sum", "(", "-", "1", ")", ")", "-", "r_x0", ")", "/", "s_x0", ")" ]
Creates the function to define the exclusion zones
[ "Creates", "the", "function", "to", "define", "the", "exclusion", "zones" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L64-L68
228,182
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
AcquisitionLP._penalized_acquisition
def _penalized_acquisition(self, x, model, X_batch, r_x0, s_x0): ''' Creates a penalized acquisition function using 'hammer' functions around the points collected in the batch .. Note:: the penalized acquisition is always mapped to the log space. This way gradients can be computed additively and are more stable. ''' fval = -self.acq.acquisition_function(x)[:,0] if self.transform=='softplus': fval_org = fval.copy() fval[fval_org>=40.] = np.log(fval_org[fval_org>=40.]) fval[fval_org<40.] = np.log(np.log1p(np.exp(fval_org[fval_org<40.]))) elif self.transform=='none': fval = np.log(fval+1e-50) fval = -fval if X_batch is not None: h_vals = self._hammer_function(x, X_batch, r_x0, s_x0) fval += -h_vals.sum(axis=-1) return fval
python
def _penalized_acquisition(self, x, model, X_batch, r_x0, s_x0): ''' Creates a penalized acquisition function using 'hammer' functions around the points collected in the batch .. Note:: the penalized acquisition is always mapped to the log space. This way gradients can be computed additively and are more stable. ''' fval = -self.acq.acquisition_function(x)[:,0] if self.transform=='softplus': fval_org = fval.copy() fval[fval_org>=40.] = np.log(fval_org[fval_org>=40.]) fval[fval_org<40.] = np.log(np.log1p(np.exp(fval_org[fval_org<40.]))) elif self.transform=='none': fval = np.log(fval+1e-50) fval = -fval if X_batch is not None: h_vals = self._hammer_function(x, X_batch, r_x0, s_x0) fval += -h_vals.sum(axis=-1) return fval
[ "def", "_penalized_acquisition", "(", "self", ",", "x", ",", "model", ",", "X_batch", ",", "r_x0", ",", "s_x0", ")", ":", "fval", "=", "-", "self", ".", "acq", ".", "acquisition_function", "(", "x", ")", "[", ":", ",", "0", "]", "if", "self", ".", "transform", "==", "'softplus'", ":", "fval_org", "=", "fval", ".", "copy", "(", ")", "fval", "[", "fval_org", ">=", "40.", "]", "=", "np", ".", "log", "(", "fval_org", "[", "fval_org", ">=", "40.", "]", ")", "fval", "[", "fval_org", "<", "40.", "]", "=", "np", ".", "log", "(", "np", ".", "log1p", "(", "np", ".", "exp", "(", "fval_org", "[", "fval_org", "<", "40.", "]", ")", ")", ")", "elif", "self", ".", "transform", "==", "'none'", ":", "fval", "=", "np", ".", "log", "(", "fval", "+", "1e-50", ")", "fval", "=", "-", "fval", "if", "X_batch", "is", "not", "None", ":", "h_vals", "=", "self", ".", "_hammer_function", "(", "x", ",", "X_batch", ",", "r_x0", ",", "s_x0", ")", "fval", "+=", "-", "h_vals", ".", "sum", "(", "axis", "=", "-", "1", ")", "return", "fval" ]
Creates a penalized acquisition function using 'hammer' functions around the points collected in the batch .. Note:: the penalized acquisition is always mapped to the log space. This way gradients can be computed additively and are more stable.
[ "Creates", "a", "penalized", "acquisition", "function", "using", "hammer", "functions", "around", "the", "points", "collected", "in", "the", "batch" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L70-L89
228,183
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
AcquisitionLP.acquisition_function
def acquisition_function(self, x): """ Returns the value of the acquisition function at x. """ return self._penalized_acquisition(x, self.model, self.X_batch, self.r_x0, self.s_x0)
python
def acquisition_function(self, x): """ Returns the value of the acquisition function at x. """ return self._penalized_acquisition(x, self.model, self.X_batch, self.r_x0, self.s_x0)
[ "def", "acquisition_function", "(", "self", ",", "x", ")", ":", "return", "self", ".", "_penalized_acquisition", "(", "x", ",", "self", ".", "model", ",", "self", ".", "X_batch", ",", "self", ".", "r_x0", ",", "self", ".", "s_x0", ")" ]
Returns the value of the acquisition function at x.
[ "Returns", "the", "value", "of", "the", "acquisition", "function", "at", "x", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L105-L110
228,184
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
AcquisitionLP.d_acquisition_function
def d_acquisition_function(self, x): """ Returns the gradient of the acquisition function at x. """ x = np.atleast_2d(x) if self.transform=='softplus': fval = -self.acq.acquisition_function(x)[:,0] scale = 1./(np.log1p(np.exp(fval))*(1.+np.exp(-fval))) elif self.transform=='none': fval = -self.acq.acquisition_function(x)[:,0] scale = 1./fval else: scale = 1. if self.X_batch is None: _, grad_acq_x = self.acq.acquisition_function_withGradients(x) return scale*grad_acq_x else: _, grad_acq_x = self.acq.acquisition_function_withGradients(x) return scale*grad_acq_x - self._d_hammer_function(x, self.X_batch, self.r_x0, self.s_x0)
python
def d_acquisition_function(self, x): """ Returns the gradient of the acquisition function at x. """ x = np.atleast_2d(x) if self.transform=='softplus': fval = -self.acq.acquisition_function(x)[:,0] scale = 1./(np.log1p(np.exp(fval))*(1.+np.exp(-fval))) elif self.transform=='none': fval = -self.acq.acquisition_function(x)[:,0] scale = 1./fval else: scale = 1. if self.X_batch is None: _, grad_acq_x = self.acq.acquisition_function_withGradients(x) return scale*grad_acq_x else: _, grad_acq_x = self.acq.acquisition_function_withGradients(x) return scale*grad_acq_x - self._d_hammer_function(x, self.X_batch, self.r_x0, self.s_x0)
[ "def", "d_acquisition_function", "(", "self", ",", "x", ")", ":", "x", "=", "np", ".", "atleast_2d", "(", "x", ")", "if", "self", ".", "transform", "==", "'softplus'", ":", "fval", "=", "-", "self", ".", "acq", ".", "acquisition_function", "(", "x", ")", "[", ":", ",", "0", "]", "scale", "=", "1.", "/", "(", "np", ".", "log1p", "(", "np", ".", "exp", "(", "fval", ")", ")", "*", "(", "1.", "+", "np", ".", "exp", "(", "-", "fval", ")", ")", ")", "elif", "self", ".", "transform", "==", "'none'", ":", "fval", "=", "-", "self", ".", "acq", ".", "acquisition_function", "(", "x", ")", "[", ":", ",", "0", "]", "scale", "=", "1.", "/", "fval", "else", ":", "scale", "=", "1.", "if", "self", ".", "X_batch", "is", "None", ":", "_", ",", "grad_acq_x", "=", "self", ".", "acq", ".", "acquisition_function_withGradients", "(", "x", ")", "return", "scale", "*", "grad_acq_x", "else", ":", "_", ",", "grad_acq_x", "=", "self", ".", "acq", ".", "acquisition_function_withGradients", "(", "x", ")", "return", "scale", "*", "grad_acq_x", "-", "self", ".", "_d_hammer_function", "(", "x", ",", "self", ".", "X_batch", ",", "self", ".", "r_x0", ",", "self", ".", "s_x0", ")" ]
Returns the gradient of the acquisition function at x.
[ "Returns", "the", "gradient", "of", "the", "acquisition", "function", "at", "x", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L112-L132
228,185
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
AcquisitionLP.acquisition_function_withGradients
def acquisition_function_withGradients(self, x): """ Returns the acquisition function and its its gradient at x. """ aqu_x = self.acquisition_function(x) aqu_x_grad = self.d_acquisition_function(x) return aqu_x, aqu_x_grad
python
def acquisition_function_withGradients(self, x): """ Returns the acquisition function and its its gradient at x. """ aqu_x = self.acquisition_function(x) aqu_x_grad = self.d_acquisition_function(x) return aqu_x, aqu_x_grad
[ "def", "acquisition_function_withGradients", "(", "self", ",", "x", ")", ":", "aqu_x", "=", "self", ".", "acquisition_function", "(", "x", ")", "aqu_x_grad", "=", "self", ".", "d_acquisition_function", "(", "x", ")", "return", "aqu_x", ",", "aqu_x_grad" ]
Returns the acquisition function and its its gradient at x.
[ "Returns", "the", "acquisition", "function", "and", "its", "its", "gradient", "at", "x", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L134-L140
228,186
SheffieldML/GPyOpt
GPyOpt/acquisitions/base.py
AcquisitionBase.acquisition_function
def acquisition_function(self,x): """ Takes an acquisition and weights it so the domain and cost are taken into account. """ f_acqu = self._compute_acq(x) cost_x, _ = self.cost_withGradients(x) return -(f_acqu*self.space.indicator_constraints(x))/cost_x
python
def acquisition_function(self,x): """ Takes an acquisition and weights it so the domain and cost are taken into account. """ f_acqu = self._compute_acq(x) cost_x, _ = self.cost_withGradients(x) return -(f_acqu*self.space.indicator_constraints(x))/cost_x
[ "def", "acquisition_function", "(", "self", ",", "x", ")", ":", "f_acqu", "=", "self", ".", "_compute_acq", "(", "x", ")", "cost_x", ",", "_", "=", "self", ".", "cost_withGradients", "(", "x", ")", "return", "-", "(", "f_acqu", "*", "self", ".", "space", ".", "indicator_constraints", "(", "x", ")", ")", "/", "cost_x" ]
Takes an acquisition and weights it so the domain and cost are taken into account.
[ "Takes", "an", "acquisition", "and", "weights", "it", "so", "the", "domain", "and", "cost", "are", "taken", "into", "account", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/base.py#L33-L39
228,187
SheffieldML/GPyOpt
GPyOpt/acquisitions/base.py
AcquisitionBase.acquisition_function_withGradients
def acquisition_function_withGradients(self, x): """ Takes an acquisition and it gradient and weights it so the domain and cost are taken into account. """ f_acqu,df_acqu = self._compute_acq_withGradients(x) cost_x, cost_grad_x = self.cost_withGradients(x) f_acq_cost = f_acqu/cost_x df_acq_cost = (df_acqu*cost_x - f_acqu*cost_grad_x)/(cost_x**2) return -f_acq_cost*self.space.indicator_constraints(x), -df_acq_cost*self.space.indicator_constraints(x)
python
def acquisition_function_withGradients(self, x): """ Takes an acquisition and it gradient and weights it so the domain and cost are taken into account. """ f_acqu,df_acqu = self._compute_acq_withGradients(x) cost_x, cost_grad_x = self.cost_withGradients(x) f_acq_cost = f_acqu/cost_x df_acq_cost = (df_acqu*cost_x - f_acqu*cost_grad_x)/(cost_x**2) return -f_acq_cost*self.space.indicator_constraints(x), -df_acq_cost*self.space.indicator_constraints(x)
[ "def", "acquisition_function_withGradients", "(", "self", ",", "x", ")", ":", "f_acqu", ",", "df_acqu", "=", "self", ".", "_compute_acq_withGradients", "(", "x", ")", "cost_x", ",", "cost_grad_x", "=", "self", ".", "cost_withGradients", "(", "x", ")", "f_acq_cost", "=", "f_acqu", "/", "cost_x", "df_acq_cost", "=", "(", "df_acqu", "*", "cost_x", "-", "f_acqu", "*", "cost_grad_x", ")", "/", "(", "cost_x", "**", "2", ")", "return", "-", "f_acq_cost", "*", "self", ".", "space", ".", "indicator_constraints", "(", "x", ")", ",", "-", "df_acq_cost", "*", "self", ".", "space", ".", "indicator_constraints", "(", "x", ")" ]
Takes an acquisition and it gradient and weights it so the domain and cost are taken into account.
[ "Takes", "an", "acquisition", "and", "it", "gradient", "and", "weights", "it", "so", "the", "domain", "and", "cost", "are", "taken", "into", "account", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/base.py#L42-L50
228,188
SheffieldML/GPyOpt
GPyOpt/util/general.py
reshape
def reshape(x,input_dim): ''' Reshapes x into a matrix with input_dim columns ''' x = np.array(x) if x.size ==input_dim: x = x.reshape((1,input_dim)) return x
python
def reshape(x,input_dim): ''' Reshapes x into a matrix with input_dim columns ''' x = np.array(x) if x.size ==input_dim: x = x.reshape((1,input_dim)) return x
[ "def", "reshape", "(", "x", ",", "input_dim", ")", ":", "x", "=", "np", ".", "array", "(", "x", ")", "if", "x", ".", "size", "==", "input_dim", ":", "x", "=", "x", ".", "reshape", "(", "(", "1", ",", "input_dim", ")", ")", "return", "x" ]
Reshapes x into a matrix with input_dim columns
[ "Reshapes", "x", "into", "a", "matrix", "with", "input_dim", "columns" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L76-L84
228,189
SheffieldML/GPyOpt
GPyOpt/util/general.py
spawn
def spawn(f): ''' Function for parallel evaluation of the acquisition function ''' def fun(pipe,x): pipe.send(f(x)) pipe.close() return fun
python
def spawn(f): ''' Function for parallel evaluation of the acquisition function ''' def fun(pipe,x): pipe.send(f(x)) pipe.close() return fun
[ "def", "spawn", "(", "f", ")", ":", "def", "fun", "(", "pipe", ",", "x", ")", ":", "pipe", ".", "send", "(", "f", "(", "x", ")", ")", "pipe", ".", "close", "(", ")", "return", "fun" ]
Function for parallel evaluation of the acquisition function
[ "Function", "for", "parallel", "evaluation", "of", "the", "acquisition", "function" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L144-L151
228,190
SheffieldML/GPyOpt
GPyOpt/util/general.py
values_to_array
def values_to_array(input_values): ''' Transforms a values of int, float and tuples to a column vector numpy array ''' if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) elif type(input_values)==int or type(input_values)==float or type(np.int64): values = np.atleast_2d(np.array(input_values)) else: print('Type to transform not recognized') return values
python
def values_to_array(input_values): ''' Transforms a values of int, float and tuples to a column vector numpy array ''' if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) elif type(input_values)==int or type(input_values)==float or type(np.int64): values = np.atleast_2d(np.array(input_values)) else: print('Type to transform not recognized') return values
[ "def", "values_to_array", "(", "input_values", ")", ":", "if", "type", "(", "input_values", ")", "==", "tuple", ":", "values", "=", "np", ".", "array", "(", "input_values", ")", ".", "reshape", "(", "-", "1", ",", "1", ")", "elif", "type", "(", "input_values", ")", "==", "np", ".", "ndarray", ":", "values", "=", "np", ".", "atleast_2d", "(", "input_values", ")", "elif", "type", "(", "input_values", ")", "==", "int", "or", "type", "(", "input_values", ")", "==", "float", "or", "type", "(", "np", ".", "int64", ")", ":", "values", "=", "np", ".", "atleast_2d", "(", "np", ".", "array", "(", "input_values", ")", ")", "else", ":", "print", "(", "'Type to transform not recognized'", ")", "return", "values" ]
Transforms a values of int, float and tuples to a column vector numpy array
[ "Transforms", "a", "values", "of", "int", "float", "and", "tuples", "to", "a", "column", "vector", "numpy", "array" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L168-L180
228,191
SheffieldML/GPyOpt
GPyOpt/util/general.py
merge_values
def merge_values(values1,values2): ''' Merges two numpy arrays by calculating all possible combinations of rows ''' array1 = values_to_array(values1) array2 = values_to_array(values2) if array1.size == 0: return array2 if array2.size == 0: return array1 merged_array = [] for row_array1 in array1: for row_array2 in array2: merged_row = np.hstack((row_array1,row_array2)) merged_array.append(merged_row) return np.atleast_2d(merged_array)
python
def merge_values(values1,values2): ''' Merges two numpy arrays by calculating all possible combinations of rows ''' array1 = values_to_array(values1) array2 = values_to_array(values2) if array1.size == 0: return array2 if array2.size == 0: return array1 merged_array = [] for row_array1 in array1: for row_array2 in array2: merged_row = np.hstack((row_array1,row_array2)) merged_array.append(merged_row) return np.atleast_2d(merged_array)
[ "def", "merge_values", "(", "values1", ",", "values2", ")", ":", "array1", "=", "values_to_array", "(", "values1", ")", "array2", "=", "values_to_array", "(", "values2", ")", "if", "array1", ".", "size", "==", "0", ":", "return", "array2", "if", "array2", ".", "size", "==", "0", ":", "return", "array1", "merged_array", "=", "[", "]", "for", "row_array1", "in", "array1", ":", "for", "row_array2", "in", "array2", ":", "merged_row", "=", "np", ".", "hstack", "(", "(", "row_array1", ",", "row_array2", ")", ")", "merged_array", ".", "append", "(", "merged_row", ")", "return", "np", ".", "atleast_2d", "(", "merged_array", ")" ]
Merges two numpy arrays by calculating all possible combinations of rows
[ "Merges", "two", "numpy", "arrays", "by", "calculating", "all", "possible", "combinations", "of", "rows" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L183-L200
228,192
SheffieldML/GPyOpt
GPyOpt/util/general.py
normalize
def normalize(Y, normalization_type='stats'): """Normalize the vector Y using statistics or its range. :param Y: Row or column vector that you want to normalize. :param normalization_type: String specifying the kind of normalization to use. Options are 'stats' to use mean and standard deviation, or 'maxmin' to use the range of function values. :return Y_normalized: The normalized vector. """ Y = np.asarray(Y, dtype=float) if np.max(Y.shape) != Y.size: raise NotImplementedError('Only 1-dimensional arrays are supported.') # Only normalize with non null sdev (divide by zero). For only one # data point both std and ptp return 0. if normalization_type == 'stats': Y_norm = Y - Y.mean() std = Y.std() if std > 0: Y_norm /= std elif normalization_type == 'maxmin': Y_norm = Y - Y.min() y_range = np.ptp(Y) if y_range > 0: Y_norm /= y_range # A range of [-1, 1] is more natural for a zero-mean GP Y_norm = 2 * (Y_norm - 0.5) else: raise ValueError('Unknown normalization type: {}'.format(normalization_type)) return Y_norm
python
def normalize(Y, normalization_type='stats'): """Normalize the vector Y using statistics or its range. :param Y: Row or column vector that you want to normalize. :param normalization_type: String specifying the kind of normalization to use. Options are 'stats' to use mean and standard deviation, or 'maxmin' to use the range of function values. :return Y_normalized: The normalized vector. """ Y = np.asarray(Y, dtype=float) if np.max(Y.shape) != Y.size: raise NotImplementedError('Only 1-dimensional arrays are supported.') # Only normalize with non null sdev (divide by zero). For only one # data point both std and ptp return 0. if normalization_type == 'stats': Y_norm = Y - Y.mean() std = Y.std() if std > 0: Y_norm /= std elif normalization_type == 'maxmin': Y_norm = Y - Y.min() y_range = np.ptp(Y) if y_range > 0: Y_norm /= y_range # A range of [-1, 1] is more natural for a zero-mean GP Y_norm = 2 * (Y_norm - 0.5) else: raise ValueError('Unknown normalization type: {}'.format(normalization_type)) return Y_norm
[ "def", "normalize", "(", "Y", ",", "normalization_type", "=", "'stats'", ")", ":", "Y", "=", "np", ".", "asarray", "(", "Y", ",", "dtype", "=", "float", ")", "if", "np", ".", "max", "(", "Y", ".", "shape", ")", "!=", "Y", ".", "size", ":", "raise", "NotImplementedError", "(", "'Only 1-dimensional arrays are supported.'", ")", "# Only normalize with non null sdev (divide by zero). For only one", "# data point both std and ptp return 0.", "if", "normalization_type", "==", "'stats'", ":", "Y_norm", "=", "Y", "-", "Y", ".", "mean", "(", ")", "std", "=", "Y", ".", "std", "(", ")", "if", "std", ">", "0", ":", "Y_norm", "/=", "std", "elif", "normalization_type", "==", "'maxmin'", ":", "Y_norm", "=", "Y", "-", "Y", ".", "min", "(", ")", "y_range", "=", "np", ".", "ptp", "(", "Y", ")", "if", "y_range", ">", "0", ":", "Y_norm", "/=", "y_range", "# A range of [-1, 1] is more natural for a zero-mean GP", "Y_norm", "=", "2", "*", "(", "Y_norm", "-", "0.5", ")", "else", ":", "raise", "ValueError", "(", "'Unknown normalization type: {}'", ".", "format", "(", "normalization_type", ")", ")", "return", "Y_norm" ]
Normalize the vector Y using statistics or its range. :param Y: Row or column vector that you want to normalize. :param normalization_type: String specifying the kind of normalization to use. Options are 'stats' to use mean and standard deviation, or 'maxmin' to use the range of function values. :return Y_normalized: The normalized vector.
[ "Normalize", "the", "vector", "Y", "using", "statistics", "or", "its", "range", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L203-L234
228,193
SheffieldML/GPyOpt
GPyOpt/experiment_design/grid_design.py
GridDesign.get_samples
def get_samples(self, init_points_count): """ This method may return less points than requested. The total number of generated points is the smallest closest integer of n^d to the selected amount of points. """ init_points_count = self._adjust_init_points_count(init_points_count) samples = np.empty((init_points_count, self.space.dimensionality)) # Use random design to fill non-continuous variables random_design = RandomDesign(self.space) random_design.fill_noncontinous_variables(samples) if self.space.has_continuous(): X_design = multigrid(self.space.get_continuous_bounds(), self.data_per_dimension) samples[:,self.space.get_continuous_dims()] = X_design return samples
python
def get_samples(self, init_points_count): """ This method may return less points than requested. The total number of generated points is the smallest closest integer of n^d to the selected amount of points. """ init_points_count = self._adjust_init_points_count(init_points_count) samples = np.empty((init_points_count, self.space.dimensionality)) # Use random design to fill non-continuous variables random_design = RandomDesign(self.space) random_design.fill_noncontinous_variables(samples) if self.space.has_continuous(): X_design = multigrid(self.space.get_continuous_bounds(), self.data_per_dimension) samples[:,self.space.get_continuous_dims()] = X_design return samples
[ "def", "get_samples", "(", "self", ",", "init_points_count", ")", ":", "init_points_count", "=", "self", ".", "_adjust_init_points_count", "(", "init_points_count", ")", "samples", "=", "np", ".", "empty", "(", "(", "init_points_count", ",", "self", ".", "space", ".", "dimensionality", ")", ")", "# Use random design to fill non-continuous variables", "random_design", "=", "RandomDesign", "(", "self", ".", "space", ")", "random_design", ".", "fill_noncontinous_variables", "(", "samples", ")", "if", "self", ".", "space", ".", "has_continuous", "(", ")", ":", "X_design", "=", "multigrid", "(", "self", ".", "space", ".", "get_continuous_bounds", "(", ")", ",", "self", ".", "data_per_dimension", ")", "samples", "[", ":", ",", "self", ".", "space", ".", "get_continuous_dims", "(", ")", "]", "=", "X_design", "return", "samples" ]
This method may return less points than requested. The total number of generated points is the smallest closest integer of n^d to the selected amount of points.
[ "This", "method", "may", "return", "less", "points", "than", "requested", ".", "The", "total", "number", "of", "generated", "points", "is", "the", "smallest", "closest", "integer", "of", "n^d", "to", "the", "selected", "amount", "of", "points", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/experiment_design/grid_design.py#L26-L43
228,194
SheffieldML/GPyOpt
GPyOpt/experiment_design/random_design.py
RandomDesign.get_samples_with_constraints
def get_samples_with_constraints(self, init_points_count): """ Draw random samples and only save those that satisfy constraints Finish when required number of samples is generated """ samples = np.empty((0, self.space.dimensionality)) while samples.shape[0] < init_points_count: domain_samples = self.get_samples_without_constraints(init_points_count) valid_indices = (self.space.indicator_constraints(domain_samples) == 1).flatten() if sum(valid_indices) > 0: valid_samples = domain_samples[valid_indices,:] samples = np.vstack((samples,valid_samples)) return samples[0:init_points_count,:]
python
def get_samples_with_constraints(self, init_points_count): """ Draw random samples and only save those that satisfy constraints Finish when required number of samples is generated """ samples = np.empty((0, self.space.dimensionality)) while samples.shape[0] < init_points_count: domain_samples = self.get_samples_without_constraints(init_points_count) valid_indices = (self.space.indicator_constraints(domain_samples) == 1).flatten() if sum(valid_indices) > 0: valid_samples = domain_samples[valid_indices,:] samples = np.vstack((samples,valid_samples)) return samples[0:init_points_count,:]
[ "def", "get_samples_with_constraints", "(", "self", ",", "init_points_count", ")", ":", "samples", "=", "np", ".", "empty", "(", "(", "0", ",", "self", ".", "space", ".", "dimensionality", ")", ")", "while", "samples", ".", "shape", "[", "0", "]", "<", "init_points_count", ":", "domain_samples", "=", "self", ".", "get_samples_without_constraints", "(", "init_points_count", ")", "valid_indices", "=", "(", "self", ".", "space", ".", "indicator_constraints", "(", "domain_samples", ")", "==", "1", ")", ".", "flatten", "(", ")", "if", "sum", "(", "valid_indices", ")", ">", "0", ":", "valid_samples", "=", "domain_samples", "[", "valid_indices", ",", ":", "]", "samples", "=", "np", ".", "vstack", "(", "(", "samples", ",", "valid_samples", ")", ")", "return", "samples", "[", "0", ":", "init_points_count", ",", ":", "]" ]
Draw random samples and only save those that satisfy constraints Finish when required number of samples is generated
[ "Draw", "random", "samples", "and", "only", "save", "those", "that", "satisfy", "constraints", "Finish", "when", "required", "number", "of", "samples", "is", "generated" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/experiment_design/random_design.py#L21-L35
228,195
SheffieldML/GPyOpt
GPyOpt/experiment_design/random_design.py
RandomDesign.fill_noncontinous_variables
def fill_noncontinous_variables(self, samples): """ Fill sample values to non-continuous variables in place """ init_points_count = samples.shape[0] for (idx, var) in enumerate(self.space.space_expanded): if isinstance(var, DiscreteVariable) or isinstance(var, CategoricalVariable) : sample_var = np.atleast_2d(np.random.choice(var.domain, init_points_count)) samples[:,idx] = sample_var.flatten() # sample in the case of bandit variables elif isinstance(var, BanditVariable): # Bandit variable is represented by a several adjacent columns in the samples array idx_samples = np.random.randint(var.domain.shape[0], size=init_points_count) bandit_idx = np.arange(idx, idx + var.domain.shape[1]) samples[:, bandit_idx] = var.domain[idx_samples,:]
python
def fill_noncontinous_variables(self, samples): """ Fill sample values to non-continuous variables in place """ init_points_count = samples.shape[0] for (idx, var) in enumerate(self.space.space_expanded): if isinstance(var, DiscreteVariable) or isinstance(var, CategoricalVariable) : sample_var = np.atleast_2d(np.random.choice(var.domain, init_points_count)) samples[:,idx] = sample_var.flatten() # sample in the case of bandit variables elif isinstance(var, BanditVariable): # Bandit variable is represented by a several adjacent columns in the samples array idx_samples = np.random.randint(var.domain.shape[0], size=init_points_count) bandit_idx = np.arange(idx, idx + var.domain.shape[1]) samples[:, bandit_idx] = var.domain[idx_samples,:]
[ "def", "fill_noncontinous_variables", "(", "self", ",", "samples", ")", ":", "init_points_count", "=", "samples", ".", "shape", "[", "0", "]", "for", "(", "idx", ",", "var", ")", "in", "enumerate", "(", "self", ".", "space", ".", "space_expanded", ")", ":", "if", "isinstance", "(", "var", ",", "DiscreteVariable", ")", "or", "isinstance", "(", "var", ",", "CategoricalVariable", ")", ":", "sample_var", "=", "np", ".", "atleast_2d", "(", "np", ".", "random", ".", "choice", "(", "var", ".", "domain", ",", "init_points_count", ")", ")", "samples", "[", ":", ",", "idx", "]", "=", "sample_var", ".", "flatten", "(", ")", "# sample in the case of bandit variables", "elif", "isinstance", "(", "var", ",", "BanditVariable", ")", ":", "# Bandit variable is represented by a several adjacent columns in the samples array", "idx_samples", "=", "np", ".", "random", ".", "randint", "(", "var", ".", "domain", ".", "shape", "[", "0", "]", ",", "size", "=", "init_points_count", ")", "bandit_idx", "=", "np", ".", "arange", "(", "idx", ",", "idx", "+", "var", ".", "domain", ".", "shape", "[", "1", "]", ")", "samples", "[", ":", ",", "bandit_idx", "]", "=", "var", ".", "domain", "[", "idx_samples", ",", ":", "]" ]
Fill sample values to non-continuous variables in place
[ "Fill", "sample", "values", "to", "non", "-", "continuous", "variables", "in", "place" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/experiment_design/random_design.py#L37-L53
228,196
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._get_obj
def _get_obj(self,space): """ Imports the acquisition function. """ obj_func = self.obj_func from ..core.task import SingleObjective return SingleObjective(obj_func, self.config['resources']['cores'], space=space, unfold_args=True)
python
def _get_obj(self,space): """ Imports the acquisition function. """ obj_func = self.obj_func from ..core.task import SingleObjective return SingleObjective(obj_func, self.config['resources']['cores'], space=space, unfold_args=True)
[ "def", "_get_obj", "(", "self", ",", "space", ")", ":", "obj_func", "=", "self", ".", "obj_func", "from", ".", ".", "core", ".", "task", "import", "SingleObjective", "return", "SingleObjective", "(", "obj_func", ",", "self", ".", "config", "[", "'resources'", "]", "[", "'cores'", "]", ",", "space", "=", "space", ",", "unfold_args", "=", "True", ")" ]
Imports the acquisition function.
[ "Imports", "the", "acquisition", "function", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L24-L32
228,197
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._get_space
def _get_space(self): """ Imports the domain. """ assert 'space' in self.config, 'The search space is NOT configured!' space_config = self.config['space'] constraint_config = self.config['constraints'] from ..core.task.space import Design_space return Design_space.fromConfig(space_config, constraint_config)
python
def _get_space(self): """ Imports the domain. """ assert 'space' in self.config, 'The search space is NOT configured!' space_config = self.config['space'] constraint_config = self.config['constraints'] from ..core.task.space import Design_space return Design_space.fromConfig(space_config, constraint_config)
[ "def", "_get_space", "(", "self", ")", ":", "assert", "'space'", "in", "self", ".", "config", ",", "'The search space is NOT configured!'", "space_config", "=", "self", ".", "config", "[", "'space'", "]", "constraint_config", "=", "self", ".", "config", "[", "'constraints'", "]", "from", ".", ".", "core", ".", "task", ".", "space", "import", "Design_space", "return", "Design_space", ".", "fromConfig", "(", "space_config", ",", "constraint_config", ")" ]
Imports the domain.
[ "Imports", "the", "domain", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L34-L43
228,198
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._get_model
def _get_model(self): """ Imports the model. """ from copy import deepcopy model_args = deepcopy(self.config['model']) del model_args['type'] from ..models import select_model return select_model(self.config['model']['type']).fromConfig(model_args)
python
def _get_model(self): """ Imports the model. """ from copy import deepcopy model_args = deepcopy(self.config['model']) del model_args['type'] from ..models import select_model return select_model(self.config['model']['type']).fromConfig(model_args)
[ "def", "_get_model", "(", "self", ")", ":", "from", "copy", "import", "deepcopy", "model_args", "=", "deepcopy", "(", "self", ".", "config", "[", "'model'", "]", ")", "del", "model_args", "[", "'type'", "]", "from", ".", ".", "models", "import", "select_model", "return", "select_model", "(", "self", ".", "config", "[", "'model'", "]", "[", "'type'", "]", ")", ".", "fromConfig", "(", "model_args", ")" ]
Imports the model.
[ "Imports", "the", "model", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L45-L55
228,199
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._get_acquisition
def _get_acquisition(self, model, space): """ Imports the acquisition """ from copy import deepcopy acqOpt_config = deepcopy(self.config['acquisition']['optimizer']) acqOpt_name = acqOpt_config['name'] del acqOpt_config['name'] from ..optimization import AcquisitionOptimizer acqOpt = AcquisitionOptimizer(space, acqOpt_name, **acqOpt_config) from ..acquisitions import select_acquisition return select_acquisition(self.config['acquisition']['type']).fromConfig(model, space, acqOpt, None, self.config['acquisition'])
python
def _get_acquisition(self, model, space): """ Imports the acquisition """ from copy import deepcopy acqOpt_config = deepcopy(self.config['acquisition']['optimizer']) acqOpt_name = acqOpt_config['name'] del acqOpt_config['name'] from ..optimization import AcquisitionOptimizer acqOpt = AcquisitionOptimizer(space, acqOpt_name, **acqOpt_config) from ..acquisitions import select_acquisition return select_acquisition(self.config['acquisition']['type']).fromConfig(model, space, acqOpt, None, self.config['acquisition'])
[ "def", "_get_acquisition", "(", "self", ",", "model", ",", "space", ")", ":", "from", "copy", "import", "deepcopy", "acqOpt_config", "=", "deepcopy", "(", "self", ".", "config", "[", "'acquisition'", "]", "[", "'optimizer'", "]", ")", "acqOpt_name", "=", "acqOpt_config", "[", "'name'", "]", "del", "acqOpt_config", "[", "'name'", "]", "from", ".", ".", "optimization", "import", "AcquisitionOptimizer", "acqOpt", "=", "AcquisitionOptimizer", "(", "space", ",", "acqOpt_name", ",", "*", "*", "acqOpt_config", ")", "from", ".", ".", "acquisitions", "import", "select_acquisition", "return", "select_acquisition", "(", "self", ".", "config", "[", "'acquisition'", "]", "[", "'type'", "]", ")", ".", "fromConfig", "(", "model", ",", "space", ",", "acqOpt", ",", "None", ",", "self", ".", "config", "[", "'acquisition'", "]", ")" ]
Imports the acquisition
[ "Imports", "the", "acquisition" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L58-L71