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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
241,900 | sassoftware/saspy | saspy/sasbase.py | SASsession.exist | def exist(self, table: str, libref: str = "") -> bool:
"""
Does the SAS data set currently exist
:param table: the name of the SAS Data Set
:param libref: the libref for the Data Set, defaults to WORK, or USER if assigned
:return: Boolean True it the Data Set exists and False if it does not
:rtype: bool
"""
return self._io.exist(table, libref) | python | def exist(self, table: str, libref: str = "") -> bool:
return self._io.exist(table, libref) | [
"def",
"exist",
"(",
"self",
",",
"table",
":",
"str",
",",
"libref",
":",
"str",
"=",
"\"\"",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_io",
".",
"exist",
"(",
"table",
",",
"libref",
")"
] | Does the SAS data set currently exist
:param table: the name of the SAS Data Set
:param libref: the libref for the Data Set, defaults to WORK, or USER if assigned
:return: Boolean True it the Data Set exists and False if it does not
:rtype: bool | [
"Does",
"the",
"SAS",
"data",
"set",
"currently",
"exist"
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L540-L549 |
241,901 | sassoftware/saspy | saspy/sasbase.py | SASsession.sasstat | def sasstat(self) -> 'SASstat':
"""
This methods creates a SASstat object which you can use to run various analytics.
See the sasstat.py module.
:return: sasstat object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASstat(self) | python | def sasstat(self) -> 'SASstat':
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASstat(self) | [
"def",
"sasstat",
"(",
"self",
")",
"->",
"'SASstat'",
":",
"if",
"not",
"self",
".",
"_loaded_macros",
":",
"self",
".",
"_loadmacros",
"(",
")",
"self",
".",
"_loaded_macros",
"=",
"True",
"return",
"SASstat",
"(",
"self",
")"
] | This methods creates a SASstat object which you can use to run various analytics.
See the sasstat.py module.
:return: sasstat object | [
"This",
"methods",
"creates",
"a",
"SASstat",
"object",
"which",
"you",
"can",
"use",
"to",
"run",
"various",
"analytics",
".",
"See",
"the",
"sasstat",
".",
"py",
"module",
"."
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L562-L573 |
241,902 | sassoftware/saspy | saspy/sasbase.py | SASsession.sasml | def sasml(self) -> 'SASml':
"""
This methods creates a SASML object which you can use to run various analytics. See the sasml.py module.
:return: sasml object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASml(self) | python | def sasml(self) -> 'SASml':
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASml(self) | [
"def",
"sasml",
"(",
"self",
")",
"->",
"'SASml'",
":",
"if",
"not",
"self",
".",
"_loaded_macros",
":",
"self",
".",
"_loadmacros",
"(",
")",
"self",
".",
"_loaded_macros",
"=",
"True",
"return",
"SASml",
"(",
"self",
")"
] | This methods creates a SASML object which you can use to run various analytics. See the sasml.py module.
:return: sasml object | [
"This",
"methods",
"creates",
"a",
"SASML",
"object",
"which",
"you",
"can",
"use",
"to",
"run",
"various",
"analytics",
".",
"See",
"the",
"sasml",
".",
"py",
"module",
"."
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L575-L585 |
241,903 | sassoftware/saspy | saspy/sasbase.py | SASsession.sasqc | def sasqc(self) -> 'SASqc':
"""
This methods creates a SASqc object which you can use to run various analytics. See the sasqc.py module.
:return: sasqc object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASqc(self) | python | def sasqc(self) -> 'SASqc':
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASqc(self) | [
"def",
"sasqc",
"(",
"self",
")",
"->",
"'SASqc'",
":",
"if",
"not",
"self",
".",
"_loaded_macros",
":",
"self",
".",
"_loadmacros",
"(",
")",
"self",
".",
"_loaded_macros",
"=",
"True",
"return",
"SASqc",
"(",
"self",
")"
] | This methods creates a SASqc object which you can use to run various analytics. See the sasqc.py module.
:return: sasqc object | [
"This",
"methods",
"creates",
"a",
"SASqc",
"object",
"which",
"you",
"can",
"use",
"to",
"run",
"various",
"analytics",
".",
"See",
"the",
"sasqc",
".",
"py",
"module",
"."
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L587-L597 |
241,904 | sassoftware/saspy | saspy/sasbase.py | SASsession.sasutil | def sasutil(self) -> 'SASutil':
"""
This methods creates a SASutil object which you can use to run various analytics.
See the sasutil.py module.
:return: sasutil object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASutil(self) | python | def sasutil(self) -> 'SASutil':
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASutil(self) | [
"def",
"sasutil",
"(",
"self",
")",
"->",
"'SASutil'",
":",
"if",
"not",
"self",
".",
"_loaded_macros",
":",
"self",
".",
"_loadmacros",
"(",
")",
"self",
".",
"_loaded_macros",
"=",
"True",
"return",
"SASutil",
"(",
"self",
")"
] | This methods creates a SASutil object which you can use to run various analytics.
See the sasutil.py module.
:return: sasutil object | [
"This",
"methods",
"creates",
"a",
"SASutil",
"object",
"which",
"you",
"can",
"use",
"to",
"run",
"various",
"analytics",
".",
"See",
"the",
"sasutil",
".",
"py",
"module",
"."
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L599-L610 |
241,905 | sassoftware/saspy | saspy/sasbase.py | SASsession.sasviyaml | def sasviyaml(self) -> 'SASViyaML':
"""
This methods creates a SASViyaML object which you can use to run various analytics.
See the SASViyaML.py module.
:return: SASViyaML object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASViyaML(self) | python | def sasviyaml(self) -> 'SASViyaML':
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASViyaML(self) | [
"def",
"sasviyaml",
"(",
"self",
")",
"->",
"'SASViyaML'",
":",
"if",
"not",
"self",
".",
"_loaded_macros",
":",
"self",
".",
"_loadmacros",
"(",
")",
"self",
".",
"_loaded_macros",
"=",
"True",
"return",
"SASViyaML",
"(",
"self",
")"
] | This methods creates a SASViyaML object which you can use to run various analytics.
See the SASViyaML.py module.
:return: SASViyaML object | [
"This",
"methods",
"creates",
"a",
"SASViyaML",
"object",
"which",
"you",
"can",
"use",
"to",
"run",
"various",
"analytics",
".",
"See",
"the",
"SASViyaML",
".",
"py",
"module",
"."
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L612-L623 |
241,906 | sassoftware/saspy | saspy/sasbase.py | SASsession._loadmacros | def _loadmacros(self):
"""
Load the SAS macros at the start of the session
:return:
"""
macro_path = os.path.dirname(os.path.realpath(__file__))
fd = os.open(macro_path + '/' + 'libname_gen.sas', os.O_RDONLY)
code = b'options nosource;\n'
code += os.read(fd, 32767)
code += b'\noptions source;'
self._io._asubmit(code.decode(), results='text')
os.close(fd) | python | def _loadmacros(self):
macro_path = os.path.dirname(os.path.realpath(__file__))
fd = os.open(macro_path + '/' + 'libname_gen.sas', os.O_RDONLY)
code = b'options nosource;\n'
code += os.read(fd, 32767)
code += b'\noptions source;'
self._io._asubmit(code.decode(), results='text')
os.close(fd) | [
"def",
"_loadmacros",
"(",
"self",
")",
":",
"macro_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"fd",
"=",
"os",
".",
"open",
"(",
"macro_path",
"+",
"'/'",
"+",
"'libname_gen.sas... | Load the SAS macros at the start of the session
:return: | [
"Load",
"the",
"SAS",
"macros",
"at",
"the",
"start",
"of",
"the",
"session"
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L625-L638 |
241,907 | sassoftware/saspy | saspy/sasbase.py | SASsession.sasdata | def sasdata(self, table: str, libref: str = '', results: str = '', dsopts: dict = None) -> 'SASdata':
"""
Method to define an existing SAS dataset so that it can be accessed via SASPy
:param table: the name of the SAS Data Set
:param libref: the libref for the Data Set, defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, Pandas, HTML and TEXT are the valid options
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
- format is a string or dictionary { var: format }
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
'format' : {'money': 'dollar10', 'time': 'tod5.'}
}
:return: SASdata object
"""
dsopts = dsopts if dsopts is not None else {}
if results == '':
results = self.results
sd = SASdata(self, libref, table, results, dsopts)
if not self.exist(sd.table, sd.libref):
if not self.batch:
print(
"Table " + sd.libref + '.' + sd.table + " does not exist. This SASdata object will not be useful until the data set is created.")
return sd | python | def sasdata(self, table: str, libref: str = '', results: str = '', dsopts: dict = None) -> 'SASdata':
dsopts = dsopts if dsopts is not None else {}
if results == '':
results = self.results
sd = SASdata(self, libref, table, results, dsopts)
if not self.exist(sd.table, sd.libref):
if not self.batch:
print(
"Table " + sd.libref + '.' + sd.table + " does not exist. This SASdata object will not be useful until the data set is created.")
return sd | [
"def",
"sasdata",
"(",
"self",
",",
"table",
":",
"str",
",",
"libref",
":",
"str",
"=",
"''",
",",
"results",
":",
"str",
"=",
"''",
",",
"dsopts",
":",
"dict",
"=",
"None",
")",
"->",
"'SASdata'",
":",
"dsopts",
"=",
"dsopts",
"if",
"dsopts",
"... | Method to define an existing SAS dataset so that it can be accessed via SASPy
:param table: the name of the SAS Data Set
:param libref: the libref for the Data Set, defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, Pandas, HTML and TEXT are the valid options
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
- format is a string or dictionary { var: format }
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
'format' : {'money': 'dollar10', 'time': 'tod5.'}
}
:return: SASdata object | [
"Method",
"to",
"define",
"an",
"existing",
"SAS",
"dataset",
"so",
"that",
"it",
"can",
"be",
"accessed",
"via",
"SASPy"
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L640-L677 |
241,908 | sassoftware/saspy | saspy/sasbase.py | SASsession.datasets | def datasets(self, libref: str = '') -> str:
"""
This method is used to query a libref. The results show information about the libref including members.
:param libref: the libref to query
:return:
"""
code = "proc datasets"
if libref:
code += " dd=" + libref
code += "; quit;"
if self.nosub:
print(code)
else:
if self.results.lower() == 'html':
ll = self._io.submit(code, "html")
if not self.batch:
self.DISPLAY(self.HTML(ll['LST']))
else:
return ll
else:
ll = self._io.submit(code, "text")
if self.batch:
return ll['LOG'].rsplit(";*\';*\";*/;\n")[0]
else:
print(ll['LOG'].rsplit(";*\';*\";*/;\n")[0]) | python | def datasets(self, libref: str = '') -> str:
code = "proc datasets"
if libref:
code += " dd=" + libref
code += "; quit;"
if self.nosub:
print(code)
else:
if self.results.lower() == 'html':
ll = self._io.submit(code, "html")
if not self.batch:
self.DISPLAY(self.HTML(ll['LST']))
else:
return ll
else:
ll = self._io.submit(code, "text")
if self.batch:
return ll['LOG'].rsplit(";*\';*\";*/;\n")[0]
else:
print(ll['LOG'].rsplit(";*\';*\";*/;\n")[0]) | [
"def",
"datasets",
"(",
"self",
",",
"libref",
":",
"str",
"=",
"''",
")",
"->",
"str",
":",
"code",
"=",
"\"proc datasets\"",
"if",
"libref",
":",
"code",
"+=",
"\" dd=\"",
"+",
"libref",
"code",
"+=",
"\"; quit;\"",
"if",
"self",
".",
"nosub",
":",
... | This method is used to query a libref. The results show information about the libref including members.
:param libref: the libref to query
:return: | [
"This",
"method",
"is",
"used",
"to",
"query",
"a",
"libref",
".",
"The",
"results",
"show",
"information",
"about",
"the",
"libref",
"including",
"members",
"."
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L705-L731 |
241,909 | sassoftware/saspy | saspy/sasbase.py | SASsession.upload | def upload(self, localfile: str, remotefile: str, overwrite: bool = True, permission: str = '', **kwargs):
"""
This method uploads a local file to the SAS servers file system.
:param localfile: path to the local file
:param remotefile: path to remote file to create or overwrite
:param overwrite: overwrite the output file if it exists?
:param permission: permissions to set on the new file. See SAS Filename Statement Doc for syntax
:return: SAS Log
"""
if self.nosub:
print("too complicated to show the code, read the source :), sorry.")
return None
else:
log = self._io.upload(localfile, remotefile, overwrite, permission, **kwargs)
return log | python | def upload(self, localfile: str, remotefile: str, overwrite: bool = True, permission: str = '', **kwargs):
if self.nosub:
print("too complicated to show the code, read the source :), sorry.")
return None
else:
log = self._io.upload(localfile, remotefile, overwrite, permission, **kwargs)
return log | [
"def",
"upload",
"(",
"self",
",",
"localfile",
":",
"str",
",",
"remotefile",
":",
"str",
",",
"overwrite",
":",
"bool",
"=",
"True",
",",
"permission",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"nosub",
":",
"... | This method uploads a local file to the SAS servers file system.
:param localfile: path to the local file
:param remotefile: path to remote file to create or overwrite
:param overwrite: overwrite the output file if it exists?
:param permission: permissions to set on the new file. See SAS Filename Statement Doc for syntax
:return: SAS Log | [
"This",
"method",
"uploads",
"a",
"local",
"file",
"to",
"the",
"SAS",
"servers",
"file",
"system",
"."
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L792-L808 |
241,910 | sassoftware/saspy | saspy/sasbase.py | SASsession.df2sd | def df2sd(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '',
results: str = '', keep_outer_quotes: bool = False) -> 'SASdata':
"""
This is an alias for 'dataframe2sasdata'. Why type all that?
:param df: :class:`pandas.DataFrame` Pandas Data Frame to import to a SAS Data Set
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives
:param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them
:return: SASdata object
"""
return self.dataframe2sasdata(df, table, libref, results, keep_outer_quotes) | python | def df2sd(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '',
results: str = '', keep_outer_quotes: bool = False) -> 'SASdata':
return self.dataframe2sasdata(df, table, libref, results, keep_outer_quotes) | [
"def",
"df2sd",
"(",
"self",
",",
"df",
":",
"'pd.DataFrame'",
",",
"table",
":",
"str",
"=",
"'_df'",
",",
"libref",
":",
"str",
"=",
"''",
",",
"results",
":",
"str",
"=",
"''",
",",
"keep_outer_quotes",
":",
"bool",
"=",
"False",
")",
"->",
"'SA... | This is an alias for 'dataframe2sasdata'. Why type all that?
:param df: :class:`pandas.DataFrame` Pandas Data Frame to import to a SAS Data Set
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives
:param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them
:return: SASdata object | [
"This",
"is",
"an",
"alias",
"for",
"dataframe2sasdata",
".",
"Why",
"type",
"all",
"that?"
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L827-L839 |
241,911 | sassoftware/saspy | saspy/sasbase.py | SASsession.dataframe2sasdata | def dataframe2sasdata(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '',
results: str = '', keep_outer_quotes: bool = False) -> 'SASdata':
"""
This method imports a Pandas Data Frame to a SAS Data Set, returning the SASdata object for the new Data Set.
:param df: Pandas Data Frame to import to a SAS Data Set
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives
:param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them
:return: SASdata object
"""
if libref != '':
if libref.upper() not in self.assigned_librefs():
print("The libref specified is not assigned in this SAS Session.")
return None
if results == '':
results = self.results
if self.nosub:
print("too complicated to show the code, read the source :), sorry.")
return None
else:
self._io.dataframe2sasdata(df, table, libref, keep_outer_quotes)
if self.exist(table, libref):
return SASdata(self, libref, table, results)
else:
return None | python | def dataframe2sasdata(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '',
results: str = '', keep_outer_quotes: bool = False) -> 'SASdata':
if libref != '':
if libref.upper() not in self.assigned_librefs():
print("The libref specified is not assigned in this SAS Session.")
return None
if results == '':
results = self.results
if self.nosub:
print("too complicated to show the code, read the source :), sorry.")
return None
else:
self._io.dataframe2sasdata(df, table, libref, keep_outer_quotes)
if self.exist(table, libref):
return SASdata(self, libref, table, results)
else:
return None | [
"def",
"dataframe2sasdata",
"(",
"self",
",",
"df",
":",
"'pd.DataFrame'",
",",
"table",
":",
"str",
"=",
"'_df'",
",",
"libref",
":",
"str",
"=",
"''",
",",
"results",
":",
"str",
"=",
"''",
",",
"keep_outer_quotes",
":",
"bool",
"=",
"False",
")",
... | This method imports a Pandas Data Frame to a SAS Data Set, returning the SASdata object for the new Data Set.
:param df: Pandas Data Frame to import to a SAS Data Set
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives
:param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them
:return: SASdata object | [
"This",
"method",
"imports",
"a",
"Pandas",
"Data",
"Frame",
"to",
"a",
"SAS",
"Data",
"Set",
"returning",
"the",
"SASdata",
"object",
"for",
"the",
"new",
"Data",
"Set",
"."
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L841-L869 |
241,912 | sassoftware/saspy | saspy/sasbase.py | SASsession.sd2df | def sd2df(self, table: str, libref: str = '', dsopts: dict = None, method: str = 'MEMORY',
**kwargs) -> 'pd.DataFrame':
"""
This is an alias for 'sasdata2dataframe'. Why type all that?
SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame
:param table: the name of the SAS Data Set you want to export to a Pandas Data Frame
:param libref: the libref for the SAS Data Set.
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
- format is a string or dictionary { var: format }
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
'format' : {'money': 'dollar10', 'time': 'tod5.'}
}
: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: dictionary
:return: Pandas data frame
"""
dsopts = dsopts if dsopts is not None else {}
return self.sasdata2dataframe(table, libref, dsopts, method, **kwargs) | python | def sd2df(self, table: str, libref: str = '', dsopts: dict = None, method: str = 'MEMORY',
**kwargs) -> 'pd.DataFrame':
dsopts = dsopts if dsopts is not None else {}
return self.sasdata2dataframe(table, libref, dsopts, method, **kwargs) | [
"def",
"sd2df",
"(",
"self",
",",
"table",
":",
"str",
",",
"libref",
":",
"str",
"=",
"''",
",",
"dsopts",
":",
"dict",
"=",
"None",
",",
"method",
":",
"str",
"=",
"'MEMORY'",
",",
"*",
"*",
"kwargs",
")",
"->",
"'pd.DataFrame'",
":",
"dsopts",
... | This is an alias for 'sasdata2dataframe'. Why type all that?
SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame
:param table: the name of the SAS Data Set you want to export to a Pandas Data Frame
:param libref: the libref for the SAS Data Set.
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
- format is a string or dictionary { var: format }
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
'format' : {'money': 'dollar10', 'time': 'tod5.'}
}
: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: dictionary
:return: Pandas data frame | [
"This",
"is",
"an",
"alias",
"for",
"sasdata2dataframe",
".",
"Why",
"type",
"all",
"that?",
"SASdata",
"object",
"that",
"refers",
"to",
"the",
"Sas",
"Data",
"Set",
"you",
"want",
"to",
"export",
"to",
"a",
"Pandas",
"Data",
"Frame"
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L871-L902 |
241,913 | sassoftware/saspy | saspy/sasbase.py | SASsession.sd2df_CSV | def sd2df_CSV(self, table: str, libref: str = '', dsopts: dict = None, tempfile: str = None, tempkeep: bool = False,
**kwargs) -> 'pd.DataFrame':
"""
This is an alias for 'sasdata2dataframe' specifying method='CSV'. Why type all that?
SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame
:param table: the name of the SAS Data Set you want to export to a Pandas Data Frame
:param libref: the libref for the SAS Data Set.
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
- format is a string or dictionary { var: format }
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
'format' : {'money': 'dollar10', 'time': 'tod5.'}
}
: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: dictionary
:return: Pandas data frame
"""
dsopts = dsopts if dsopts is not None else {}
return self.sasdata2dataframe(table, libref, dsopts, method='CSV', tempfile=tempfile, tempkeep=tempkeep,
**kwargs) | python | def sd2df_CSV(self, table: str, libref: str = '', dsopts: dict = None, tempfile: str = None, tempkeep: bool = False,
**kwargs) -> 'pd.DataFrame':
dsopts = dsopts if dsopts is not None else {}
return self.sasdata2dataframe(table, libref, dsopts, method='CSV', tempfile=tempfile, tempkeep=tempkeep,
**kwargs) | [
"def",
"sd2df_CSV",
"(",
"self",
",",
"table",
":",
"str",
",",
"libref",
":",
"str",
"=",
"''",
",",
"dsopts",
":",
"dict",
"=",
"None",
",",
"tempfile",
":",
"str",
"=",
"None",
",",
"tempkeep",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs... | This is an alias for 'sasdata2dataframe' specifying method='CSV'. Why type all that?
SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame
:param table: the name of the SAS Data Set you want to export to a Pandas Data Frame
:param libref: the libref for the SAS Data Set.
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
- format is a string or dictionary { var: format }
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
'format' : {'money': 'dollar10', 'time': 'tod5.'}
}
: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: dictionary
:return: Pandas data frame | [
"This",
"is",
"an",
"alias",
"for",
"sasdata2dataframe",
"specifying",
"method",
"=",
"CSV",
".",
"Why",
"type",
"all",
"that?",
"SASdata",
"object",
"that",
"refers",
"to",
"the",
"Sas",
"Data",
"Set",
"you",
"want",
"to",
"export",
"to",
"a",
"Pandas",
... | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L904-L937 |
241,914 | sassoftware/saspy | saspy/sasbase.py | SASsession.sasdata2dataframe | def sasdata2dataframe(self, table: str, libref: str = '', dsopts: dict = None, method: str = 'MEMORY',
**kwargs) -> 'pd.DataFrame':
"""
This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object.
SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame
:param table: the name of the SAS Data Set you want to export to a Pandas Data Frame
:param libref: the libref for the SAS Data Set.
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
- format is a string or dictionary { var: format }
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
'format' : {'money': 'dollar10', 'time': 'tod5.'}
}
: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: dictionary
:return: Pandas data frame
"""
dsopts = dsopts if dsopts is not None else {}
if self.exist(table, libref) == 0:
print('The SAS Data Set ' + libref + '.' + table + ' does not exist')
return None
if self.nosub:
print("too complicated to show the code, read the source :), sorry.")
return None
else:
return self._io.sasdata2dataframe(table, libref, dsopts, method=method, **kwargs) | python | def sasdata2dataframe(self, table: str, libref: str = '', dsopts: dict = None, method: str = 'MEMORY',
**kwargs) -> 'pd.DataFrame':
dsopts = dsopts if dsopts is not None else {}
if self.exist(table, libref) == 0:
print('The SAS Data Set ' + libref + '.' + table + ' does not exist')
return None
if self.nosub:
print("too complicated to show the code, read the source :), sorry.")
return None
else:
return self._io.sasdata2dataframe(table, libref, dsopts, method=method, **kwargs) | [
"def",
"sasdata2dataframe",
"(",
"self",
",",
"table",
":",
"str",
",",
"libref",
":",
"str",
"=",
"''",
",",
"dsopts",
":",
"dict",
"=",
"None",
",",
"method",
":",
"str",
"=",
"'MEMORY'",
",",
"*",
"*",
"kwargs",
")",
"->",
"'pd.DataFrame'",
":",
... | This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object.
SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame
:param table: the name of the SAS Data Set you want to export to a Pandas Data Frame
:param libref: the libref for the SAS Data Set.
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
- format is a string or dictionary { var: format }
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
'format' : {'money': 'dollar10', 'time': 'tod5.'}
}
: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: dictionary
:return: Pandas data frame | [
"This",
"method",
"exports",
"the",
"SAS",
"Data",
"Set",
"to",
"a",
"Pandas",
"Data",
"Frame",
"returning",
"the",
"Data",
"Frame",
"object",
".",
"SASdata",
"object",
"that",
"refers",
"to",
"the",
"Sas",
"Data",
"Set",
"you",
"want",
"to",
"export",
"... | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L939-L979 |
241,915 | sassoftware/saspy | saspy/sasbase.py | SASsession.disconnect | def disconnect(self):
"""
This method disconnects an IOM session to allow for reconnecting when switching networks
See the Advanced topics section of the doc for details
"""
if self.sascfg.mode != 'IOM':
res = "This method is only available with the IOM access method"
else:
res = self._io.disconnect()
return res | python | def disconnect(self):
if self.sascfg.mode != 'IOM':
res = "This method is only available with the IOM access method"
else:
res = self._io.disconnect()
return res | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"sascfg",
".",
"mode",
"!=",
"'IOM'",
":",
"res",
"=",
"\"This method is only available with the IOM access method\"",
"else",
":",
"res",
"=",
"self",
".",
"_io",
".",
"disconnect",
"(",
")",
"r... | This method disconnects an IOM session to allow for reconnecting when switching networks
See the Advanced topics section of the doc for details | [
"This",
"method",
"disconnects",
"an",
"IOM",
"session",
"to",
"allow",
"for",
"reconnecting",
"when",
"switching",
"networks",
"See",
"the",
"Advanced",
"topics",
"section",
"of",
"the",
"doc",
"for",
"details"
] | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L1159-L1168 |
241,916 | 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:
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 - 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 |
241,917 | 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):
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",
"=",
"resu... | 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",
... | e433f71990f249d3a6c3db323ceb11cb2d462cf9 | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L116-L128 |
241,918 | 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):
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",
")... | 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 |
241,919 | 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':
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",
")",... | 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 |
241,920 | 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):
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",
"... | 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 |
241,921 | 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):
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",
"(",
")",
"+",
"\";%... | 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 |
241,922 | 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):
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;\... | 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 |
241,923 | 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):
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",
":",... | 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 |
241,924 | 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):
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",
... | 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 |
241,925 | 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':
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",
",",
"st... | 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 |
241,926 | 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:
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",
... | 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 |
241,927 | 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':
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",
".",
"ta... | 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 |
241,928 | 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':
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'",
"]",
")",
"retur... | 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 |
241,929 | 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':
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'",
",",
"tempf... | 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 |
241,930 | 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:
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",
"+"... | 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 |
241,931 | 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:
# 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 ... | 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 |
241,932 | 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):
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 ... | 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 |
241,933 | 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):
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__",
... | 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 |
241,934 | 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):
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",
")",... | 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 |
241,935 | 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':
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'",
",",
... | 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 |
241,936 | 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 |
241,937 | 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):
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_packa... | 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 |
241,938 | 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):
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",
".",
"... | 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 |
241,939 | 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):
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... | 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 |
241,940 | 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",
"("... | 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 |
241,941 | 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):
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... | 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 |
241,942 | 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):
# 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_spe... | 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 |
241,943 | 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'",
")",
",",
"sel... | 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 |
241,944 | 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",
"... | 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 |
241,945 | 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",
"=",
"'c... | 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 |
241,946 | 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):
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",
"(",
"cel... | 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 |
241,947 | 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):
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",
"... | 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 |
241,948 | 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):
_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 basecl... | 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 |
241,949 | 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'end... | 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 |
241,950 | 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 |
241,951 | 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",
"... | 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 |
241,952 | 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",
"st... | 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 |
241,953 | 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",
... | 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 |
241,954 | 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",
"=",
"escap... | 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 |
241,955 | 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):
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",
":",
"r... | 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 |
241,956 | 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 |
241,957 | 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 |
241,958 | 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",
... | 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 |
241,959 | 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):
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",
... | 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 |
241,960 | 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')):
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",
".... | 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 |
241,961 | 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):
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",
"=",
"'{}.{}'",
".",
"for... | 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 |
241,962 | 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_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 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 |
241,963 | 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):
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",
",",
"pl... | 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 |
241,964 | 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):
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 |
241,965 | 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):
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",
"(",... | 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 |
241,966 | 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):
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",
... | 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 |
241,967 | 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):
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",
"sel... | 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 |
241,968 | 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):
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 |
241,969 | 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):
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'",
")... | 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 |
241,970 | 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",
... | 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 |
241,971 | 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):
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",
... | 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 |
241,972 | 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):
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",
"compil... | 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 |
241,973 | 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):
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",
... | 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 |
241,974 | 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",
"=",
... | 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 |
241,975 | 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 |
241,976 | 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"... | 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 |
241,977 | 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):
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",
")",
... | 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 |
241,978 | 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 (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 |
241,979 | 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):
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}... | 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 |
241,980 | 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):
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",
"+",
... | 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 |
241,981 | 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):
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",
"... | 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 |
241,982 | 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):
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",
".",
... | 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 |
241,983 | 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\"\\he... | 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 |
241,984 | 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):
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",
".",
... | 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 |
241,985 | 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):
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",
... | Euclidean distance between two coordinates. | [
"Euclidean",
"distance",
"between",
"two",
"coordinates",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L151-L156 |
241,986 | 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):
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",
"No... | 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 |
241,987 | 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):
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",
"=",
... | 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 |
241,988 | 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):
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 |
241,989 | 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):
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",
"(",
")",
")",... | 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 |
241,990 | 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):
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 a representation for the command. | [
"Return",
"a",
"representation",
"for",
"the",
"command",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L467-L474 |
241,991 | 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):
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 {%\\... | 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 |
241,992 | 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):
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 |
241,993 | 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):
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",
... | 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 |
241,994 | 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):
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",
")"... | 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 |
241,995 | 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):
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_functio... | 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 |
241,996 | 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):
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",
... | 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 |
241,997 | 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",
")",
"[",
":",... | 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 |
241,998 | 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",
".",
... | 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 |
241,999 | 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):
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.