repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 39
1.84M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
ampl/amplpy | amplpy/ampl.py | AMPL.getValue | def getValue(self, scalarExpression):
"""
Get a scalar value from the underlying AMPL interpreter, as a double or
a string.
Args:
scalarExpression: An AMPL expression which evaluates to a scalar
value.
Returns:
The value of the expression.
"""
return lock_and_call(
lambda: Utils.castVariant(self._impl.getValue(scalarExpression)),
self._lock
) | python | def getValue(self, scalarExpression):
return lock_and_call(
lambda: Utils.castVariant(self._impl.getValue(scalarExpression)),
self._lock
) | [
"def",
"getValue",
"(",
"self",
",",
"scalarExpression",
")",
":",
"return",
"lock_and_call",
"(",
"lambda",
":",
"Utils",
".",
"castVariant",
"(",
"self",
".",
"_impl",
".",
"getValue",
"(",
"scalarExpression",
")",
")",
",",
"self",
".",
"_lock",
")"
]
| Get a scalar value from the underlying AMPL interpreter, as a double or
a string.
Args:
scalarExpression: An AMPL expression which evaluates to a scalar
value.
Returns:
The value of the expression. | [
"Get",
"a",
"scalar",
"value",
"from",
"the",
"underlying",
"AMPL",
"interpreter",
"as",
"a",
"double",
"or",
"a",
"string",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L612-L627 |
ampl/amplpy | amplpy/ampl.py | AMPL.setData | def setData(self, data, setName=None):
"""
Assign the data in the dataframe to the AMPL entities with the names
corresponding to the column names.
Args:
data: The dataframe containing the data to be assigned.
setName: The name of the set to which the indices values of the
DataFrame are to be assigned.
Raises:
AMPLException: if the data assignment procedure was not successful.
"""
if not isinstance(data, DataFrame):
if pd is not None and isinstance(data, pd.DataFrame):
data = DataFrame.fromPandas(data)
if setName is None:
lock_and_call(
lambda: self._impl.setData(data._impl),
self._lock
)
else:
lock_and_call(
lambda: self._impl.setData(data._impl, setName),
self._lock
) | python | def setData(self, data, setName=None):
if not isinstance(data, DataFrame):
if pd is not None and isinstance(data, pd.DataFrame):
data = DataFrame.fromPandas(data)
if setName is None:
lock_and_call(
lambda: self._impl.setData(data._impl),
self._lock
)
else:
lock_and_call(
lambda: self._impl.setData(data._impl, setName),
self._lock
) | [
"def",
"setData",
"(",
"self",
",",
"data",
",",
"setName",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"DataFrame",
")",
":",
"if",
"pd",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"data",
",",
"pd",
".",
"DataFrame",
")",
":",
"data",
"=",
"DataFrame",
".",
"fromPandas",
"(",
"data",
")",
"if",
"setName",
"is",
"None",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setData",
"(",
"data",
".",
"_impl",
")",
",",
"self",
".",
"_lock",
")",
"else",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setData",
"(",
"data",
".",
"_impl",
",",
"setName",
")",
",",
"self",
".",
"_lock",
")"
]
| Assign the data in the dataframe to the AMPL entities with the names
corresponding to the column names.
Args:
data: The dataframe containing the data to be assigned.
setName: The name of the set to which the indices values of the
DataFrame are to be assigned.
Raises:
AMPLException: if the data assignment procedure was not successful. | [
"Assign",
"the",
"data",
"in",
"the",
"dataframe",
"to",
"the",
"AMPL",
"entities",
"with",
"the",
"names",
"corresponding",
"to",
"the",
"column",
"names",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L629-L655 |
ampl/amplpy | amplpy/ampl.py | AMPL.readTable | def readTable(self, tableName):
"""
Read the table corresponding to the specified name, equivalent to the
AMPL statement:
.. code-block:: ampl
read table tableName;
Args:
tableName: Name of the table to be read.
"""
lock_and_call(
lambda: self._impl.readTable(tableName),
self._lock
) | python | def readTable(self, tableName):
lock_and_call(
lambda: self._impl.readTable(tableName),
self._lock
) | [
"def",
"readTable",
"(",
"self",
",",
"tableName",
")",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"readTable",
"(",
"tableName",
")",
",",
"self",
".",
"_lock",
")"
]
| Read the table corresponding to the specified name, equivalent to the
AMPL statement:
.. code-block:: ampl
read table tableName;
Args:
tableName: Name of the table to be read. | [
"Read",
"the",
"table",
"corresponding",
"to",
"the",
"specified",
"name",
"equivalent",
"to",
"the",
"AMPL",
"statement",
":"
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L657-L672 |
ampl/amplpy | amplpy/ampl.py | AMPL.writeTable | def writeTable(self, tableName):
"""
Write the table corresponding to the specified name, equivalent to the
AMPL statement
.. code-block:: ampl
write table tableName;
Args:
tableName: Name of the table to be written.
"""
lock_and_call(
lambda: self._impl.writeTable(tableName),
self._lock
) | python | def writeTable(self, tableName):
lock_and_call(
lambda: self._impl.writeTable(tableName),
self._lock
) | [
"def",
"writeTable",
"(",
"self",
",",
"tableName",
")",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"writeTable",
"(",
"tableName",
")",
",",
"self",
".",
"_lock",
")"
]
| Write the table corresponding to the specified name, equivalent to the
AMPL statement
.. code-block:: ampl
write table tableName;
Args:
tableName: Name of the table to be written. | [
"Write",
"the",
"table",
"corresponding",
"to",
"the",
"specified",
"name",
"equivalent",
"to",
"the",
"AMPL",
"statement"
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L674-L689 |
ampl/amplpy | amplpy/ampl.py | AMPL.display | def display(self, *amplExpressions):
"""
Writes on the current OutputHandler the outcome of the AMPL statement.
.. code-block:: ampl
display e1, e2, .., en;
where e1, ..., en are the strings passed to the procedure.
Args:
amplExpressions: Expressions to be evaluated.
"""
exprs = list(map(str, amplExpressions))
lock_and_call(
lambda: self._impl.displayLst(exprs, len(exprs)),
self._lock
) | python | def display(self, *amplExpressions):
exprs = list(map(str, amplExpressions))
lock_and_call(
lambda: self._impl.displayLst(exprs, len(exprs)),
self._lock
) | [
"def",
"display",
"(",
"self",
",",
"*",
"amplExpressions",
")",
":",
"exprs",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"amplExpressions",
")",
")",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"displayLst",
"(",
"exprs",
",",
"len",
"(",
"exprs",
")",
")",
",",
"self",
".",
"_lock",
")"
]
| Writes on the current OutputHandler the outcome of the AMPL statement.
.. code-block:: ampl
display e1, e2, .., en;
where e1, ..., en are the strings passed to the procedure.
Args:
amplExpressions: Expressions to be evaluated. | [
"Writes",
"on",
"the",
"current",
"OutputHandler",
"the",
"outcome",
"of",
"the",
"AMPL",
"statement",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L691-L708 |
ampl/amplpy | amplpy/ampl.py | AMPL.setOutputHandler | def setOutputHandler(self, outputhandler):
"""
Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands.
"""
class OutputHandlerInternal(amplpython.OutputHandler):
def output(self, kind, msg):
outputhandler.output(kind, msg)
self._outputhandler = outputhandler
self._outputhandler_internal = OutputHandlerInternal()
lock_and_call(
lambda: self._impl.setOutputHandler(
self._outputhandler_internal
),
self._lock
) | python | def setOutputHandler(self, outputhandler):
class OutputHandlerInternal(amplpython.OutputHandler):
def output(self, kind, msg):
outputhandler.output(kind, msg)
self._outputhandler = outputhandler
self._outputhandler_internal = OutputHandlerInternal()
lock_and_call(
lambda: self._impl.setOutputHandler(
self._outputhandler_internal
),
self._lock
) | [
"def",
"setOutputHandler",
"(",
"self",
",",
"outputhandler",
")",
":",
"class",
"OutputHandlerInternal",
"(",
"amplpython",
".",
"OutputHandler",
")",
":",
"def",
"output",
"(",
"self",
",",
"kind",
",",
"msg",
")",
":",
"outputhandler",
".",
"output",
"(",
"kind",
",",
"msg",
")",
"self",
".",
"_outputhandler",
"=",
"outputhandler",
"self",
".",
"_outputhandler_internal",
"=",
"OutputHandlerInternal",
"(",
")",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setOutputHandler",
"(",
"self",
".",
"_outputhandler_internal",
")",
",",
"self",
".",
"_lock",
")"
]
| Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands. | [
"Sets",
"a",
"new",
"output",
"handler",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L710-L729 |
ampl/amplpy | amplpy/ampl.py | AMPL.setErrorHandler | def setErrorHandler(self, errorhandler):
"""
Sets a new error handler.
Args:
errorhandler: The object handling AMPL errors and warnings.
"""
class ErrorHandlerWrapper(ErrorHandler):
def __init__(self, errorhandler):
self.errorhandler = errorhandler
self.last_exception = None
def error(self, exception):
if isinstance(exception, amplpython.AMPLException):
exception = AMPLException(exception)
try:
self.errorhandler.error(exception)
except Exception as e:
self.last_exception = e
def warning(self, exception):
if isinstance(exception, amplpython.AMPLException):
exception = AMPLException(exception)
try:
self.errorhandler.warning(exception)
except Exception as e:
self.last_exception = e
def check(self):
if self.last_exception is not None:
e, self.last_exception = self.last_exception, None
raise e
errorhandler_wrapper = ErrorHandlerWrapper(errorhandler)
class InnerErrorHandler(amplpython.ErrorHandler):
def error(self, exception):
errorhandler_wrapper.error(exception)
def warning(self, exception):
errorhandler_wrapper.warning(exception)
self._errorhandler = errorhandler
self._errorhandler_inner = InnerErrorHandler()
self._errorhandler_wrapper = errorhandler_wrapper
lock_and_call(
lambda: self._impl.setErrorHandler(self._errorhandler_inner),
self._lock
) | python | def setErrorHandler(self, errorhandler):
class ErrorHandlerWrapper(ErrorHandler):
def __init__(self, errorhandler):
self.errorhandler = errorhandler
self.last_exception = None
def error(self, exception):
if isinstance(exception, amplpython.AMPLException):
exception = AMPLException(exception)
try:
self.errorhandler.error(exception)
except Exception as e:
self.last_exception = e
def warning(self, exception):
if isinstance(exception, amplpython.AMPLException):
exception = AMPLException(exception)
try:
self.errorhandler.warning(exception)
except Exception as e:
self.last_exception = e
def check(self):
if self.last_exception is not None:
e, self.last_exception = self.last_exception, None
raise e
errorhandler_wrapper = ErrorHandlerWrapper(errorhandler)
class InnerErrorHandler(amplpython.ErrorHandler):
def error(self, exception):
errorhandler_wrapper.error(exception)
def warning(self, exception):
errorhandler_wrapper.warning(exception)
self._errorhandler = errorhandler
self._errorhandler_inner = InnerErrorHandler()
self._errorhandler_wrapper = errorhandler_wrapper
lock_and_call(
lambda: self._impl.setErrorHandler(self._errorhandler_inner),
self._lock
) | [
"def",
"setErrorHandler",
"(",
"self",
",",
"errorhandler",
")",
":",
"class",
"ErrorHandlerWrapper",
"(",
"ErrorHandler",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"errorhandler",
")",
":",
"self",
".",
"errorhandler",
"=",
"errorhandler",
"self",
".",
"last_exception",
"=",
"None",
"def",
"error",
"(",
"self",
",",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"amplpython",
".",
"AMPLException",
")",
":",
"exception",
"=",
"AMPLException",
"(",
"exception",
")",
"try",
":",
"self",
".",
"errorhandler",
".",
"error",
"(",
"exception",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"last_exception",
"=",
"e",
"def",
"warning",
"(",
"self",
",",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"amplpython",
".",
"AMPLException",
")",
":",
"exception",
"=",
"AMPLException",
"(",
"exception",
")",
"try",
":",
"self",
".",
"errorhandler",
".",
"warning",
"(",
"exception",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"last_exception",
"=",
"e",
"def",
"check",
"(",
"self",
")",
":",
"if",
"self",
".",
"last_exception",
"is",
"not",
"None",
":",
"e",
",",
"self",
".",
"last_exception",
"=",
"self",
".",
"last_exception",
",",
"None",
"raise",
"e",
"errorhandler_wrapper",
"=",
"ErrorHandlerWrapper",
"(",
"errorhandler",
")",
"class",
"InnerErrorHandler",
"(",
"amplpython",
".",
"ErrorHandler",
")",
":",
"def",
"error",
"(",
"self",
",",
"exception",
")",
":",
"errorhandler_wrapper",
".",
"error",
"(",
"exception",
")",
"def",
"warning",
"(",
"self",
",",
"exception",
")",
":",
"errorhandler_wrapper",
".",
"warning",
"(",
"exception",
")",
"self",
".",
"_errorhandler",
"=",
"errorhandler",
"self",
".",
"_errorhandler_inner",
"=",
"InnerErrorHandler",
"(",
")",
"self",
".",
"_errorhandler_wrapper",
"=",
"errorhandler_wrapper",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setErrorHandler",
"(",
"self",
".",
"_errorhandler_inner",
")",
",",
"self",
".",
"_lock",
")"
]
| Sets a new error handler.
Args:
errorhandler: The object handling AMPL errors and warnings. | [
"Sets",
"a",
"new",
"error",
"handler",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L731-L779 |
ampl/amplpy | amplpy/ampl.py | AMPL.getVariables | def getVariables(self):
"""
Get all the variables declared.
"""
variables = lock_and_call(
lambda: self._impl.getVariables(),
self._lock
)
return EntityMap(variables, Variable) | python | def getVariables(self):
variables = lock_and_call(
lambda: self._impl.getVariables(),
self._lock
)
return EntityMap(variables, Variable) | [
"def",
"getVariables",
"(",
"self",
")",
":",
"variables",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getVariables",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"variables",
",",
"Variable",
")"
]
| Get all the variables declared. | [
"Get",
"all",
"the",
"variables",
"declared",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L799-L807 |
ampl/amplpy | amplpy/ampl.py | AMPL.getConstraints | def getConstraints(self):
"""
Get all the constraints declared.
"""
constraints = lock_and_call(
lambda: self._impl.getConstraints(),
self._lock
)
return EntityMap(constraints, Constraint) | python | def getConstraints(self):
constraints = lock_and_call(
lambda: self._impl.getConstraints(),
self._lock
)
return EntityMap(constraints, Constraint) | [
"def",
"getConstraints",
"(",
"self",
")",
":",
"constraints",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getConstraints",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"constraints",
",",
"Constraint",
")"
]
| Get all the constraints declared. | [
"Get",
"all",
"the",
"constraints",
"declared",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L809-L817 |
ampl/amplpy | amplpy/ampl.py | AMPL.getObjectives | def getObjectives(self):
"""
Get all the objectives declared.
"""
objectives = lock_and_call(
lambda: self._impl.getObjectives(),
self._lock
)
return EntityMap(objectives, Objective) | python | def getObjectives(self):
objectives = lock_and_call(
lambda: self._impl.getObjectives(),
self._lock
)
return EntityMap(objectives, Objective) | [
"def",
"getObjectives",
"(",
"self",
")",
":",
"objectives",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getObjectives",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"objectives",
",",
"Objective",
")"
]
| Get all the objectives declared. | [
"Get",
"all",
"the",
"objectives",
"declared",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L819-L827 |
ampl/amplpy | amplpy/ampl.py | AMPL.getSets | def getSets(self):
"""
Get all the sets declared.
"""
sets = lock_and_call(
lambda: self._impl.getSets(),
self._lock
)
return EntityMap(sets, Set) | python | def getSets(self):
sets = lock_and_call(
lambda: self._impl.getSets(),
self._lock
)
return EntityMap(sets, Set) | [
"def",
"getSets",
"(",
"self",
")",
":",
"sets",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getSets",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"sets",
",",
"Set",
")"
]
| Get all the sets declared. | [
"Get",
"all",
"the",
"sets",
"declared",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L829-L837 |
ampl/amplpy | amplpy/ampl.py | AMPL.getParameters | def getParameters(self):
"""
Get all the parameters declared.
"""
parameters = lock_and_call(
lambda: self._impl.getParameters(),
self._lock
)
return EntityMap(parameters, Parameter) | python | def getParameters(self):
parameters = lock_and_call(
lambda: self._impl.getParameters(),
self._lock
)
return EntityMap(parameters, Parameter) | [
"def",
"getParameters",
"(",
"self",
")",
":",
"parameters",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getParameters",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"parameters",
",",
"Parameter",
")"
]
| Get all the parameters declared. | [
"Get",
"all",
"the",
"parameters",
"declared",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L839-L847 |
ampl/amplpy | amplpy/ampl.py | AMPL.getCurrentObjective | def getCurrentObjective(self):
"""
Get the the current objective. Returns `None` if no objective is set.
"""
name = self._impl.getCurrentObjectiveName()
if name == '':
return None
else:
return self.getObjective(name) | python | def getCurrentObjective(self):
name = self._impl.getCurrentObjectiveName()
if name == '':
return None
else:
return self.getObjective(name) | [
"def",
"getCurrentObjective",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"_impl",
".",
"getCurrentObjectiveName",
"(",
")",
"if",
"name",
"==",
"''",
":",
"return",
"None",
"else",
":",
"return",
"self",
".",
"getObjective",
"(",
"name",
")"
]
| Get the the current objective. Returns `None` if no objective is set. | [
"Get",
"the",
"the",
"current",
"objective",
".",
"Returns",
"None",
"if",
"no",
"objective",
"is",
"set",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L849-L857 |
ampl/amplpy | amplpy/ampl.py | AMPL._var | def _var(self):
"""
Get/Set a variable.
"""
class Variables(object):
def __getitem__(_self, name):
return self.getVariable(name)
def __setitem__(_self, name, value):
self.getVariable(name).setValue(value)
def __iter__(_self):
return self.getVariables()
return Variables() | python | def _var(self):
class Variables(object):
def __getitem__(_self, name):
return self.getVariable(name)
def __setitem__(_self, name, value):
self.getVariable(name).setValue(value)
def __iter__(_self):
return self.getVariables()
return Variables() | [
"def",
"_var",
"(",
"self",
")",
":",
"class",
"Variables",
"(",
"object",
")",
":",
"def",
"__getitem__",
"(",
"_self",
",",
"name",
")",
":",
"return",
"self",
".",
"getVariable",
"(",
"name",
")",
"def",
"__setitem__",
"(",
"_self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"getVariable",
"(",
"name",
")",
".",
"setValue",
"(",
"value",
")",
"def",
"__iter__",
"(",
"_self",
")",
":",
"return",
"self",
".",
"getVariables",
"(",
")",
"return",
"Variables",
"(",
")"
]
| Get/Set a variable. | [
"Get",
"/",
"Set",
"a",
"variable",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L859-L873 |
ampl/amplpy | amplpy/ampl.py | AMPL._con | def _con(self):
"""
Get/Set a constraint.
"""
class Constraints(object):
def __getitem__(_self, name):
return self.getConstraint(name)
def __setitem__(_self, name, value):
self.getConstraint(name).setDual(value)
def __iter__(_self):
return self.getConstraints()
return Constraints() | python | def _con(self):
class Constraints(object):
def __getitem__(_self, name):
return self.getConstraint(name)
def __setitem__(_self, name, value):
self.getConstraint(name).setDual(value)
def __iter__(_self):
return self.getConstraints()
return Constraints() | [
"def",
"_con",
"(",
"self",
")",
":",
"class",
"Constraints",
"(",
"object",
")",
":",
"def",
"__getitem__",
"(",
"_self",
",",
"name",
")",
":",
"return",
"self",
".",
"getConstraint",
"(",
"name",
")",
"def",
"__setitem__",
"(",
"_self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"getConstraint",
"(",
"name",
")",
".",
"setDual",
"(",
"value",
")",
"def",
"__iter__",
"(",
"_self",
")",
":",
"return",
"self",
".",
"getConstraints",
"(",
")",
"return",
"Constraints",
"(",
")"
]
| Get/Set a constraint. | [
"Get",
"/",
"Set",
"a",
"constraint",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L875-L889 |
ampl/amplpy | amplpy/ampl.py | AMPL._obj | def _obj(self):
"""
Get an objective.
"""
class Objectives(object):
def __getitem__(_self, name):
return self.getObjective(name)
def __iter__(_self):
return self.getObjectives()
return Objectives() | python | def _obj(self):
class Objectives(object):
def __getitem__(_self, name):
return self.getObjective(name)
def __iter__(_self):
return self.getObjectives()
return Objectives() | [
"def",
"_obj",
"(",
"self",
")",
":",
"class",
"Objectives",
"(",
"object",
")",
":",
"def",
"__getitem__",
"(",
"_self",
",",
"name",
")",
":",
"return",
"self",
".",
"getObjective",
"(",
"name",
")",
"def",
"__iter__",
"(",
"_self",
")",
":",
"return",
"self",
".",
"getObjectives",
"(",
")",
"return",
"Objectives",
"(",
")"
]
| Get an objective. | [
"Get",
"an",
"objective",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L891-L902 |
ampl/amplpy | amplpy/ampl.py | AMPL._set | def _set(self):
"""
Get/Set a set.
"""
class Sets(object):
def __getitem__(_self, name):
return self.getSet(name)
def __setitem__(_self, name, values):
self.getSet(name).setValues(values)
def __iter__(_self):
return self.getSets()
return Sets() | python | def _set(self):
class Sets(object):
def __getitem__(_self, name):
return self.getSet(name)
def __setitem__(_self, name, values):
self.getSet(name).setValues(values)
def __iter__(_self):
return self.getSets()
return Sets() | [
"def",
"_set",
"(",
"self",
")",
":",
"class",
"Sets",
"(",
"object",
")",
":",
"def",
"__getitem__",
"(",
"_self",
",",
"name",
")",
":",
"return",
"self",
".",
"getSet",
"(",
"name",
")",
"def",
"__setitem__",
"(",
"_self",
",",
"name",
",",
"values",
")",
":",
"self",
".",
"getSet",
"(",
"name",
")",
".",
"setValues",
"(",
"values",
")",
"def",
"__iter__",
"(",
"_self",
")",
":",
"return",
"self",
".",
"getSets",
"(",
")",
"return",
"Sets",
"(",
")"
]
| Get/Set a set. | [
"Get",
"/",
"Set",
"a",
"set",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L904-L918 |
ampl/amplpy | amplpy/ampl.py | AMPL._param | def _param(self):
"""
Get/Set a parameter.
"""
class Parameters(object):
def __getitem__(_self, name):
return self.getParameter(name)
def __setitem__(_self, name, value):
if isinstance(value, (float, int, basestring)):
self.getParameter(name).set(value)
else:
self.getParameter(name).setValues(value)
def __iter__(_self):
return self.getParameters()
return Parameters() | python | def _param(self):
class Parameters(object):
def __getitem__(_self, name):
return self.getParameter(name)
def __setitem__(_self, name, value):
if isinstance(value, (float, int, basestring)):
self.getParameter(name).set(value)
else:
self.getParameter(name).setValues(value)
def __iter__(_self):
return self.getParameters()
return Parameters() | [
"def",
"_param",
"(",
"self",
")",
":",
"class",
"Parameters",
"(",
"object",
")",
":",
"def",
"__getitem__",
"(",
"_self",
",",
"name",
")",
":",
"return",
"self",
".",
"getParameter",
"(",
"name",
")",
"def",
"__setitem__",
"(",
"_self",
",",
"name",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"float",
",",
"int",
",",
"basestring",
")",
")",
":",
"self",
".",
"getParameter",
"(",
"name",
")",
".",
"set",
"(",
"value",
")",
"else",
":",
"self",
".",
"getParameter",
"(",
"name",
")",
".",
"setValues",
"(",
"value",
")",
"def",
"__iter__",
"(",
"_self",
")",
":",
"return",
"self",
".",
"getParameters",
"(",
")",
"return",
"Parameters",
"(",
")"
]
| Get/Set a parameter. | [
"Get",
"/",
"Set",
"a",
"parameter",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L920-L937 |
ampl/amplpy | amplpy/ampl.py | AMPL._option | def _option(self):
"""
Get/Set an option.
"""
class Options(object):
def __getitem__(_self, name):
return self.getOption(name)
def __setitem__(_self, name, value):
self.setOption(name, value)
return Options() | python | def _option(self):
class Options(object):
def __getitem__(_self, name):
return self.getOption(name)
def __setitem__(_self, name, value):
self.setOption(name, value)
return Options() | [
"def",
"_option",
"(",
"self",
")",
":",
"class",
"Options",
"(",
"object",
")",
":",
"def",
"__getitem__",
"(",
"_self",
",",
"name",
")",
":",
"return",
"self",
".",
"getOption",
"(",
"name",
")",
"def",
"__setitem__",
"(",
"_self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"setOption",
"(",
"name",
",",
"value",
")",
"return",
"Options",
"(",
")"
]
| Get/Set an option. | [
"Get",
"/",
"Set",
"an",
"option",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L939-L950 |
ampl/amplpy | amplpy/ampl.py | AMPL.exportData | def exportData(self, datfile):
"""
Create a .dat file with the data that has been loaded.
Args:
datfile: Path to the file (Relative to the current working
directory or absolute).
"""
def ampl_set(name, values):
def format_entry(e):
return repr(e).replace(' ', '')
return 'set {0} := {1};'.format(
name, ','.join(format_entry(e) for e in values)
)
def ampl_param(name, values):
def format_entry(k, v):
k = repr(k).strip('()').replace(' ', '')
if v == inf:
v = "Infinity"
elif v == -inf:
v = "-Infinity"
else:
v = repr(v).strip('()').replace(' ', '')
return '[{0}]{1}'.format(k, v)
return 'param {0} := {1};'.format(
name, ''.join(format_entry(k, v) for k, v in values.items())
)
with open(datfile, 'w') as f:
for name, entity in self.getSets():
values = entity.getValues().toList()
print(ampl_set(name, values), file=f)
for name, entity in self.getParameters():
if entity.isScalar():
print(
'param {} := {};'.format(name, entity.value()),
file=f
)
else:
values = entity.getValues().toDict()
print(ampl_param(name, values), file=f) | python | def exportData(self, datfile):
def ampl_set(name, values):
def format_entry(e):
return repr(e).replace(' ', '')
return 'set {0} := {1};'.format(
name, ','.join(format_entry(e) for e in values)
)
def ampl_param(name, values):
def format_entry(k, v):
k = repr(k).strip('()').replace(' ', '')
if v == inf:
v = "Infinity"
elif v == -inf:
v = "-Infinity"
else:
v = repr(v).strip('()').replace(' ', '')
return '[{0}]{1}'.format(k, v)
return 'param {0} := {1};'.format(
name, ''.join(format_entry(k, v) for k, v in values.items())
)
with open(datfile, 'w') as f:
for name, entity in self.getSets():
values = entity.getValues().toList()
print(ampl_set(name, values), file=f)
for name, entity in self.getParameters():
if entity.isScalar():
print(
'param {} := {};'.format(name, entity.value()),
file=f
)
else:
values = entity.getValues().toDict()
print(ampl_param(name, values), file=f) | [
"def",
"exportData",
"(",
"self",
",",
"datfile",
")",
":",
"def",
"ampl_set",
"(",
"name",
",",
"values",
")",
":",
"def",
"format_entry",
"(",
"e",
")",
":",
"return",
"repr",
"(",
"e",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"return",
"'set {0} := {1};'",
".",
"format",
"(",
"name",
",",
"','",
".",
"join",
"(",
"format_entry",
"(",
"e",
")",
"for",
"e",
"in",
"values",
")",
")",
"def",
"ampl_param",
"(",
"name",
",",
"values",
")",
":",
"def",
"format_entry",
"(",
"k",
",",
"v",
")",
":",
"k",
"=",
"repr",
"(",
"k",
")",
".",
"strip",
"(",
"'()'",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"if",
"v",
"==",
"inf",
":",
"v",
"=",
"\"Infinity\"",
"elif",
"v",
"==",
"-",
"inf",
":",
"v",
"=",
"\"-Infinity\"",
"else",
":",
"v",
"=",
"repr",
"(",
"v",
")",
".",
"strip",
"(",
"'()'",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"return",
"'[{0}]{1}'",
".",
"format",
"(",
"k",
",",
"v",
")",
"return",
"'param {0} := {1};'",
".",
"format",
"(",
"name",
",",
"''",
".",
"join",
"(",
"format_entry",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"values",
".",
"items",
"(",
")",
")",
")",
"with",
"open",
"(",
"datfile",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"name",
",",
"entity",
"in",
"self",
".",
"getSets",
"(",
")",
":",
"values",
"=",
"entity",
".",
"getValues",
"(",
")",
".",
"toList",
"(",
")",
"print",
"(",
"ampl_set",
"(",
"name",
",",
"values",
")",
",",
"file",
"=",
"f",
")",
"for",
"name",
",",
"entity",
"in",
"self",
".",
"getParameters",
"(",
")",
":",
"if",
"entity",
".",
"isScalar",
"(",
")",
":",
"print",
"(",
"'param {} := {};'",
".",
"format",
"(",
"name",
",",
"entity",
".",
"value",
"(",
")",
")",
",",
"file",
"=",
"f",
")",
"else",
":",
"values",
"=",
"entity",
".",
"getValues",
"(",
")",
".",
"toDict",
"(",
")",
"print",
"(",
"ampl_param",
"(",
"name",
",",
"values",
")",
",",
"file",
"=",
"f",
")"
]
| Create a .dat file with the data that has been loaded.
Args:
datfile: Path to the file (Relative to the current working
directory or absolute). | [
"Create",
"a",
".",
"dat",
"file",
"with",
"the",
"data",
"that",
"has",
"been",
"loaded",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L959-L1003 |
ampl/amplpy | amplpy/ampl.py | AMPL.exportGurobiModel | def exportGurobiModel(self, gurobiDriver='gurobi', verbose=False):
"""
Export the model to Gurobi as a gurobipy.Model object.
Args:
gurobiDriver: The name or the path of the Gurobi solver driver.
verbose: Whether should generate verbose output.
Returns:
A :class:`gurobipy.Model` object with the model loaded.
"""
from gurobipy import GRB, read
from tempfile import mkdtemp
from shutil import rmtree
from os import path
import sys
if (sys.version_info > (3, 0)):
from io import StringIO
else:
from io import BytesIO as StringIO
tmp_dir = mkdtemp()
model_file = path.join(tmp_dir, 'model.mps')
previous = {
'solver': self.getOption('solver') or '',
'gurobi_auxfiles': self.getOption('auxfiles') or '',
'gurobi_options': self.getOption('gurobi_options') or '',
}
temporary = {
'solver': gurobiDriver,
'gurobi_auxfiles': 'rc',
'gurobi_options': '''
writeprob={}
timelim=0
presolve=0
heurfrac=0
outlev=0
'''.format(model_file)
}
for option in temporary:
self.setOption(option, temporary[option])
output = self.getOutput('solve;')
if not path.isfile(model_file):
raise RuntimeError(output)
for option in previous:
self.setOption(option, previous[option])
text_trap = StringIO()
stdout = sys.stdout
sys.stdout = text_trap
model = read(model_file)
sys.stdout = stdout
if verbose:
print(text_trap.getvalue())
if model_file.endswith('.mps'):
if not self.getCurrentObjective().minimization():
model.ModelSense = GRB.MAXIMIZE
model.setObjective(- model.getObjective())
model.update()
rmtree(tmp_dir)
return model | python | def exportGurobiModel(self, gurobiDriver='gurobi', verbose=False):
from gurobipy import GRB, read
from tempfile import mkdtemp
from shutil import rmtree
from os import path
import sys
if (sys.version_info > (3, 0)):
from io import StringIO
else:
from io import BytesIO as StringIO
tmp_dir = mkdtemp()
model_file = path.join(tmp_dir, 'model.mps')
previous = {
'solver': self.getOption('solver') or '',
'gurobi_auxfiles': self.getOption('auxfiles') or '',
'gurobi_options': self.getOption('gurobi_options') or '',
}
temporary = {
'solver': gurobiDriver,
'gurobi_auxfiles': 'rc',
'gurobi_options': .format(model_file)
}
for option in temporary:
self.setOption(option, temporary[option])
output = self.getOutput('solve;')
if not path.isfile(model_file):
raise RuntimeError(output)
for option in previous:
self.setOption(option, previous[option])
text_trap = StringIO()
stdout = sys.stdout
sys.stdout = text_trap
model = read(model_file)
sys.stdout = stdout
if verbose:
print(text_trap.getvalue())
if model_file.endswith('.mps'):
if not self.getCurrentObjective().minimization():
model.ModelSense = GRB.MAXIMIZE
model.setObjective(- model.getObjective())
model.update()
rmtree(tmp_dir)
return model | [
"def",
"exportGurobiModel",
"(",
"self",
",",
"gurobiDriver",
"=",
"'gurobi'",
",",
"verbose",
"=",
"False",
")",
":",
"from",
"gurobipy",
"import",
"GRB",
",",
"read",
"from",
"tempfile",
"import",
"mkdtemp",
"from",
"shutil",
"import",
"rmtree",
"from",
"os",
"import",
"path",
"import",
"sys",
"if",
"(",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"0",
")",
")",
":",
"from",
"io",
"import",
"StringIO",
"else",
":",
"from",
"io",
"import",
"BytesIO",
"as",
"StringIO",
"tmp_dir",
"=",
"mkdtemp",
"(",
")",
"model_file",
"=",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"'model.mps'",
")",
"previous",
"=",
"{",
"'solver'",
":",
"self",
".",
"getOption",
"(",
"'solver'",
")",
"or",
"''",
",",
"'gurobi_auxfiles'",
":",
"self",
".",
"getOption",
"(",
"'auxfiles'",
")",
"or",
"''",
",",
"'gurobi_options'",
":",
"self",
".",
"getOption",
"(",
"'gurobi_options'",
")",
"or",
"''",
",",
"}",
"temporary",
"=",
"{",
"'solver'",
":",
"gurobiDriver",
",",
"'gurobi_auxfiles'",
":",
"'rc'",
",",
"'gurobi_options'",
":",
"'''\n writeprob={}\n timelim=0\n presolve=0\n heurfrac=0\n outlev=0\n '''",
".",
"format",
"(",
"model_file",
")",
"}",
"for",
"option",
"in",
"temporary",
":",
"self",
".",
"setOption",
"(",
"option",
",",
"temporary",
"[",
"option",
"]",
")",
"output",
"=",
"self",
".",
"getOutput",
"(",
"'solve;'",
")",
"if",
"not",
"path",
".",
"isfile",
"(",
"model_file",
")",
":",
"raise",
"RuntimeError",
"(",
"output",
")",
"for",
"option",
"in",
"previous",
":",
"self",
".",
"setOption",
"(",
"option",
",",
"previous",
"[",
"option",
"]",
")",
"text_trap",
"=",
"StringIO",
"(",
")",
"stdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"text_trap",
"model",
"=",
"read",
"(",
"model_file",
")",
"sys",
".",
"stdout",
"=",
"stdout",
"if",
"verbose",
":",
"print",
"(",
"text_trap",
".",
"getvalue",
"(",
")",
")",
"if",
"model_file",
".",
"endswith",
"(",
"'.mps'",
")",
":",
"if",
"not",
"self",
".",
"getCurrentObjective",
"(",
")",
".",
"minimization",
"(",
")",
":",
"model",
".",
"ModelSense",
"=",
"GRB",
".",
"MAXIMIZE",
"model",
".",
"setObjective",
"(",
"-",
"model",
".",
"getObjective",
"(",
")",
")",
"model",
".",
"update",
"(",
")",
"rmtree",
"(",
"tmp_dir",
")",
"return",
"model"
]
| Export the model to Gurobi as a gurobipy.Model object.
Args:
gurobiDriver: The name or the path of the Gurobi solver driver.
verbose: Whether should generate verbose output.
Returns:
A :class:`gurobipy.Model` object with the model loaded. | [
"Export",
"the",
"model",
"to",
"Gurobi",
"as",
"a",
"gurobipy",
".",
"Model",
"object",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1005-L1068 |
ampl/amplpy | amplpy/ampl.py | AMPL.importGurobiSolution | def importGurobiSolution(self, grbmodel):
"""
Import the solution from a gurobipy.Model object.
Args:
grbmodel: A :class:`gurobipy.Model` object with the model solved.
"""
self.eval(''.join(
'let {} := {};'.format(var.VarName, var.X)
for var in grbmodel.getVars()
if '$' not in var.VarName
)) | python | def importGurobiSolution(self, grbmodel):
self.eval(''.join(
'let {} := {};'.format(var.VarName, var.X)
for var in grbmodel.getVars()
if '$' not in var.VarName
)) | [
"def",
"importGurobiSolution",
"(",
"self",
",",
"grbmodel",
")",
":",
"self",
".",
"eval",
"(",
"''",
".",
"join",
"(",
"'let {} := {};'",
".",
"format",
"(",
"var",
".",
"VarName",
",",
"var",
".",
"X",
")",
"for",
"var",
"in",
"grbmodel",
".",
"getVars",
"(",
")",
"if",
"'$'",
"not",
"in",
"var",
".",
"VarName",
")",
")"
]
| Import the solution from a gurobipy.Model object.
Args:
grbmodel: A :class:`gurobipy.Model` object with the model solved. | [
"Import",
"the",
"solution",
"from",
"a",
"gurobipy",
".",
"Model",
"object",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1070-L1081 |
ampl/amplpy | amplpy/ampl.py | AMPL._startRecording | def _startRecording(self, filename):
"""
Start recording the session to a file for debug purposes.
"""
self.setOption('_log_file_name', filename)
self.setOption('_log_input_only', True)
self.setOption('_log', True) | python | def _startRecording(self, filename):
self.setOption('_log_file_name', filename)
self.setOption('_log_input_only', True)
self.setOption('_log', True) | [
"def",
"_startRecording",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"setOption",
"(",
"'_log_file_name'",
",",
"filename",
")",
"self",
".",
"setOption",
"(",
"'_log_input_only'",
",",
"True",
")",
"self",
".",
"setOption",
"(",
"'_log'",
",",
"True",
")"
]
| Start recording the session to a file for debug purposes. | [
"Start",
"recording",
"the",
"session",
"to",
"a",
"file",
"for",
"debug",
"purposes",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1084-L1090 |
ampl/amplpy | amplpy/ampl.py | AMPL._loadSession | def _loadSession(self, filename):
"""
Load a recorded session.
"""
try:
self.eval(open(filename).read())
except RuntimeError as e:
print(e) | python | def _loadSession(self, filename):
try:
self.eval(open(filename).read())
except RuntimeError as e:
print(e) | [
"def",
"_loadSession",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"self",
".",
"eval",
"(",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
")",
"except",
"RuntimeError",
"as",
"e",
":",
"print",
"(",
"e",
")"
]
| Load a recorded session. | [
"Load",
"a",
"recorded",
"session",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1098-L1105 |
ampl/amplpy | setup.py | ls_dir | def ls_dir(base_dir):
"""List files recursively."""
return [
os.path.join(dirpath.replace(base_dir, '', 1), f)
for (dirpath, dirnames, files) in os.walk(base_dir)
for f in files
] | python | def ls_dir(base_dir):
return [
os.path.join(dirpath.replace(base_dir, '', 1), f)
for (dirpath, dirnames, files) in os.walk(base_dir)
for f in files
] | [
"def",
"ls_dir",
"(",
"base_dir",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
".",
"replace",
"(",
"base_dir",
",",
"''",
",",
"1",
")",
",",
"f",
")",
"for",
"(",
"dirpath",
",",
"dirnames",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"base_dir",
")",
"for",
"f",
"in",
"files",
"]"
]
| List files recursively. | [
"List",
"files",
"recursively",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/setup.py#L45-L51 |
ampl/amplpy | amplpy/entity.py | Entity.get | def get(self, *index):
"""
Get the instance with the specified index.
Returns:
The corresponding instance.
"""
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, list)):
index = index[0]
if len(index) == 0:
return self.wrapFunction(self._impl.get())
else:
return self.wrapFunction(self._impl.get(Tuple(index)._impl)) | python | def get(self, *index):
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, list)):
index = index[0]
if len(index) == 0:
return self.wrapFunction(self._impl.get())
else:
return self.wrapFunction(self._impl.get(Tuple(index)._impl)) | [
"def",
"get",
"(",
"self",
",",
"*",
"index",
")",
":",
"assert",
"self",
".",
"wrapFunction",
"is",
"not",
"None",
"if",
"len",
"(",
"index",
")",
"==",
"1",
"and",
"isinstance",
"(",
"index",
"[",
"0",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"index",
"=",
"index",
"[",
"0",
"]",
"if",
"len",
"(",
"index",
")",
"==",
"0",
":",
"return",
"self",
".",
"wrapFunction",
"(",
"self",
".",
"_impl",
".",
"get",
"(",
")",
")",
"else",
":",
"return",
"self",
".",
"wrapFunction",
"(",
"self",
".",
"_impl",
".",
"get",
"(",
"Tuple",
"(",
"index",
")",
".",
"_impl",
")",
")"
]
| Get the instance with the specified index.
Returns:
The corresponding instance. | [
"Get",
"the",
"instance",
"with",
"the",
"specified",
"index",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L60-L73 |
ampl/amplpy | amplpy/entity.py | Entity.find | def find(self, *index):
"""
Searches the current entity for an instance with the specified index.
Returns:
The wanted instance if found, otherwise it returns `None`.
"""
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, list)):
index = index[0]
it = self._impl.find(Tuple(index)._impl)
if it == self._impl.end():
return None
else:
return self.wrapFunction(it) | python | def find(self, *index):
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, list)):
index = index[0]
it = self._impl.find(Tuple(index)._impl)
if it == self._impl.end():
return None
else:
return self.wrapFunction(it) | [
"def",
"find",
"(",
"self",
",",
"*",
"index",
")",
":",
"assert",
"self",
".",
"wrapFunction",
"is",
"not",
"None",
"if",
"len",
"(",
"index",
")",
"==",
"1",
"and",
"isinstance",
"(",
"index",
"[",
"0",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"index",
"=",
"index",
"[",
"0",
"]",
"it",
"=",
"self",
".",
"_impl",
".",
"find",
"(",
"Tuple",
"(",
"index",
")",
".",
"_impl",
")",
"if",
"it",
"==",
"self",
".",
"_impl",
".",
"end",
"(",
")",
":",
"return",
"None",
"else",
":",
"return",
"self",
".",
"wrapFunction",
"(",
"it",
")"
]
| Searches the current entity for an instance with the specified index.
Returns:
The wanted instance if found, otherwise it returns `None`. | [
"Searches",
"the",
"current",
"entity",
"for",
"an",
"instance",
"with",
"the",
"specified",
"index",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L75-L89 |
ampl/amplpy | amplpy/entity.py | Entity.getValues | def getValues(self, suffixes=None):
"""
If a list of suffixes is provided, get the specified suffixes value for
all instances. Otherwise, get all the principal values of this entity.
The specific returned value depends on the type of entity (see list
below). For:
- Variables and Objectives it returns the suffix ``val``.
- Parameters it returns their values.
- Constraints it returns the suffix ``dual``.
- Sets it returns all the members of the set. Note that it does not
apply to indexed sets. See :func:`~amplpy.Set.getValues`.
Retruns:
A :class:`~amplpy.DataFrame` containing the values for all
instances.
"""
if suffixes is None:
return DataFrame._fromDataFrameRef(self._impl.getValues())
else:
suffixes = list(map(str, suffixes))
return DataFrame._fromDataFrameRef(
self._impl.getValuesLst(suffixes, len(suffixes))
) | python | def getValues(self, suffixes=None):
if suffixes is None:
return DataFrame._fromDataFrameRef(self._impl.getValues())
else:
suffixes = list(map(str, suffixes))
return DataFrame._fromDataFrameRef(
self._impl.getValuesLst(suffixes, len(suffixes))
) | [
"def",
"getValues",
"(",
"self",
",",
"suffixes",
"=",
"None",
")",
":",
"if",
"suffixes",
"is",
"None",
":",
"return",
"DataFrame",
".",
"_fromDataFrameRef",
"(",
"self",
".",
"_impl",
".",
"getValues",
"(",
")",
")",
"else",
":",
"suffixes",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"suffixes",
")",
")",
"return",
"DataFrame",
".",
"_fromDataFrameRef",
"(",
"self",
".",
"_impl",
".",
"getValuesLst",
"(",
"suffixes",
",",
"len",
"(",
"suffixes",
")",
")",
")"
]
| If a list of suffixes is provided, get the specified suffixes value for
all instances. Otherwise, get all the principal values of this entity.
The specific returned value depends on the type of entity (see list
below). For:
- Variables and Objectives it returns the suffix ``val``.
- Parameters it returns their values.
- Constraints it returns the suffix ``dual``.
- Sets it returns all the members of the set. Note that it does not
apply to indexed sets. See :func:`~amplpy.Set.getValues`.
Retruns:
A :class:`~amplpy.DataFrame` containing the values for all
instances. | [
"If",
"a",
"list",
"of",
"suffixes",
"is",
"provided",
"get",
"the",
"specified",
"suffixes",
"value",
"for",
"all",
"instances",
".",
"Otherwise",
"get",
"all",
"the",
"principal",
"values",
"of",
"this",
"entity",
".",
"The",
"specific",
"returned",
"value",
"depends",
"on",
"the",
"type",
"of",
"entity",
"(",
"see",
"list",
"below",
")",
".",
"For",
":"
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L152-L175 |
ampl/amplpy | amplpy/entity.py | Entity.setValues | def setValues(self, data):
"""
Set the values of this entiy to the correponding values of a
DataFrame indexed over the same sets (or a subset).
This function assigns the values in the first data column of
the passed dataframe to the entity the function is called from.
In particular, the statement:
.. code-block:: python
x.setValues(y.getValues())
is semantically equivalent to the AMPL statement:
.. code-block:: ampl
let {s in S} x[s] := y[s];
Args:
data: The data to set the entity to.
"""
if isinstance(data, DataFrame):
self._impl.setValuesDf(data._impl)
else:
if pd is not None and isinstance(data, (pd.DataFrame, pd.Series)):
df = DataFrame.fromPandas(data)
self._impl.setValuesDf(df._impl)
return
raise TypeError | python | def setValues(self, data):
if isinstance(data, DataFrame):
self._impl.setValuesDf(data._impl)
else:
if pd is not None and isinstance(data, (pd.DataFrame, pd.Series)):
df = DataFrame.fromPandas(data)
self._impl.setValuesDf(df._impl)
return
raise TypeError | [
"def",
"setValues",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"DataFrame",
")",
":",
"self",
".",
"_impl",
".",
"setValuesDf",
"(",
"data",
".",
"_impl",
")",
"else",
":",
"if",
"pd",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"data",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"df",
"=",
"DataFrame",
".",
"fromPandas",
"(",
"data",
")",
"self",
".",
"_impl",
".",
"setValuesDf",
"(",
"df",
".",
"_impl",
")",
"return",
"raise",
"TypeError"
]
| Set the values of this entiy to the correponding values of a
DataFrame indexed over the same sets (or a subset).
This function assigns the values in the first data column of
the passed dataframe to the entity the function is called from.
In particular, the statement:
.. code-block:: python
x.setValues(y.getValues())
is semantically equivalent to the AMPL statement:
.. code-block:: ampl
let {s in S} x[s] := y[s];
Args:
data: The data to set the entity to. | [
"Set",
"the",
"values",
"of",
"this",
"entiy",
"to",
"the",
"correponding",
"values",
"of",
"a",
"DataFrame",
"indexed",
"over",
"the",
"same",
"sets",
"(",
"or",
"a",
"subset",
")",
".",
"This",
"function",
"assigns",
"the",
"values",
"in",
"the",
"first",
"data",
"column",
"of",
"the",
"passed",
"dataframe",
"to",
"the",
"entity",
"the",
"function",
"is",
"called",
"from",
".",
"In",
"particular",
"the",
"statement",
":"
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L177-L205 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.addRow | def addRow(self, *value):
"""
Add a row to the DataFrame. The size of the tuple must be equal to the
total number of columns in the dataframe.
Args:
value: A single argument with a tuple containing all the values
for the row to be added, or multiple arguments with the values for
each column.
"""
if len(value) == 1 and isinstance(value[0], (tuple, list)):
value = value[0]
assert len(value) == self.getNumCols()
self._impl.addRow(Tuple(value)._impl) | python | def addRow(self, *value):
if len(value) == 1 and isinstance(value[0], (tuple, list)):
value = value[0]
assert len(value) == self.getNumCols()
self._impl.addRow(Tuple(value)._impl) | [
"def",
"addRow",
"(",
"self",
",",
"*",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"==",
"1",
"and",
"isinstance",
"(",
"value",
"[",
"0",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"value",
"=",
"value",
"[",
"0",
"]",
"assert",
"len",
"(",
"value",
")",
"==",
"self",
".",
"getNumCols",
"(",
")",
"self",
".",
"_impl",
".",
"addRow",
"(",
"Tuple",
"(",
"value",
")",
".",
"_impl",
")"
]
| Add a row to the DataFrame. The size of the tuple must be equal to the
total number of columns in the dataframe.
Args:
value: A single argument with a tuple containing all the values
for the row to be added, or multiple arguments with the values for
each column. | [
"Add",
"a",
"row",
"to",
"the",
"DataFrame",
".",
"The",
"size",
"of",
"the",
"tuple",
"must",
"be",
"equal",
"to",
"the",
"total",
"number",
"of",
"columns",
"in",
"the",
"dataframe",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L155-L168 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.addColumn | def addColumn(self, header, values=[]):
"""
Add a new column with the corresponding header and values to the
dataframe.
Args:
header: The name of the new column.
values: A list of size :func:`~amplpy.DataFrame.getNumRows` with
all the values of the new column.
"""
if len(values) == 0:
self._impl.addColumn(header)
else:
assert len(values) == self.getNumRows()
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.addColumnStr(header, values)
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.addColumnDbl(header, values)
else:
raise NotImplementedError | python | def addColumn(self, header, values=[]):
if len(values) == 0:
self._impl.addColumn(header)
else:
assert len(values) == self.getNumRows()
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.addColumnStr(header, values)
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.addColumnDbl(header, values)
else:
raise NotImplementedError | [
"def",
"addColumn",
"(",
"self",
",",
"header",
",",
"values",
"=",
"[",
"]",
")",
":",
"if",
"len",
"(",
"values",
")",
"==",
"0",
":",
"self",
".",
"_impl",
".",
"addColumn",
"(",
"header",
")",
"else",
":",
"assert",
"len",
"(",
"values",
")",
"==",
"self",
".",
"getNumRows",
"(",
")",
"if",
"any",
"(",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"addColumnStr",
"(",
"header",
",",
"values",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"Real",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"float",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"addColumnDbl",
"(",
"header",
",",
"values",
")",
"else",
":",
"raise",
"NotImplementedError"
]
| Add a new column with the corresponding header and values to the
dataframe.
Args:
header: The name of the new column.
values: A list of size :func:`~amplpy.DataFrame.getNumRows` with
all the values of the new column. | [
"Add",
"a",
"new",
"column",
"with",
"the",
"corresponding",
"header",
"and",
"values",
"to",
"the",
"dataframe",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L170-L192 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.setColumn | def setColumn(self, header, values):
"""
Set the values of a column.
Args:
header: The header of the column to be set.
values: The values to set.
"""
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setColumnStr(header, values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setColumnDbl(header, values, len(values))
else:
print(values)
raise NotImplementedError | python | def setColumn(self, header, values):
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setColumnStr(header, values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setColumnDbl(header, values, len(values))
else:
print(values)
raise NotImplementedError | [
"def",
"setColumn",
"(",
"self",
",",
"header",
",",
"values",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setColumnStr",
"(",
"header",
",",
"values",
",",
"len",
"(",
"values",
")",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"Real",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"float",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setColumnDbl",
"(",
"header",
",",
"values",
",",
"len",
"(",
"values",
")",
")",
"else",
":",
"print",
"(",
"values",
")",
"raise",
"NotImplementedError"
]
| Set the values of a column.
Args:
header: The header of the column to be set.
values: The values to set. | [
"Set",
"the",
"values",
"of",
"a",
"column",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L203-L220 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.getRow | def getRow(self, key):
"""
Get a row by value of the indexing columns. If the index is not
specified, gets the only row of a dataframe with no indexing columns.
Args:
key: Tuple representing the index of the desired row.
Returns:
The row.
"""
return Row(self._impl.getRow(Tuple(key)._impl)) | python | def getRow(self, key):
return Row(self._impl.getRow(Tuple(key)._impl)) | [
"def",
"getRow",
"(",
"self",
",",
"key",
")",
":",
"return",
"Row",
"(",
"self",
".",
"_impl",
".",
"getRow",
"(",
"Tuple",
"(",
"key",
")",
".",
"_impl",
")",
")"
]
| Get a row by value of the indexing columns. If the index is not
specified, gets the only row of a dataframe with no indexing columns.
Args:
key: Tuple representing the index of the desired row.
Returns:
The row. | [
"Get",
"a",
"row",
"by",
"value",
"of",
"the",
"indexing",
"columns",
".",
"If",
"the",
"index",
"is",
"not",
"specified",
"gets",
"the",
"only",
"row",
"of",
"a",
"dataframe",
"with",
"no",
"indexing",
"columns",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L222-L233 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.getRowByIndex | def getRowByIndex(self, index):
"""
Get row by numeric index.
Args:
index: Zero-based index of the row to get.
Returns:
The corresponding row.
"""
assert isinstance(index, int)
return Row(self._impl.getRowByIndex(index)) | python | def getRowByIndex(self, index):
assert isinstance(index, int)
return Row(self._impl.getRowByIndex(index)) | [
"def",
"getRowByIndex",
"(",
"self",
",",
"index",
")",
":",
"assert",
"isinstance",
"(",
"index",
",",
"int",
")",
"return",
"Row",
"(",
"self",
".",
"_impl",
".",
"getRowByIndex",
"(",
"index",
")",
")"
]
| Get row by numeric index.
Args:
index: Zero-based index of the row to get.
Returns:
The corresponding row. | [
"Get",
"row",
"by",
"numeric",
"index",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L235-L246 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.getHeaders | def getHeaders(self):
"""
Get the headers of this DataFrame.
Returns:
The headers of this DataFrame.
"""
headers = self._impl.getHeaders()
return tuple(
headers.getIndex(i) for i in range(self._impl.getNumCols())
) | python | def getHeaders(self):
headers = self._impl.getHeaders()
return tuple(
headers.getIndex(i) for i in range(self._impl.getNumCols())
) | [
"def",
"getHeaders",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"_impl",
".",
"getHeaders",
"(",
")",
"return",
"tuple",
"(",
"headers",
".",
"getIndex",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_impl",
".",
"getNumCols",
"(",
")",
")",
")"
]
| Get the headers of this DataFrame.
Returns:
The headers of this DataFrame. | [
"Get",
"the",
"headers",
"of",
"this",
"DataFrame",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L248-L258 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.setValues | def setValues(self, values):
"""
Set the values of a DataFrame from a dictionary.
Args:
values: Dictionary with the values to set.
"""
ncols = self.getNumCols()
nindices = self.getNumIndices()
for key, value in values.items():
key = Utils.convToList(key)
assert len(key) == nindices
value = Utils.convToList(value)
assert len(value) == ncols-nindices
self.addRow(key + value) | python | def setValues(self, values):
ncols = self.getNumCols()
nindices = self.getNumIndices()
for key, value in values.items():
key = Utils.convToList(key)
assert len(key) == nindices
value = Utils.convToList(value)
assert len(value) == ncols-nindices
self.addRow(key + value) | [
"def",
"setValues",
"(",
"self",
",",
"values",
")",
":",
"ncols",
"=",
"self",
".",
"getNumCols",
"(",
")",
"nindices",
"=",
"self",
".",
"getNumIndices",
"(",
")",
"for",
"key",
",",
"value",
"in",
"values",
".",
"items",
"(",
")",
":",
"key",
"=",
"Utils",
".",
"convToList",
"(",
"key",
")",
"assert",
"len",
"(",
"key",
")",
"==",
"nindices",
"value",
"=",
"Utils",
".",
"convToList",
"(",
"value",
")",
"assert",
"len",
"(",
"value",
")",
"==",
"ncols",
"-",
"nindices",
"self",
".",
"addRow",
"(",
"key",
"+",
"value",
")"
]
| Set the values of a DataFrame from a dictionary.
Args:
values: Dictionary with the values to set. | [
"Set",
"the",
"values",
"of",
"a",
"DataFrame",
"from",
"a",
"dictionary",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L260-L274 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.toDict | def toDict(self):
"""
Return a dictionary with the DataFrame data.
"""
d = {}
nindices = self.getNumIndices()
for i in range(self.getNumRows()):
row = list(self.getRowByIndex(i))
if nindices > 1:
key = tuple(row[:nindices])
elif nindices == 1:
key = row[0]
else:
key = None
if len(row) - nindices == 0:
d[key] = None
elif len(row) - nindices == 1:
d[key] = row[nindices]
else:
d[key] = tuple(row[nindices:])
return d | python | def toDict(self):
d = {}
nindices = self.getNumIndices()
for i in range(self.getNumRows()):
row = list(self.getRowByIndex(i))
if nindices > 1:
key = tuple(row[:nindices])
elif nindices == 1:
key = row[0]
else:
key = None
if len(row) - nindices == 0:
d[key] = None
elif len(row) - nindices == 1:
d[key] = row[nindices]
else:
d[key] = tuple(row[nindices:])
return d | [
"def",
"toDict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"nindices",
"=",
"self",
".",
"getNumIndices",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"getNumRows",
"(",
")",
")",
":",
"row",
"=",
"list",
"(",
"self",
".",
"getRowByIndex",
"(",
"i",
")",
")",
"if",
"nindices",
">",
"1",
":",
"key",
"=",
"tuple",
"(",
"row",
"[",
":",
"nindices",
"]",
")",
"elif",
"nindices",
"==",
"1",
":",
"key",
"=",
"row",
"[",
"0",
"]",
"else",
":",
"key",
"=",
"None",
"if",
"len",
"(",
"row",
")",
"-",
"nindices",
"==",
"0",
":",
"d",
"[",
"key",
"]",
"=",
"None",
"elif",
"len",
"(",
"row",
")",
"-",
"nindices",
"==",
"1",
":",
"d",
"[",
"key",
"]",
"=",
"row",
"[",
"nindices",
"]",
"else",
":",
"d",
"[",
"key",
"]",
"=",
"tuple",
"(",
"row",
"[",
"nindices",
":",
"]",
")",
"return",
"d"
]
| Return a dictionary with the DataFrame data. | [
"Return",
"a",
"dictionary",
"with",
"the",
"DataFrame",
"data",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L276-L296 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.toList | def toList(self):
"""
Return a list with the DataFrame data.
"""
if self.getNumCols() > 1:
return [
tuple(self.getRowByIndex(i))
for i in range(self.getNumRows())
]
else:
return [
self.getRowByIndex(i)[0]
for i in range(self.getNumRows())
] | python | def toList(self):
if self.getNumCols() > 1:
return [
tuple(self.getRowByIndex(i))
for i in range(self.getNumRows())
]
else:
return [
self.getRowByIndex(i)[0]
for i in range(self.getNumRows())
] | [
"def",
"toList",
"(",
"self",
")",
":",
"if",
"self",
".",
"getNumCols",
"(",
")",
">",
"1",
":",
"return",
"[",
"tuple",
"(",
"self",
".",
"getRowByIndex",
"(",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"getNumRows",
"(",
")",
")",
"]",
"else",
":",
"return",
"[",
"self",
".",
"getRowByIndex",
"(",
"i",
")",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"getNumRows",
"(",
")",
")",
"]"
]
| Return a list with the DataFrame data. | [
"Return",
"a",
"list",
"with",
"the",
"DataFrame",
"data",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L298-L311 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.toPandas | def toPandas(self):
"""
Return a pandas DataFrame with the DataFrame data.
"""
assert pd is not None
nindices = self.getNumIndices()
headers = self.getHeaders()
columns = {
header: list(self.getColumn(header))
for header in headers[nindices:]
}
index = zip(*[
list(self.getColumn(header))
for header in headers[:nindices]
])
index = [key if len(key) > 1 else key[0] for key in index]
if index == []:
return pd.DataFrame(columns, index=None)
else:
return pd.DataFrame(columns, index=index) | python | def toPandas(self):
assert pd is not None
nindices = self.getNumIndices()
headers = self.getHeaders()
columns = {
header: list(self.getColumn(header))
for header in headers[nindices:]
}
index = zip(*[
list(self.getColumn(header))
for header in headers[:nindices]
])
index = [key if len(key) > 1 else key[0] for key in index]
if index == []:
return pd.DataFrame(columns, index=None)
else:
return pd.DataFrame(columns, index=index) | [
"def",
"toPandas",
"(",
"self",
")",
":",
"assert",
"pd",
"is",
"not",
"None",
"nindices",
"=",
"self",
".",
"getNumIndices",
"(",
")",
"headers",
"=",
"self",
".",
"getHeaders",
"(",
")",
"columns",
"=",
"{",
"header",
":",
"list",
"(",
"self",
".",
"getColumn",
"(",
"header",
")",
")",
"for",
"header",
"in",
"headers",
"[",
"nindices",
":",
"]",
"}",
"index",
"=",
"zip",
"(",
"*",
"[",
"list",
"(",
"self",
".",
"getColumn",
"(",
"header",
")",
")",
"for",
"header",
"in",
"headers",
"[",
":",
"nindices",
"]",
"]",
")",
"index",
"=",
"[",
"key",
"if",
"len",
"(",
"key",
")",
">",
"1",
"else",
"key",
"[",
"0",
"]",
"for",
"key",
"in",
"index",
"]",
"if",
"index",
"==",
"[",
"]",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"columns",
",",
"index",
"=",
"None",
")",
"else",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"columns",
",",
"index",
"=",
"index",
")"
]
| Return a pandas DataFrame with the DataFrame data. | [
"Return",
"a",
"pandas",
"DataFrame",
"with",
"the",
"DataFrame",
"data",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L313-L332 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.fromPandas | def fromPandas(cls, df):
"""
Create a :class:`~amplpy.DataFrame` from a pandas DataFrame.
"""
assert pd is not None
if isinstance(df, pd.Series):
df = pd.DataFrame(df)
else:
assert isinstance(df, pd.DataFrame)
keys = [
key if isinstance(key, tuple) else (key,)
for key in df.index.tolist()
]
index = [
('index{}'.format(i), cindex)
for i, cindex in enumerate(zip(*keys))
]
columns = [
(str(cname), df[cname].tolist())
for cname in df.columns.tolist()
]
return cls(index=index, columns=columns) | python | def fromPandas(cls, df):
assert pd is not None
if isinstance(df, pd.Series):
df = pd.DataFrame(df)
else:
assert isinstance(df, pd.DataFrame)
keys = [
key if isinstance(key, tuple) else (key,)
for key in df.index.tolist()
]
index = [
('index{}'.format(i), cindex)
for i, cindex in enumerate(zip(*keys))
]
columns = [
(str(cname), df[cname].tolist())
for cname in df.columns.tolist()
]
return cls(index=index, columns=columns) | [
"def",
"fromPandas",
"(",
"cls",
",",
"df",
")",
":",
"assert",
"pd",
"is",
"not",
"None",
"if",
"isinstance",
"(",
"df",
",",
"pd",
".",
"Series",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"df",
")",
"else",
":",
"assert",
"isinstance",
"(",
"df",
",",
"pd",
".",
"DataFrame",
")",
"keys",
"=",
"[",
"key",
"if",
"isinstance",
"(",
"key",
",",
"tuple",
")",
"else",
"(",
"key",
",",
")",
"for",
"key",
"in",
"df",
".",
"index",
".",
"tolist",
"(",
")",
"]",
"index",
"=",
"[",
"(",
"'index{}'",
".",
"format",
"(",
"i",
")",
",",
"cindex",
")",
"for",
"i",
",",
"cindex",
"in",
"enumerate",
"(",
"zip",
"(",
"*",
"keys",
")",
")",
"]",
"columns",
"=",
"[",
"(",
"str",
"(",
"cname",
")",
",",
"df",
"[",
"cname",
"]",
".",
"tolist",
"(",
")",
")",
"for",
"cname",
"in",
"df",
".",
"columns",
".",
"tolist",
"(",
")",
"]",
"return",
"cls",
"(",
"index",
"=",
"index",
",",
"columns",
"=",
"columns",
")"
]
| Create a :class:`~amplpy.DataFrame` from a pandas DataFrame. | [
"Create",
"a",
":",
"class",
":",
"~amplpy",
".",
"DataFrame",
"from",
"a",
"pandas",
"DataFrame",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L335-L356 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.fromNumpy | def fromNumpy(cls, data):
"""
Create a :class:`~amplpy.DataFrame` from a numpy array or matrix.
"""
assert np is not None
if isinstance(data, np.ndarray):
index = []
if len(data.shape) == 1:
columns = [('value', data.tolist())]
elif len(data.shape) == 2:
columns = [
('c{}'.format(i), col)
for i, col in enumerate(zip(*data.tolist()))
]
else:
raise TypeError
else:
raise TypeError
return cls(index=index, columns=columns) | python | def fromNumpy(cls, data):
assert np is not None
if isinstance(data, np.ndarray):
index = []
if len(data.shape) == 1:
columns = [('value', data.tolist())]
elif len(data.shape) == 2:
columns = [
('c{}'.format(i), col)
for i, col in enumerate(zip(*data.tolist()))
]
else:
raise TypeError
else:
raise TypeError
return cls(index=index, columns=columns) | [
"def",
"fromNumpy",
"(",
"cls",
",",
"data",
")",
":",
"assert",
"np",
"is",
"not",
"None",
"if",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
":",
"index",
"=",
"[",
"]",
"if",
"len",
"(",
"data",
".",
"shape",
")",
"==",
"1",
":",
"columns",
"=",
"[",
"(",
"'value'",
",",
"data",
".",
"tolist",
"(",
")",
")",
"]",
"elif",
"len",
"(",
"data",
".",
"shape",
")",
"==",
"2",
":",
"columns",
"=",
"[",
"(",
"'c{}'",
".",
"format",
"(",
"i",
")",
",",
"col",
")",
"for",
"i",
",",
"col",
"in",
"enumerate",
"(",
"zip",
"(",
"*",
"data",
".",
"tolist",
"(",
")",
")",
")",
"]",
"else",
":",
"raise",
"TypeError",
"else",
":",
"raise",
"TypeError",
"return",
"cls",
"(",
"index",
"=",
"index",
",",
"columns",
"=",
"columns",
")"
]
| Create a :class:`~amplpy.DataFrame` from a numpy array or matrix. | [
"Create",
"a",
":",
"class",
":",
"~amplpy",
".",
"DataFrame",
"from",
"a",
"numpy",
"array",
"or",
"matrix",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L359-L377 |
ampl/amplpy | amplpy/parameter.py | Parameter.set | def set(self, *args):
"""
Set the value of a single instance of this parameter.
Args:
args: value if the parameter is scalar, index and value
otherwise.
Raises:
RuntimeError: If the entity has been deleted in the underlying
AMPL.
TypeError: If the parameter is not scalar and the index is not
provided.
"""
assert len(args) in (1, 2)
if len(args) == 1:
value = args[0]
self._impl.set(value)
else:
index, value = args
if isinstance(value, Real):
self._impl.setTplDbl(Tuple(index)._impl, value)
elif isinstance(value, basestring):
self._impl.setTplStr(Tuple(index)._impl, value)
else:
raise TypeError | python | def set(self, *args):
assert len(args) in (1, 2)
if len(args) == 1:
value = args[0]
self._impl.set(value)
else:
index, value = args
if isinstance(value, Real):
self._impl.setTplDbl(Tuple(index)._impl, value)
elif isinstance(value, basestring):
self._impl.setTplStr(Tuple(index)._impl, value)
else:
raise TypeError | [
"def",
"set",
"(",
"self",
",",
"*",
"args",
")",
":",
"assert",
"len",
"(",
"args",
")",
"in",
"(",
"1",
",",
"2",
")",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"value",
"=",
"args",
"[",
"0",
"]",
"self",
".",
"_impl",
".",
"set",
"(",
"value",
")",
"else",
":",
"index",
",",
"value",
"=",
"args",
"if",
"isinstance",
"(",
"value",
",",
"Real",
")",
":",
"self",
".",
"_impl",
".",
"setTplDbl",
"(",
"Tuple",
"(",
"index",
")",
".",
"_impl",
",",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"self",
".",
"_impl",
".",
"setTplStr",
"(",
"Tuple",
"(",
"index",
")",
".",
"_impl",
",",
"value",
")",
"else",
":",
"raise",
"TypeError"
]
| Set the value of a single instance of this parameter.
Args:
args: value if the parameter is scalar, index and value
otherwise.
Raises:
RuntimeError: If the entity has been deleted in the underlying
AMPL.
TypeError: If the parameter is not scalar and the index is not
provided. | [
"Set",
"the",
"value",
"of",
"a",
"single",
"instance",
"of",
"this",
"parameter",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/parameter.py#L70-L96 |
ampl/amplpy | amplpy/parameter.py | Parameter.setValues | def setValues(self, values):
"""
Assign the values (string or float) to the parameter instances with the
specified indices, equivalent to the AMPL code:
.. code-block:: ampl
let {i in indices} par[i] := values[i];
Args:
values: list, dictionary or :class:`~amplpy.DataFrame` with the
indices and the values to be set.
Raises:
TypeError: If called on a scalar parameter.
"""
if isinstance(values, dict):
indices, values = list(zip(*values.items()))
indices = Utils.toTupleArray(indices)
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setValuesTaStr(indices, values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setValuesTaDbl(indices, values, len(values))
else:
raise TypeError
elif isinstance(values, (list, tuple)):
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setValuesStr(values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setValuesDbl(values, len(values))
else:
raise TypeError
else:
if np is not None and isinstance(values, np.ndarray):
self.setValues(DataFrame.fromNumpy(values).toList())
return
Entity.setValues(self, values) | python | def setValues(self, values):
if isinstance(values, dict):
indices, values = list(zip(*values.items()))
indices = Utils.toTupleArray(indices)
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setValuesTaStr(indices, values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setValuesTaDbl(indices, values, len(values))
else:
raise TypeError
elif isinstance(values, (list, tuple)):
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setValuesStr(values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setValuesDbl(values, len(values))
else:
raise TypeError
else:
if np is not None and isinstance(values, np.ndarray):
self.setValues(DataFrame.fromNumpy(values).toList())
return
Entity.setValues(self, values) | [
"def",
"setValues",
"(",
"self",
",",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"dict",
")",
":",
"indices",
",",
"values",
"=",
"list",
"(",
"zip",
"(",
"*",
"values",
".",
"items",
"(",
")",
")",
")",
"indices",
"=",
"Utils",
".",
"toTupleArray",
"(",
"indices",
")",
"if",
"any",
"(",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setValuesTaStr",
"(",
"indices",
",",
"values",
",",
"len",
"(",
"values",
")",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"Real",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"float",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setValuesTaDbl",
"(",
"indices",
",",
"values",
",",
"len",
"(",
"values",
")",
")",
"else",
":",
"raise",
"TypeError",
"elif",
"isinstance",
"(",
"values",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setValuesStr",
"(",
"values",
",",
"len",
"(",
"values",
")",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"Real",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"float",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setValuesDbl",
"(",
"values",
",",
"len",
"(",
"values",
")",
")",
"else",
":",
"raise",
"TypeError",
"else",
":",
"if",
"np",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"values",
",",
"np",
".",
"ndarray",
")",
":",
"self",
".",
"setValues",
"(",
"DataFrame",
".",
"fromNumpy",
"(",
"values",
")",
".",
"toList",
"(",
")",
")",
"return",
"Entity",
".",
"setValues",
"(",
"self",
",",
"values",
")"
]
| Assign the values (string or float) to the parameter instances with the
specified indices, equivalent to the AMPL code:
.. code-block:: ampl
let {i in indices} par[i] := values[i];
Args:
values: list, dictionary or :class:`~amplpy.DataFrame` with the
indices and the values to be set.
Raises:
TypeError: If called on a scalar parameter. | [
"Assign",
"the",
"values",
"(",
"string",
"or",
"float",
")",
"to",
"the",
"parameter",
"instances",
"with",
"the",
"specified",
"indices",
"equivalent",
"to",
"the",
"AMPL",
"code",
":"
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/parameter.py#L98-L138 |
ampl/amplpy | amplpy/set.py | Set.setValues | def setValues(self, values):
"""
Set the tuples in this set. Valid only for non-indexed sets.
Args:
values: A list of tuples or a :class:`~amplpy.DataFrame`.
In the case of a :class:`~amplpy.DataFrame`, the number of indexing
columns of the must be equal to the arity of the set. In the case of
a list of tuples, the arity of each tuple must be equal to the arity
of the set.
For example, considering the following AMPL entities and corresponding
Python objects:
.. code-block:: ampl
set A := 1..2;
param p{i in A} := i+10;
set AA;
The following is valid:
.. code-block:: python
A, AA = ampl.getSet('A'), ampl.getSet('AA')
AA.setValues(A.getValues()) # AA has now the members {1, 2}
"""
if isinstance(values, (list, set)):
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setValuesStr(values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setValuesDbl(values, len(values))
elif all(isinstance(value, tuple) for value in values):
self._impl.setValues(Utils.toTupleArray(values), len(values))
else:
raise TypeError
else:
if np is not None and isinstance(values, np.ndarray):
self.setValues(DataFrame.fromNumpy(values).toList())
return
Entity.setValues(self, values) | python | def setValues(self, values):
if isinstance(values, (list, set)):
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setValuesStr(values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setValuesDbl(values, len(values))
elif all(isinstance(value, tuple) for value in values):
self._impl.setValues(Utils.toTupleArray(values), len(values))
else:
raise TypeError
else:
if np is not None and isinstance(values, np.ndarray):
self.setValues(DataFrame.fromNumpy(values).toList())
return
Entity.setValues(self, values) | [
"def",
"setValues",
"(",
"self",
",",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"(",
"list",
",",
"set",
")",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setValuesStr",
"(",
"values",
",",
"len",
"(",
"values",
")",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"Real",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"float",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setValuesDbl",
"(",
"values",
",",
"len",
"(",
"values",
")",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"tuple",
")",
"for",
"value",
"in",
"values",
")",
":",
"self",
".",
"_impl",
".",
"setValues",
"(",
"Utils",
".",
"toTupleArray",
"(",
"values",
")",
",",
"len",
"(",
"values",
")",
")",
"else",
":",
"raise",
"TypeError",
"else",
":",
"if",
"np",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"values",
",",
"np",
".",
"ndarray",
")",
":",
"self",
".",
"setValues",
"(",
"DataFrame",
".",
"fromNumpy",
"(",
"values",
")",
".",
"toList",
"(",
")",
")",
"return",
"Entity",
".",
"setValues",
"(",
"self",
",",
"values",
")"
]
| Set the tuples in this set. Valid only for non-indexed sets.
Args:
values: A list of tuples or a :class:`~amplpy.DataFrame`.
In the case of a :class:`~amplpy.DataFrame`, the number of indexing
columns of the must be equal to the arity of the set. In the case of
a list of tuples, the arity of each tuple must be equal to the arity
of the set.
For example, considering the following AMPL entities and corresponding
Python objects:
.. code-block:: ampl
set A := 1..2;
param p{i in A} := i+10;
set AA;
The following is valid:
.. code-block:: python
A, AA = ampl.getSet('A'), ampl.getSet('AA')
AA.setValues(A.getValues()) # AA has now the members {1, 2} | [
"Set",
"the",
"tuples",
"in",
"this",
"set",
".",
"Valid",
"only",
"for",
"non",
"-",
"indexed",
"sets",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/set.py#L80-L123 |
ampl/amplpy | amplpy/errorhandler.py | ErrorHandler.error | def error(self, amplexception):
"""
Receives notification of an error.
"""
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Error:\n{:s}'.format(msg))
raise amplexception | python | def error(self, amplexception):
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Error:\n{:s}'.format(msg))
raise amplexception | [
"def",
"error",
"(",
"self",
",",
"amplexception",
")",
":",
"msg",
"=",
"'\\t'",
"+",
"str",
"(",
"amplexception",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"print",
"(",
"'Error:\\n{:s}'",
".",
"format",
"(",
"msg",
")",
")",
"raise",
"amplexception"
]
| Receives notification of an error. | [
"Receives",
"notification",
"of",
"an",
"error",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/errorhandler.py#L18-L24 |
ampl/amplpy | amplpy/errorhandler.py | ErrorHandler.warning | def warning(self, amplexception):
"""
Receives notification of a warning.
"""
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Warning:\n{:s}'.format(msg)) | python | def warning(self, amplexception):
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Warning:\n{:s}'.format(msg)) | [
"def",
"warning",
"(",
"self",
",",
"amplexception",
")",
":",
"msg",
"=",
"'\\t'",
"+",
"str",
"(",
"amplexception",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"print",
"(",
"'Warning:\\n{:s}'",
".",
"format",
"(",
"msg",
")",
")"
]
| Receives notification of a warning. | [
"Receives",
"notification",
"of",
"a",
"warning",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/errorhandler.py#L26-L31 |
ampl/amplpy | amplpy/utils.py | register_magics | def register_magics(store_name='_ampl_cells', ampl_object=None):
"""
Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``.
Args:
store_name: Name of the store where ``%%ampl cells`` will be stored.
ampl_object: Object used to evaluate ``%%ampl_eval`` cells.
"""
from IPython.core.magic import (
Magics, magics_class, cell_magic, line_magic
)
@magics_class
class StoreAMPL(Magics):
def __init__(self, shell=None, **kwargs):
Magics.__init__(self, shell=shell, **kwargs)
self._store = []
shell.user_ns[store_name] = self._store
@cell_magic
def ampl(self, line, cell):
"""Store the cell in the store"""
self._store.append(cell)
@cell_magic
def ampl_eval(self, line, cell):
"""Evaluate the cell"""
ampl_object.eval(cell)
@line_magic
def get_ampl(self, line):
"""Retrieve the store"""
return self._store
get_ipython().register_magics(StoreAMPL) | python | def register_magics(store_name='_ampl_cells', ampl_object=None):
from IPython.core.magic import (
Magics, magics_class, cell_magic, line_magic
)
@magics_class
class StoreAMPL(Magics):
def __init__(self, shell=None, **kwargs):
Magics.__init__(self, shell=shell, **kwargs)
self._store = []
shell.user_ns[store_name] = self._store
@cell_magic
def ampl(self, line, cell):
self._store.append(cell)
@cell_magic
def ampl_eval(self, line, cell):
ampl_object.eval(cell)
@line_magic
def get_ampl(self, line):
return self._store
get_ipython().register_magics(StoreAMPL) | [
"def",
"register_magics",
"(",
"store_name",
"=",
"'_ampl_cells'",
",",
"ampl_object",
"=",
"None",
")",
":",
"from",
"IPython",
".",
"core",
".",
"magic",
"import",
"(",
"Magics",
",",
"magics_class",
",",
"cell_magic",
",",
"line_magic",
")",
"@",
"magics_class",
"class",
"StoreAMPL",
"(",
"Magics",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"shell",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"Magics",
".",
"__init__",
"(",
"self",
",",
"shell",
"=",
"shell",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_store",
"=",
"[",
"]",
"shell",
".",
"user_ns",
"[",
"store_name",
"]",
"=",
"self",
".",
"_store",
"@",
"cell_magic",
"def",
"ampl",
"(",
"self",
",",
"line",
",",
"cell",
")",
":",
"\"\"\"Store the cell in the store\"\"\"",
"self",
".",
"_store",
".",
"append",
"(",
"cell",
")",
"@",
"cell_magic",
"def",
"ampl_eval",
"(",
"self",
",",
"line",
",",
"cell",
")",
":",
"\"\"\"Evaluate the cell\"\"\"",
"ampl_object",
".",
"eval",
"(",
"cell",
")",
"@",
"line_magic",
"def",
"get_ampl",
"(",
"self",
",",
"line",
")",
":",
"\"\"\"Retrieve the store\"\"\"",
"return",
"self",
".",
"_store",
"get_ipython",
"(",
")",
".",
"register_magics",
"(",
"StoreAMPL",
")"
]
| Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``.
Args:
store_name: Name of the store where ``%%ampl cells`` will be stored.
ampl_object: Object used to evaluate ``%%ampl_eval`` cells. | [
"Register",
"jupyter",
"notebook",
"magics",
"%%ampl",
"and",
"%%ampl_eval",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/utils.py#L11-L45 |
ampl/amplpy | amplpy/variable.py | Variable.fix | def fix(self, value=None):
"""
Fix all instances of this variable to a value if provided or to
their current value otherwise.
Args:
value: value to be set.
"""
if value is None:
self._impl.fix()
else:
self._impl.fix(value) | python | def fix(self, value=None):
if value is None:
self._impl.fix()
else:
self._impl.fix(value) | [
"def",
"fix",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"self",
".",
"_impl",
".",
"fix",
"(",
")",
"else",
":",
"self",
".",
"_impl",
".",
"fix",
"(",
"value",
")"
]
| Fix all instances of this variable to a value if provided or to
their current value otherwise.
Args:
value: value to be set. | [
"Fix",
"all",
"instances",
"of",
"this",
"variable",
"to",
"a",
"value",
"if",
"provided",
"or",
"to",
"their",
"current",
"value",
"otherwise",
"."
]
| train | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/variable.py#L38-L50 |
eventable/vobject | vobject/base.py | toVName | def toVName(name, stripNum=0, upper=False):
"""
Turn a Python name into an iCalendar style name,
optionally uppercase and with characters stripped off.
"""
if upper:
name = name.upper()
if stripNum != 0:
name = name[:-stripNum]
return name.replace('_', '-') | python | def toVName(name, stripNum=0, upper=False):
if upper:
name = name.upper()
if stripNum != 0:
name = name[:-stripNum]
return name.replace('_', '-') | [
"def",
"toVName",
"(",
"name",
",",
"stripNum",
"=",
"0",
",",
"upper",
"=",
"False",
")",
":",
"if",
"upper",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"if",
"stripNum",
"!=",
"0",
":",
"name",
"=",
"name",
"[",
":",
"-",
"stripNum",
"]",
"return",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")"
]
| Turn a Python name into an iCalendar style name,
optionally uppercase and with characters stripped off. | [
"Turn",
"a",
"Python",
"name",
"into",
"an",
"iCalendar",
"style",
"name",
"optionally",
"uppercase",
"and",
"with",
"characters",
"stripped",
"off",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L261-L270 |
eventable/vobject | vobject/base.py | parseParams | def parseParams(string):
"""
Parse parameters
"""
all = params_re.findall(string)
allParameters = []
for tup in all:
paramList = [tup[0]] # tup looks like (name, valuesString)
for pair in param_values_re.findall(tup[1]):
# pair looks like ('', value) or (value, '')
if pair[0] != '':
paramList.append(pair[0])
else:
paramList.append(pair[1])
allParameters.append(paramList)
return allParameters | python | def parseParams(string):
all = params_re.findall(string)
allParameters = []
for tup in all:
paramList = [tup[0]]
for pair in param_values_re.findall(tup[1]):
if pair[0] != '':
paramList.append(pair[0])
else:
paramList.append(pair[1])
allParameters.append(paramList)
return allParameters | [
"def",
"parseParams",
"(",
"string",
")",
":",
"all",
"=",
"params_re",
".",
"findall",
"(",
"string",
")",
"allParameters",
"=",
"[",
"]",
"for",
"tup",
"in",
"all",
":",
"paramList",
"=",
"[",
"tup",
"[",
"0",
"]",
"]",
"# tup looks like (name, valuesString)",
"for",
"pair",
"in",
"param_values_re",
".",
"findall",
"(",
"tup",
"[",
"1",
"]",
")",
":",
"# pair looks like ('', value) or (value, '')",
"if",
"pair",
"[",
"0",
"]",
"!=",
"''",
":",
"paramList",
".",
"append",
"(",
"pair",
"[",
"0",
"]",
")",
"else",
":",
"paramList",
".",
"append",
"(",
"pair",
"[",
"1",
"]",
")",
"allParameters",
".",
"append",
"(",
"paramList",
")",
"return",
"allParameters"
]
| Parse parameters | [
"Parse",
"parameters"
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L789-L804 |
eventable/vobject | vobject/base.py | parseLine | def parseLine(line, lineNumber=None):
"""
Parse line
"""
match = line_re.match(line)
if match is None:
raise ParseError("Failed to parse line: {0!s}".format(line), lineNumber)
# Underscores are replaced with dash to work around Lotus Notes
return (match.group('name').replace('_', '-'),
parseParams(match.group('params')),
match.group('value'), match.group('group')) | python | def parseLine(line, lineNumber=None):
match = line_re.match(line)
if match is None:
raise ParseError("Failed to parse line: {0!s}".format(line), lineNumber)
return (match.group('name').replace('_', '-'),
parseParams(match.group('params')),
match.group('value'), match.group('group')) | [
"def",
"parseLine",
"(",
"line",
",",
"lineNumber",
"=",
"None",
")",
":",
"match",
"=",
"line_re",
".",
"match",
"(",
"line",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ParseError",
"(",
"\"Failed to parse line: {0!s}\"",
".",
"format",
"(",
"line",
")",
",",
"lineNumber",
")",
"# Underscores are replaced with dash to work around Lotus Notes",
"return",
"(",
"match",
".",
"group",
"(",
"'name'",
")",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
",",
"parseParams",
"(",
"match",
".",
"group",
"(",
"'params'",
")",
")",
",",
"match",
".",
"group",
"(",
"'value'",
")",
",",
"match",
".",
"group",
"(",
"'group'",
")",
")"
]
| Parse line | [
"Parse",
"line"
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L807-L817 |
eventable/vobject | vobject/base.py | dquoteEscape | def dquoteEscape(param):
"""
Return param, or "param" if ',' or ';' or ':' is in param.
"""
if param.find('"') >= 0:
raise VObjectError("Double quotes aren't allowed in parameter values.")
for char in ',;:':
if param.find(char) >= 0:
return '"' + param + '"'
return param | python | def dquoteEscape(param):
if param.find('"') >= 0:
raise VObjectError("Double quotes aren't allowed in parameter values.")
for char in ',;:':
if param.find(char) >= 0:
return '"' + param + '"'
return param | [
"def",
"dquoteEscape",
"(",
"param",
")",
":",
"if",
"param",
".",
"find",
"(",
"'\"'",
")",
">=",
"0",
":",
"raise",
"VObjectError",
"(",
"\"Double quotes aren't allowed in parameter values.\"",
")",
"for",
"char",
"in",
"',;:'",
":",
"if",
"param",
".",
"find",
"(",
"char",
")",
">=",
"0",
":",
"return",
"'\"'",
"+",
"param",
"+",
"'\"'",
"return",
"param"
]
| Return param, or "param" if ',' or ';' or ':' is in param. | [
"Return",
"param",
"or",
"param",
"if",
"or",
";",
"or",
":",
"is",
"in",
"param",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L929-L938 |
eventable/vobject | vobject/base.py | readComponents | def readComponents(streamOrString, validate=False, transform=True,
ignoreUnreadable=False, allowQP=False):
"""
Generate one Component at a time from a stream.
"""
if isinstance(streamOrString, basestring):
stream = six.StringIO(streamOrString)
else:
stream = streamOrString
try:
stack = Stack()
versionLine = None
n = 0
for line, n in getLogicalLines(stream, allowQP):
if ignoreUnreadable:
try:
vline = textLineToContentLine(line, n)
except VObjectError as e:
if e.lineNumber is not None:
msg = "Skipped line {lineNumber}, message: {msg}"
else:
msg = "Skipped a line, message: {msg}"
logger.error(msg.format(**{'lineNumber': e.lineNumber, 'msg': str(e)}))
continue
else:
vline = textLineToContentLine(line, n)
if vline.name == "VERSION":
versionLine = vline
stack.modifyTop(vline)
elif vline.name == "BEGIN":
stack.push(Component(vline.value, group=vline.group))
elif vline.name == "PROFILE":
if not stack.top():
stack.push(Component())
stack.top().setProfile(vline.value)
elif vline.name == "END":
if len(stack) == 0:
err = "Attempted to end the {0} component but it was never opened"
raise ParseError(err.format(vline.value), n)
if vline.value.upper() == stack.topName(): # START matches END
if len(stack) == 1:
component = stack.pop()
if versionLine is not None:
component.setBehaviorFromVersionLine(versionLine)
else:
behavior = getBehavior(component.name)
if behavior:
component.setBehavior(behavior)
if validate:
component.validate(raiseException=True)
if transform:
component.transformChildrenToNative()
yield component # EXIT POINT
else:
stack.modifyTop(stack.pop())
else:
err = "{0} component wasn't closed"
raise ParseError(err.format(stack.topName()), n)
else:
stack.modifyTop(vline) # not a START or END line
if stack.top():
if stack.topName() is None:
logger.warning("Top level component was never named")
elif stack.top().useBegin:
raise ParseError("Component {0!s} was never closed".format(
(stack.topName())), n)
yield stack.pop()
except ParseError as e:
e.input = streamOrString
raise | python | def readComponents(streamOrString, validate=False, transform=True,
ignoreUnreadable=False, allowQP=False):
if isinstance(streamOrString, basestring):
stream = six.StringIO(streamOrString)
else:
stream = streamOrString
try:
stack = Stack()
versionLine = None
n = 0
for line, n in getLogicalLines(stream, allowQP):
if ignoreUnreadable:
try:
vline = textLineToContentLine(line, n)
except VObjectError as e:
if e.lineNumber is not None:
msg = "Skipped line {lineNumber}, message: {msg}"
else:
msg = "Skipped a line, message: {msg}"
logger.error(msg.format(**{'lineNumber': e.lineNumber, 'msg': str(e)}))
continue
else:
vline = textLineToContentLine(line, n)
if vline.name == "VERSION":
versionLine = vline
stack.modifyTop(vline)
elif vline.name == "BEGIN":
stack.push(Component(vline.value, group=vline.group))
elif vline.name == "PROFILE":
if not stack.top():
stack.push(Component())
stack.top().setProfile(vline.value)
elif vline.name == "END":
if len(stack) == 0:
err = "Attempted to end the {0} component but it was never opened"
raise ParseError(err.format(vline.value), n)
if vline.value.upper() == stack.topName():
if len(stack) == 1:
component = stack.pop()
if versionLine is not None:
component.setBehaviorFromVersionLine(versionLine)
else:
behavior = getBehavior(component.name)
if behavior:
component.setBehavior(behavior)
if validate:
component.validate(raiseException=True)
if transform:
component.transformChildrenToNative()
yield component
else:
stack.modifyTop(stack.pop())
else:
err = "{0} component wasn't closed"
raise ParseError(err.format(stack.topName()), n)
else:
stack.modifyTop(vline)
if stack.top():
if stack.topName() is None:
logger.warning("Top level component was never named")
elif stack.top().useBegin:
raise ParseError("Component {0!s} was never closed".format(
(stack.topName())), n)
yield stack.pop()
except ParseError as e:
e.input = streamOrString
raise | [
"def",
"readComponents",
"(",
"streamOrString",
",",
"validate",
"=",
"False",
",",
"transform",
"=",
"True",
",",
"ignoreUnreadable",
"=",
"False",
",",
"allowQP",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"streamOrString",
",",
"basestring",
")",
":",
"stream",
"=",
"six",
".",
"StringIO",
"(",
"streamOrString",
")",
"else",
":",
"stream",
"=",
"streamOrString",
"try",
":",
"stack",
"=",
"Stack",
"(",
")",
"versionLine",
"=",
"None",
"n",
"=",
"0",
"for",
"line",
",",
"n",
"in",
"getLogicalLines",
"(",
"stream",
",",
"allowQP",
")",
":",
"if",
"ignoreUnreadable",
":",
"try",
":",
"vline",
"=",
"textLineToContentLine",
"(",
"line",
",",
"n",
")",
"except",
"VObjectError",
"as",
"e",
":",
"if",
"e",
".",
"lineNumber",
"is",
"not",
"None",
":",
"msg",
"=",
"\"Skipped line {lineNumber}, message: {msg}\"",
"else",
":",
"msg",
"=",
"\"Skipped a line, message: {msg}\"",
"logger",
".",
"error",
"(",
"msg",
".",
"format",
"(",
"*",
"*",
"{",
"'lineNumber'",
":",
"e",
".",
"lineNumber",
",",
"'msg'",
":",
"str",
"(",
"e",
")",
"}",
")",
")",
"continue",
"else",
":",
"vline",
"=",
"textLineToContentLine",
"(",
"line",
",",
"n",
")",
"if",
"vline",
".",
"name",
"==",
"\"VERSION\"",
":",
"versionLine",
"=",
"vline",
"stack",
".",
"modifyTop",
"(",
"vline",
")",
"elif",
"vline",
".",
"name",
"==",
"\"BEGIN\"",
":",
"stack",
".",
"push",
"(",
"Component",
"(",
"vline",
".",
"value",
",",
"group",
"=",
"vline",
".",
"group",
")",
")",
"elif",
"vline",
".",
"name",
"==",
"\"PROFILE\"",
":",
"if",
"not",
"stack",
".",
"top",
"(",
")",
":",
"stack",
".",
"push",
"(",
"Component",
"(",
")",
")",
"stack",
".",
"top",
"(",
")",
".",
"setProfile",
"(",
"vline",
".",
"value",
")",
"elif",
"vline",
".",
"name",
"==",
"\"END\"",
":",
"if",
"len",
"(",
"stack",
")",
"==",
"0",
":",
"err",
"=",
"\"Attempted to end the {0} component but it was never opened\"",
"raise",
"ParseError",
"(",
"err",
".",
"format",
"(",
"vline",
".",
"value",
")",
",",
"n",
")",
"if",
"vline",
".",
"value",
".",
"upper",
"(",
")",
"==",
"stack",
".",
"topName",
"(",
")",
":",
"# START matches END",
"if",
"len",
"(",
"stack",
")",
"==",
"1",
":",
"component",
"=",
"stack",
".",
"pop",
"(",
")",
"if",
"versionLine",
"is",
"not",
"None",
":",
"component",
".",
"setBehaviorFromVersionLine",
"(",
"versionLine",
")",
"else",
":",
"behavior",
"=",
"getBehavior",
"(",
"component",
".",
"name",
")",
"if",
"behavior",
":",
"component",
".",
"setBehavior",
"(",
"behavior",
")",
"if",
"validate",
":",
"component",
".",
"validate",
"(",
"raiseException",
"=",
"True",
")",
"if",
"transform",
":",
"component",
".",
"transformChildrenToNative",
"(",
")",
"yield",
"component",
"# EXIT POINT",
"else",
":",
"stack",
".",
"modifyTop",
"(",
"stack",
".",
"pop",
"(",
")",
")",
"else",
":",
"err",
"=",
"\"{0} component wasn't closed\"",
"raise",
"ParseError",
"(",
"err",
".",
"format",
"(",
"stack",
".",
"topName",
"(",
")",
")",
",",
"n",
")",
"else",
":",
"stack",
".",
"modifyTop",
"(",
"vline",
")",
"# not a START or END line",
"if",
"stack",
".",
"top",
"(",
")",
":",
"if",
"stack",
".",
"topName",
"(",
")",
"is",
"None",
":",
"logger",
".",
"warning",
"(",
"\"Top level component was never named\"",
")",
"elif",
"stack",
".",
"top",
"(",
")",
".",
"useBegin",
":",
"raise",
"ParseError",
"(",
"\"Component {0!s} was never closed\"",
".",
"format",
"(",
"(",
"stack",
".",
"topName",
"(",
")",
")",
")",
",",
"n",
")",
"yield",
"stack",
".",
"pop",
"(",
")",
"except",
"ParseError",
"as",
"e",
":",
"e",
".",
"input",
"=",
"streamOrString",
"raise"
]
| Generate one Component at a time from a stream. | [
"Generate",
"one",
"Component",
"at",
"a",
"time",
"from",
"a",
"stream",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1075-L1147 |
eventable/vobject | vobject/base.py | readOne | def readOne(stream, validate=False, transform=True, ignoreUnreadable=False,
allowQP=False):
"""
Return the first component from stream.
"""
return next(readComponents(stream, validate, transform, ignoreUnreadable,
allowQP)) | python | def readOne(stream, validate=False, transform=True, ignoreUnreadable=False,
allowQP=False):
return next(readComponents(stream, validate, transform, ignoreUnreadable,
allowQP)) | [
"def",
"readOne",
"(",
"stream",
",",
"validate",
"=",
"False",
",",
"transform",
"=",
"True",
",",
"ignoreUnreadable",
"=",
"False",
",",
"allowQP",
"=",
"False",
")",
":",
"return",
"next",
"(",
"readComponents",
"(",
"stream",
",",
"validate",
",",
"transform",
",",
"ignoreUnreadable",
",",
"allowQP",
")",
")"
]
| Return the first component from stream. | [
"Return",
"the",
"first",
"component",
"from",
"stream",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1150-L1156 |
eventable/vobject | vobject/base.py | registerBehavior | def registerBehavior(behavior, name=None, default=False, id=None):
"""
Register the given behavior.
If default is True (or if this is the first version registered with this
name), the version will be the default if no id is given.
"""
if not name:
name = behavior.name.upper()
if id is None:
id = behavior.versionString
if name in __behaviorRegistry:
if default:
__behaviorRegistry[name].insert(0, (id, behavior))
else:
__behaviorRegistry[name].append((id, behavior))
else:
__behaviorRegistry[name] = [(id, behavior)] | python | def registerBehavior(behavior, name=None, default=False, id=None):
if not name:
name = behavior.name.upper()
if id is None:
id = behavior.versionString
if name in __behaviorRegistry:
if default:
__behaviorRegistry[name].insert(0, (id, behavior))
else:
__behaviorRegistry[name].append((id, behavior))
else:
__behaviorRegistry[name] = [(id, behavior)] | [
"def",
"registerBehavior",
"(",
"behavior",
",",
"name",
"=",
"None",
",",
"default",
"=",
"False",
",",
"id",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"name",
"=",
"behavior",
".",
"name",
".",
"upper",
"(",
")",
"if",
"id",
"is",
"None",
":",
"id",
"=",
"behavior",
".",
"versionString",
"if",
"name",
"in",
"__behaviorRegistry",
":",
"if",
"default",
":",
"__behaviorRegistry",
"[",
"name",
"]",
".",
"insert",
"(",
"0",
",",
"(",
"id",
",",
"behavior",
")",
")",
"else",
":",
"__behaviorRegistry",
"[",
"name",
"]",
".",
"append",
"(",
"(",
"id",
",",
"behavior",
")",
")",
"else",
":",
"__behaviorRegistry",
"[",
"name",
"]",
"=",
"[",
"(",
"id",
",",
"behavior",
")",
"]"
]
| Register the given behavior.
If default is True (or if this is the first version registered with this
name), the version will be the default if no id is given. | [
"Register",
"the",
"given",
"behavior",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1163-L1180 |
eventable/vobject | vobject/base.py | getBehavior | def getBehavior(name, id=None):
"""
Return a matching behavior if it exists, or None.
If id is None, return the default for name.
"""
name = name.upper()
if name in __behaviorRegistry:
if id:
for n, behavior in __behaviorRegistry[name]:
if n == id:
return behavior
return __behaviorRegistry[name][0][1]
return None | python | def getBehavior(name, id=None):
name = name.upper()
if name in __behaviorRegistry:
if id:
for n, behavior in __behaviorRegistry[name]:
if n == id:
return behavior
return __behaviorRegistry[name][0][1]
return None | [
"def",
"getBehavior",
"(",
"name",
",",
"id",
"=",
"None",
")",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"if",
"name",
"in",
"__behaviorRegistry",
":",
"if",
"id",
":",
"for",
"n",
",",
"behavior",
"in",
"__behaviorRegistry",
"[",
"name",
"]",
":",
"if",
"n",
"==",
"id",
":",
"return",
"behavior",
"return",
"__behaviorRegistry",
"[",
"name",
"]",
"[",
"0",
"]",
"[",
"1",
"]",
"return",
"None"
]
| Return a matching behavior if it exists, or None.
If id is None, return the default for name. | [
"Return",
"a",
"matching",
"behavior",
"if",
"it",
"exists",
"or",
"None",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1183-L1197 |
eventable/vobject | vobject/base.py | VBase.validate | def validate(self, *args, **kwds):
"""
Call the behavior's validate method, or return True.
"""
if self.behavior:
return self.behavior.validate(self, *args, **kwds)
return True | python | def validate(self, *args, **kwds):
if self.behavior:
return self.behavior.validate(self, *args, **kwds)
return True | [
"def",
"validate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"self",
".",
"behavior",
":",
"return",
"self",
".",
"behavior",
".",
"validate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"return",
"True"
]
| Call the behavior's validate method, or return True. | [
"Call",
"the",
"behavior",
"s",
"validate",
"method",
"or",
"return",
"True",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L119-L125 |
eventable/vobject | vobject/base.py | VBase.autoBehavior | def autoBehavior(self, cascade=False):
"""
Set behavior if name is in self.parentBehavior.knownChildren.
If cascade is True, unset behavior and parentBehavior for all
descendants, then recalculate behavior and parentBehavior.
"""
parentBehavior = self.parentBehavior
if parentBehavior is not None:
knownChildTup = parentBehavior.knownChildren.get(self.name, None)
if knownChildTup is not None:
behavior = getBehavior(self.name, knownChildTup[2])
if behavior is not None:
self.setBehavior(behavior, cascade)
if isinstance(self, ContentLine) and self.encoded:
self.behavior.decode(self)
elif isinstance(self, ContentLine):
self.behavior = parentBehavior.defaultBehavior
if self.encoded and self.behavior:
self.behavior.decode(self) | python | def autoBehavior(self, cascade=False):
parentBehavior = self.parentBehavior
if parentBehavior is not None:
knownChildTup = parentBehavior.knownChildren.get(self.name, None)
if knownChildTup is not None:
behavior = getBehavior(self.name, knownChildTup[2])
if behavior is not None:
self.setBehavior(behavior, cascade)
if isinstance(self, ContentLine) and self.encoded:
self.behavior.decode(self)
elif isinstance(self, ContentLine):
self.behavior = parentBehavior.defaultBehavior
if self.encoded and self.behavior:
self.behavior.decode(self) | [
"def",
"autoBehavior",
"(",
"self",
",",
"cascade",
"=",
"False",
")",
":",
"parentBehavior",
"=",
"self",
".",
"parentBehavior",
"if",
"parentBehavior",
"is",
"not",
"None",
":",
"knownChildTup",
"=",
"parentBehavior",
".",
"knownChildren",
".",
"get",
"(",
"self",
".",
"name",
",",
"None",
")",
"if",
"knownChildTup",
"is",
"not",
"None",
":",
"behavior",
"=",
"getBehavior",
"(",
"self",
".",
"name",
",",
"knownChildTup",
"[",
"2",
"]",
")",
"if",
"behavior",
"is",
"not",
"None",
":",
"self",
".",
"setBehavior",
"(",
"behavior",
",",
"cascade",
")",
"if",
"isinstance",
"(",
"self",
",",
"ContentLine",
")",
"and",
"self",
".",
"encoded",
":",
"self",
".",
"behavior",
".",
"decode",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"self",
",",
"ContentLine",
")",
":",
"self",
".",
"behavior",
"=",
"parentBehavior",
".",
"defaultBehavior",
"if",
"self",
".",
"encoded",
"and",
"self",
".",
"behavior",
":",
"self",
".",
"behavior",
".",
"decode",
"(",
"self",
")"
]
| Set behavior if name is in self.parentBehavior.knownChildren.
If cascade is True, unset behavior and parentBehavior for all
descendants, then recalculate behavior and parentBehavior. | [
"Set",
"behavior",
"if",
"name",
"is",
"in",
"self",
".",
"parentBehavior",
".",
"knownChildren",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L141-L160 |
eventable/vobject | vobject/base.py | VBase.setBehavior | def setBehavior(self, behavior, cascade=True):
"""
Set behavior. If cascade is True, autoBehavior all descendants.
"""
self.behavior = behavior
if cascade:
for obj in self.getChildren():
obj.parentBehavior = behavior
obj.autoBehavior(True) | python | def setBehavior(self, behavior, cascade=True):
self.behavior = behavior
if cascade:
for obj in self.getChildren():
obj.parentBehavior = behavior
obj.autoBehavior(True) | [
"def",
"setBehavior",
"(",
"self",
",",
"behavior",
",",
"cascade",
"=",
"True",
")",
":",
"self",
".",
"behavior",
"=",
"behavior",
"if",
"cascade",
":",
"for",
"obj",
"in",
"self",
".",
"getChildren",
"(",
")",
":",
"obj",
".",
"parentBehavior",
"=",
"behavior",
"obj",
".",
"autoBehavior",
"(",
"True",
")"
]
| Set behavior. If cascade is True, autoBehavior all descendants. | [
"Set",
"behavior",
".",
"If",
"cascade",
"is",
"True",
"autoBehavior",
"all",
"descendants",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L162-L170 |
eventable/vobject | vobject/base.py | VBase.transformToNative | def transformToNative(self):
"""
Transform this object into a custom VBase subclass.
transformToNative should always return a representation of this object.
It may do so by modifying self in place then returning self, or by
creating a new object.
"""
if self.isNative or not self.behavior or not self.behavior.hasNative:
return self
else:
self_orig = copy.copy(self)
try:
return self.behavior.transformToNative(self)
except Exception as e:
# wrap errors in transformation in a ParseError
lineNumber = getattr(self, 'lineNumber', None)
if isinstance(e, ParseError):
if lineNumber is not None:
e.lineNumber = lineNumber
raise
else:
msg = "In transformToNative, unhandled exception on line {0}: {1}: {2}"
msg = msg.format(lineNumber, sys.exc_info()[0], sys.exc_info()[1])
msg = msg + " (" + str(self_orig) + ")"
raise ParseError(msg, lineNumber) | python | def transformToNative(self):
if self.isNative or not self.behavior or not self.behavior.hasNative:
return self
else:
self_orig = copy.copy(self)
try:
return self.behavior.transformToNative(self)
except Exception as e:
lineNumber = getattr(self, 'lineNumber', None)
if isinstance(e, ParseError):
if lineNumber is not None:
e.lineNumber = lineNumber
raise
else:
msg = "In transformToNative, unhandled exception on line {0}: {1}: {2}"
msg = msg.format(lineNumber, sys.exc_info()[0], sys.exc_info()[1])
msg = msg + " (" + str(self_orig) + ")"
raise ParseError(msg, lineNumber) | [
"def",
"transformToNative",
"(",
"self",
")",
":",
"if",
"self",
".",
"isNative",
"or",
"not",
"self",
".",
"behavior",
"or",
"not",
"self",
".",
"behavior",
".",
"hasNative",
":",
"return",
"self",
"else",
":",
"self_orig",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"try",
":",
"return",
"self",
".",
"behavior",
".",
"transformToNative",
"(",
"self",
")",
"except",
"Exception",
"as",
"e",
":",
"# wrap errors in transformation in a ParseError",
"lineNumber",
"=",
"getattr",
"(",
"self",
",",
"'lineNumber'",
",",
"None",
")",
"if",
"isinstance",
"(",
"e",
",",
"ParseError",
")",
":",
"if",
"lineNumber",
"is",
"not",
"None",
":",
"e",
".",
"lineNumber",
"=",
"lineNumber",
"raise",
"else",
":",
"msg",
"=",
"\"In transformToNative, unhandled exception on line {0}: {1}: {2}\"",
"msg",
"=",
"msg",
".",
"format",
"(",
"lineNumber",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"0",
"]",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
")",
"msg",
"=",
"msg",
"+",
"\" (\"",
"+",
"str",
"(",
"self_orig",
")",
"+",
"\")\"",
"raise",
"ParseError",
"(",
"msg",
",",
"lineNumber",
")"
]
| Transform this object into a custom VBase subclass.
transformToNative should always return a representation of this object.
It may do so by modifying self in place then returning self, or by
creating a new object. | [
"Transform",
"this",
"object",
"into",
"a",
"custom",
"VBase",
"subclass",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L172-L198 |
eventable/vobject | vobject/base.py | VBase.serialize | def serialize(self, buf=None, lineLength=75, validate=True, behavior=None):
"""
Serialize to buf if it exists, otherwise return a string.
Use self.behavior.serialize if behavior exists.
"""
if not behavior:
behavior = self.behavior
if behavior:
if DEBUG:
logger.debug("serializing {0!s} with behavior {1!s}".format(self.name, behavior))
return behavior.serialize(self, buf, lineLength, validate)
else:
if DEBUG:
logger.debug("serializing {0!s} without behavior".format(self.name))
return defaultSerialize(self, buf, lineLength) | python | def serialize(self, buf=None, lineLength=75, validate=True, behavior=None):
if not behavior:
behavior = self.behavior
if behavior:
if DEBUG:
logger.debug("serializing {0!s} with behavior {1!s}".format(self.name, behavior))
return behavior.serialize(self, buf, lineLength, validate)
else:
if DEBUG:
logger.debug("serializing {0!s} without behavior".format(self.name))
return defaultSerialize(self, buf, lineLength) | [
"def",
"serialize",
"(",
"self",
",",
"buf",
"=",
"None",
",",
"lineLength",
"=",
"75",
",",
"validate",
"=",
"True",
",",
"behavior",
"=",
"None",
")",
":",
"if",
"not",
"behavior",
":",
"behavior",
"=",
"self",
".",
"behavior",
"if",
"behavior",
":",
"if",
"DEBUG",
":",
"logger",
".",
"debug",
"(",
"\"serializing {0!s} with behavior {1!s}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"behavior",
")",
")",
"return",
"behavior",
".",
"serialize",
"(",
"self",
",",
"buf",
",",
"lineLength",
",",
"validate",
")",
"else",
":",
"if",
"DEBUG",
":",
"logger",
".",
"debug",
"(",
"\"serializing {0!s} without behavior\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"return",
"defaultSerialize",
"(",
"self",
",",
"buf",
",",
"lineLength",
")"
]
| Serialize to buf if it exists, otherwise return a string.
Use self.behavior.serialize if behavior exists. | [
"Serialize",
"to",
"buf",
"if",
"it",
"exists",
"otherwise",
"return",
"a",
"string",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L242-L258 |
eventable/vobject | vobject/base.py | ContentLine.valueRepr | def valueRepr(self):
"""
Transform the representation of the value
according to the behavior, if any.
"""
v = self.value
if self.behavior:
v = self.behavior.valueRepr(self)
return v | python | def valueRepr(self):
v = self.value
if self.behavior:
v = self.behavior.valueRepr(self)
return v | [
"def",
"valueRepr",
"(",
"self",
")",
":",
"v",
"=",
"self",
".",
"value",
"if",
"self",
".",
"behavior",
":",
"v",
"=",
"self",
".",
"behavior",
".",
"valueRepr",
"(",
"self",
")",
"return",
"v"
]
| Transform the representation of the value
according to the behavior, if any. | [
"Transform",
"the",
"representation",
"of",
"the",
"value",
"according",
"to",
"the",
"behavior",
"if",
"any",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L419-L427 |
eventable/vobject | vobject/base.py | Component.setProfile | def setProfile(self, name):
"""
Assign a PROFILE to this unnamed component.
Used by vCard, not by vCalendar.
"""
if self.name or self.useBegin:
if self.name == name:
return
raise VObjectError("This component already has a PROFILE or "
"uses BEGIN.")
self.name = name.upper() | python | def setProfile(self, name):
if self.name or self.useBegin:
if self.name == name:
return
raise VObjectError("This component already has a PROFILE or "
"uses BEGIN.")
self.name = name.upper() | [
"def",
"setProfile",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"name",
"or",
"self",
".",
"useBegin",
":",
"if",
"self",
".",
"name",
"==",
"name",
":",
"return",
"raise",
"VObjectError",
"(",
"\"This component already has a PROFILE or \"",
"\"uses BEGIN.\"",
")",
"self",
".",
"name",
"=",
"name",
".",
"upper",
"(",
")"
]
| Assign a PROFILE to this unnamed component.
Used by vCard, not by vCalendar. | [
"Assign",
"a",
"PROFILE",
"to",
"this",
"unnamed",
"component",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L501-L512 |
eventable/vobject | vobject/base.py | Component.getChildValue | def getChildValue(self, childName, default=None, childNumber=0):
"""
Return a child's value (the first, by default), or None.
"""
child = self.contents.get(toVName(childName))
if child is None:
return default
else:
return child[childNumber].value | python | def getChildValue(self, childName, default=None, childNumber=0):
child = self.contents.get(toVName(childName))
if child is None:
return default
else:
return child[childNumber].value | [
"def",
"getChildValue",
"(",
"self",
",",
"childName",
",",
"default",
"=",
"None",
",",
"childNumber",
"=",
"0",
")",
":",
"child",
"=",
"self",
".",
"contents",
".",
"get",
"(",
"toVName",
"(",
"childName",
")",
")",
"if",
"child",
"is",
"None",
":",
"return",
"default",
"else",
":",
"return",
"child",
"[",
"childNumber",
"]",
".",
"value"
]
| Return a child's value (the first, by default), or None. | [
"Return",
"a",
"child",
"s",
"value",
"(",
"the",
"first",
"by",
"default",
")",
"or",
"None",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L570-L578 |
eventable/vobject | vobject/base.py | Component.add | def add(self, objOrName, group=None):
"""
Add objOrName to contents, set behavior if it can be inferred.
If objOrName is a string, create an empty component or line based on
behavior. If no behavior is found for the object, add a ContentLine.
group is an optional prefix to the name of the object (see RFC 2425).
"""
if isinstance(objOrName, VBase):
obj = objOrName
if self.behavior:
obj.parentBehavior = self.behavior
obj.autoBehavior(True)
else:
name = objOrName.upper()
try:
id = self.behavior.knownChildren[name][2]
behavior = getBehavior(name, id)
if behavior.isComponent:
obj = Component(name)
else:
obj = ContentLine(name, [], '', group)
obj.parentBehavior = self.behavior
obj.behavior = behavior
obj = obj.transformToNative()
except (KeyError, AttributeError):
obj = ContentLine(objOrName, [], '', group)
if obj.behavior is None and self.behavior is not None:
if isinstance(obj, ContentLine):
obj.behavior = self.behavior.defaultBehavior
self.contents.setdefault(obj.name.lower(), []).append(obj)
return obj | python | def add(self, objOrName, group=None):
if isinstance(objOrName, VBase):
obj = objOrName
if self.behavior:
obj.parentBehavior = self.behavior
obj.autoBehavior(True)
else:
name = objOrName.upper()
try:
id = self.behavior.knownChildren[name][2]
behavior = getBehavior(name, id)
if behavior.isComponent:
obj = Component(name)
else:
obj = ContentLine(name, [], '', group)
obj.parentBehavior = self.behavior
obj.behavior = behavior
obj = obj.transformToNative()
except (KeyError, AttributeError):
obj = ContentLine(objOrName, [], '', group)
if obj.behavior is None and self.behavior is not None:
if isinstance(obj, ContentLine):
obj.behavior = self.behavior.defaultBehavior
self.contents.setdefault(obj.name.lower(), []).append(obj)
return obj | [
"def",
"add",
"(",
"self",
",",
"objOrName",
",",
"group",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"objOrName",
",",
"VBase",
")",
":",
"obj",
"=",
"objOrName",
"if",
"self",
".",
"behavior",
":",
"obj",
".",
"parentBehavior",
"=",
"self",
".",
"behavior",
"obj",
".",
"autoBehavior",
"(",
"True",
")",
"else",
":",
"name",
"=",
"objOrName",
".",
"upper",
"(",
")",
"try",
":",
"id",
"=",
"self",
".",
"behavior",
".",
"knownChildren",
"[",
"name",
"]",
"[",
"2",
"]",
"behavior",
"=",
"getBehavior",
"(",
"name",
",",
"id",
")",
"if",
"behavior",
".",
"isComponent",
":",
"obj",
"=",
"Component",
"(",
"name",
")",
"else",
":",
"obj",
"=",
"ContentLine",
"(",
"name",
",",
"[",
"]",
",",
"''",
",",
"group",
")",
"obj",
".",
"parentBehavior",
"=",
"self",
".",
"behavior",
"obj",
".",
"behavior",
"=",
"behavior",
"obj",
"=",
"obj",
".",
"transformToNative",
"(",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"obj",
"=",
"ContentLine",
"(",
"objOrName",
",",
"[",
"]",
",",
"''",
",",
"group",
")",
"if",
"obj",
".",
"behavior",
"is",
"None",
"and",
"self",
".",
"behavior",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ContentLine",
")",
":",
"obj",
".",
"behavior",
"=",
"self",
".",
"behavior",
".",
"defaultBehavior",
"self",
".",
"contents",
".",
"setdefault",
"(",
"obj",
".",
"name",
".",
"lower",
"(",
")",
",",
"[",
"]",
")",
".",
"append",
"(",
"obj",
")",
"return",
"obj"
]
| Add objOrName to contents, set behavior if it can be inferred.
If objOrName is a string, create an empty component or line based on
behavior. If no behavior is found for the object, add a ContentLine.
group is an optional prefix to the name of the object (see RFC 2425). | [
"Add",
"objOrName",
"to",
"contents",
"set",
"behavior",
"if",
"it",
"can",
"be",
"inferred",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L580-L612 |
eventable/vobject | vobject/base.py | Component.remove | def remove(self, obj):
"""
Remove obj from contents.
"""
named = self.contents.get(obj.name.lower())
if named:
try:
named.remove(obj)
if len(named) == 0:
del self.contents[obj.name.lower()]
except ValueError:
pass | python | def remove(self, obj):
named = self.contents.get(obj.name.lower())
if named:
try:
named.remove(obj)
if len(named) == 0:
del self.contents[obj.name.lower()]
except ValueError:
pass | [
"def",
"remove",
"(",
"self",
",",
"obj",
")",
":",
"named",
"=",
"self",
".",
"contents",
".",
"get",
"(",
"obj",
".",
"name",
".",
"lower",
"(",
")",
")",
"if",
"named",
":",
"try",
":",
"named",
".",
"remove",
"(",
"obj",
")",
"if",
"len",
"(",
"named",
")",
"==",
"0",
":",
"del",
"self",
".",
"contents",
"[",
"obj",
".",
"name",
".",
"lower",
"(",
")",
"]",
"except",
"ValueError",
":",
"pass"
]
| Remove obj from contents. | [
"Remove",
"obj",
"from",
"contents",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L614-L625 |
eventable/vobject | vobject/base.py | Component.setBehaviorFromVersionLine | def setBehaviorFromVersionLine(self, versionLine):
"""
Set behavior if one matches name, versionLine.value.
"""
v = getBehavior(self.name, versionLine.value)
if v:
self.setBehavior(v) | python | def setBehaviorFromVersionLine(self, versionLine):
v = getBehavior(self.name, versionLine.value)
if v:
self.setBehavior(v) | [
"def",
"setBehaviorFromVersionLine",
"(",
"self",
",",
"versionLine",
")",
":",
"v",
"=",
"getBehavior",
"(",
"self",
".",
"name",
",",
"versionLine",
".",
"value",
")",
"if",
"v",
":",
"self",
".",
"setBehavior",
"(",
"v",
")"
]
| Set behavior if one matches name, versionLine.value. | [
"Set",
"behavior",
"if",
"one",
"matches",
"name",
"versionLine",
".",
"value",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L657-L663 |
eventable/vobject | vobject/base.py | Component.transformChildrenToNative | def transformChildrenToNative(self):
"""
Recursively replace children with their native representation.
Sort to get dependency order right, like vtimezone before vevent.
"""
for childArray in (self.contents[k] for k in self.sortChildKeys()):
for child in childArray:
child = child.transformToNative()
child.transformChildrenToNative() | python | def transformChildrenToNative(self):
for childArray in (self.contents[k] for k in self.sortChildKeys()):
for child in childArray:
child = child.transformToNative()
child.transformChildrenToNative() | [
"def",
"transformChildrenToNative",
"(",
"self",
")",
":",
"for",
"childArray",
"in",
"(",
"self",
".",
"contents",
"[",
"k",
"]",
"for",
"k",
"in",
"self",
".",
"sortChildKeys",
"(",
")",
")",
":",
"for",
"child",
"in",
"childArray",
":",
"child",
"=",
"child",
".",
"transformToNative",
"(",
")",
"child",
".",
"transformChildrenToNative",
"(",
")"
]
| Recursively replace children with their native representation.
Sort to get dependency order right, like vtimezone before vevent. | [
"Recursively",
"replace",
"children",
"with",
"their",
"native",
"representation",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L665-L674 |
eventable/vobject | vobject/base.py | Component.transformChildrenFromNative | def transformChildrenFromNative(self, clearBehavior=True):
"""
Recursively transform native children to vanilla representations.
"""
for childArray in self.contents.values():
for child in childArray:
child = child.transformFromNative()
child.transformChildrenFromNative(clearBehavior)
if clearBehavior:
child.behavior = None
child.parentBehavior = None | python | def transformChildrenFromNative(self, clearBehavior=True):
for childArray in self.contents.values():
for child in childArray:
child = child.transformFromNative()
child.transformChildrenFromNative(clearBehavior)
if clearBehavior:
child.behavior = None
child.parentBehavior = None | [
"def",
"transformChildrenFromNative",
"(",
"self",
",",
"clearBehavior",
"=",
"True",
")",
":",
"for",
"childArray",
"in",
"self",
".",
"contents",
".",
"values",
"(",
")",
":",
"for",
"child",
"in",
"childArray",
":",
"child",
"=",
"child",
".",
"transformFromNative",
"(",
")",
"child",
".",
"transformChildrenFromNative",
"(",
"clearBehavior",
")",
"if",
"clearBehavior",
":",
"child",
".",
"behavior",
"=",
"None",
"child",
".",
"parentBehavior",
"=",
"None"
]
| Recursively transform native children to vanilla representations. | [
"Recursively",
"transform",
"native",
"children",
"to",
"vanilla",
"representations",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L676-L686 |
eventable/vobject | vobject/hcalendar.py | HCalendar.serialize | def serialize(cls, obj, buf=None, lineLength=None, validate=True):
"""
Serialize iCalendar to HTML using the hCalendar microformat (http://microformats.org/wiki/hcalendar)
"""
outbuf = buf or six.StringIO()
level = 0 # holds current indentation level
tabwidth = 3
def indent():
return ' ' * level * tabwidth
def out(s):
outbuf.write(indent())
outbuf.write(s)
# not serializing optional vcalendar wrapper
vevents = obj.vevent_list
for event in vevents:
out('<span class="vevent">' + CRLF)
level += 1
# URL
url = event.getChildValue("url")
if url:
out('<a class="url" href="' + url + '">' + CRLF)
level += 1
# SUMMARY
summary = event.getChildValue("summary")
if summary:
out('<span class="summary">' + summary + '</span>:' + CRLF)
# DTSTART
dtstart = event.getChildValue("dtstart")
if dtstart:
if type(dtstart) == date:
timeformat = "%A, %B %e"
machine = "%Y%m%d"
elif type(dtstart) == datetime:
timeformat = "%A, %B %e, %H:%M"
machine = "%Y%m%dT%H%M%S%z"
#TODO: Handle non-datetime formats?
#TODO: Spec says we should handle when dtstart isn't included
out('<abbr class="dtstart", title="{0!s}">{1!s}</abbr>\r\n'
.format(dtstart.strftime(machine),
dtstart.strftime(timeformat)))
# DTEND
dtend = event.getChildValue("dtend")
if not dtend:
duration = event.getChildValue("duration")
if duration:
dtend = duration + dtstart
# TODO: If lacking dtend & duration?
if dtend:
human = dtend
# TODO: Human readable part could be smarter, excluding repeated data
if type(dtend) == date:
human = dtend - timedelta(days=1)
out('- <abbr class="dtend", title="{0!s}">{1!s}</abbr>\r\n'
.format(dtend.strftime(machine),
human.strftime(timeformat)))
# LOCATION
location = event.getChildValue("location")
if location:
out('at <span class="location">' + location + '</span>' + CRLF)
description = event.getChildValue("description")
if description:
out('<div class="description">' + description + '</div>' + CRLF)
if url:
level -= 1
out('</a>' + CRLF)
level -= 1
out('</span>' + CRLF) # close vevent
return buf or outbuf.getvalue() | python | def serialize(cls, obj, buf=None, lineLength=None, validate=True):
outbuf = buf or six.StringIO()
level = 0
tabwidth = 3
def indent():
return ' ' * level * tabwidth
def out(s):
outbuf.write(indent())
outbuf.write(s)
vevents = obj.vevent_list
for event in vevents:
out('<span class="vevent">' + CRLF)
level += 1
url = event.getChildValue("url")
if url:
out('<a class="url" href="' + url + '">' + CRLF)
level += 1
summary = event.getChildValue("summary")
if summary:
out('<span class="summary">' + summary + '</span>:' + CRLF)
dtstart = event.getChildValue("dtstart")
if dtstart:
if type(dtstart) == date:
timeformat = "%A, %B %e"
machine = "%Y%m%d"
elif type(dtstart) == datetime:
timeformat = "%A, %B %e, %H:%M"
machine = "%Y%m%dT%H%M%S%z"
out('<abbr class="dtstart", title="{0!s}">{1!s}</abbr>\r\n'
.format(dtstart.strftime(machine),
dtstart.strftime(timeformat)))
dtend = event.getChildValue("dtend")
if not dtend:
duration = event.getChildValue("duration")
if duration:
dtend = duration + dtstart
if dtend:
human = dtend
if type(dtend) == date:
human = dtend - timedelta(days=1)
out('- <abbr class="dtend", title="{0!s}">{1!s}</abbr>\r\n'
.format(dtend.strftime(machine),
human.strftime(timeformat)))
location = event.getChildValue("location")
if location:
out('at <span class="location">' + location + '</span>' + CRLF)
description = event.getChildValue("description")
if description:
out('<div class="description">' + description + '</div>' + CRLF)
if url:
level -= 1
out('</a>' + CRLF)
level -= 1
out('</span>' + CRLF)
return buf or outbuf.getvalue() | [
"def",
"serialize",
"(",
"cls",
",",
"obj",
",",
"buf",
"=",
"None",
",",
"lineLength",
"=",
"None",
",",
"validate",
"=",
"True",
")",
":",
"outbuf",
"=",
"buf",
"or",
"six",
".",
"StringIO",
"(",
")",
"level",
"=",
"0",
"# holds current indentation level",
"tabwidth",
"=",
"3",
"def",
"indent",
"(",
")",
":",
"return",
"' '",
"*",
"level",
"*",
"tabwidth",
"def",
"out",
"(",
"s",
")",
":",
"outbuf",
".",
"write",
"(",
"indent",
"(",
")",
")",
"outbuf",
".",
"write",
"(",
"s",
")",
"# not serializing optional vcalendar wrapper",
"vevents",
"=",
"obj",
".",
"vevent_list",
"for",
"event",
"in",
"vevents",
":",
"out",
"(",
"'<span class=\"vevent\">'",
"+",
"CRLF",
")",
"level",
"+=",
"1",
"# URL",
"url",
"=",
"event",
".",
"getChildValue",
"(",
"\"url\"",
")",
"if",
"url",
":",
"out",
"(",
"'<a class=\"url\" href=\"'",
"+",
"url",
"+",
"'\">'",
"+",
"CRLF",
")",
"level",
"+=",
"1",
"# SUMMARY",
"summary",
"=",
"event",
".",
"getChildValue",
"(",
"\"summary\"",
")",
"if",
"summary",
":",
"out",
"(",
"'<span class=\"summary\">'",
"+",
"summary",
"+",
"'</span>:'",
"+",
"CRLF",
")",
"# DTSTART",
"dtstart",
"=",
"event",
".",
"getChildValue",
"(",
"\"dtstart\"",
")",
"if",
"dtstart",
":",
"if",
"type",
"(",
"dtstart",
")",
"==",
"date",
":",
"timeformat",
"=",
"\"%A, %B %e\"",
"machine",
"=",
"\"%Y%m%d\"",
"elif",
"type",
"(",
"dtstart",
")",
"==",
"datetime",
":",
"timeformat",
"=",
"\"%A, %B %e, %H:%M\"",
"machine",
"=",
"\"%Y%m%dT%H%M%S%z\"",
"#TODO: Handle non-datetime formats?",
"#TODO: Spec says we should handle when dtstart isn't included",
"out",
"(",
"'<abbr class=\"dtstart\", title=\"{0!s}\">{1!s}</abbr>\\r\\n'",
".",
"format",
"(",
"dtstart",
".",
"strftime",
"(",
"machine",
")",
",",
"dtstart",
".",
"strftime",
"(",
"timeformat",
")",
")",
")",
"# DTEND",
"dtend",
"=",
"event",
".",
"getChildValue",
"(",
"\"dtend\"",
")",
"if",
"not",
"dtend",
":",
"duration",
"=",
"event",
".",
"getChildValue",
"(",
"\"duration\"",
")",
"if",
"duration",
":",
"dtend",
"=",
"duration",
"+",
"dtstart",
"# TODO: If lacking dtend & duration?",
"if",
"dtend",
":",
"human",
"=",
"dtend",
"# TODO: Human readable part could be smarter, excluding repeated data",
"if",
"type",
"(",
"dtend",
")",
"==",
"date",
":",
"human",
"=",
"dtend",
"-",
"timedelta",
"(",
"days",
"=",
"1",
")",
"out",
"(",
"'- <abbr class=\"dtend\", title=\"{0!s}\">{1!s}</abbr>\\r\\n'",
".",
"format",
"(",
"dtend",
".",
"strftime",
"(",
"machine",
")",
",",
"human",
".",
"strftime",
"(",
"timeformat",
")",
")",
")",
"# LOCATION",
"location",
"=",
"event",
".",
"getChildValue",
"(",
"\"location\"",
")",
"if",
"location",
":",
"out",
"(",
"'at <span class=\"location\">'",
"+",
"location",
"+",
"'</span>'",
"+",
"CRLF",
")",
"description",
"=",
"event",
".",
"getChildValue",
"(",
"\"description\"",
")",
"if",
"description",
":",
"out",
"(",
"'<div class=\"description\">'",
"+",
"description",
"+",
"'</div>'",
"+",
"CRLF",
")",
"if",
"url",
":",
"level",
"-=",
"1",
"out",
"(",
"'</a>'",
"+",
"CRLF",
")",
"level",
"-=",
"1",
"out",
"(",
"'</span>'",
"+",
"CRLF",
")",
"# close vevent",
"return",
"buf",
"or",
"outbuf",
".",
"getvalue",
"(",
")"
]
| Serialize iCalendar to HTML using the hCalendar microformat (http://microformats.org/wiki/hcalendar) | [
"Serialize",
"iCalendar",
"to",
"HTML",
"using",
"the",
"hCalendar",
"microformat",
"(",
"http",
":",
"//",
"microformats",
".",
"org",
"/",
"wiki",
"/",
"hcalendar",
")"
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/hcalendar.py#L43-L128 |
eventable/vobject | docs/build/lib/vobject/change_tz.py | change_tz | def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc):
"""
Change the timezone of the specified component.
Args:
cal (Component): the component to change
new_timezone (tzinfo): the timezone to change to
default (tzinfo): a timezone to assume if the dtstart or dtend in cal
doesn't have an existing timezone
utc_only (bool): only convert dates that are in utc
utc_tz (tzinfo): the tzinfo to compare to for UTC when processing
utc_only=True
"""
for vevent in getattr(cal, 'vevent_list', []):
start = getattr(vevent, 'dtstart', None)
end = getattr(vevent, 'dtend', None)
for node in (start, end):
if node:
dt = node.value
if (isinstance(dt, datetime) and
(not utc_only or dt.tzinfo == utc_tz)):
if dt.tzinfo is None:
dt = dt.replace(tzinfo = default)
node.value = dt.astimezone(new_timezone) | python | def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc):
for vevent in getattr(cal, 'vevent_list', []):
start = getattr(vevent, 'dtstart', None)
end = getattr(vevent, 'dtend', None)
for node in (start, end):
if node:
dt = node.value
if (isinstance(dt, datetime) and
(not utc_only or dt.tzinfo == utc_tz)):
if dt.tzinfo is None:
dt = dt.replace(tzinfo = default)
node.value = dt.astimezone(new_timezone) | [
"def",
"change_tz",
"(",
"cal",
",",
"new_timezone",
",",
"default",
",",
"utc_only",
"=",
"False",
",",
"utc_tz",
"=",
"icalendar",
".",
"utc",
")",
":",
"for",
"vevent",
"in",
"getattr",
"(",
"cal",
",",
"'vevent_list'",
",",
"[",
"]",
")",
":",
"start",
"=",
"getattr",
"(",
"vevent",
",",
"'dtstart'",
",",
"None",
")",
"end",
"=",
"getattr",
"(",
"vevent",
",",
"'dtend'",
",",
"None",
")",
"for",
"node",
"in",
"(",
"start",
",",
"end",
")",
":",
"if",
"node",
":",
"dt",
"=",
"node",
".",
"value",
"if",
"(",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
"and",
"(",
"not",
"utc_only",
"or",
"dt",
".",
"tzinfo",
"==",
"utc_tz",
")",
")",
":",
"if",
"dt",
".",
"tzinfo",
"is",
"None",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"default",
")",
"node",
".",
"value",
"=",
"dt",
".",
"astimezone",
"(",
"new_timezone",
")"
]
| Change the timezone of the specified component.
Args:
cal (Component): the component to change
new_timezone (tzinfo): the timezone to change to
default (tzinfo): a timezone to assume if the dtstart or dtend in cal
doesn't have an existing timezone
utc_only (bool): only convert dates that are in utc
utc_tz (tzinfo): the tzinfo to compare to for UTC when processing
utc_only=True | [
"Change",
"the",
"timezone",
"of",
"the",
"specified",
"component",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/change_tz.py#L13-L37 |
eventable/vobject | docs/build/lib/vobject/base.py | foldOneLine | def foldOneLine(outbuf, input, lineLength = 75):
"""
Folding line procedure that ensures multi-byte utf-8 sequences are not
broken across lines
TO-DO: This all seems odd. Is it still needed, especially in python3?
"""
if len(input) < lineLength:
# Optimize for unfolded line case
try:
outbuf.write(bytes(input, 'UTF-8'))
except Exception:
# fall back on py2 syntax
outbuf.write(str_(input))
else:
# Look for valid utf8 range and write that out
start = 0
written = 0
counter = 0 # counts line size in bytes
decoded = to_unicode(input)
length = len(to_basestring(input))
while written < length:
s = decoded[start] # take one char
size = len(to_basestring(s)) # calculate it's size in bytes
if counter + size > lineLength:
try:
outbuf.write(bytes("\r\n ", 'UTF-8'))
except Exception:
# fall back on py2 syntax
outbuf.write("\r\n ")
counter = 1 # one for space
if str is unicode_type:
outbuf.write(to_unicode(s))
else:
# fall back on py2 syntax
outbuf.write(s.encode('utf-8'))
written += size
counter += size
start += 1
try:
outbuf.write(bytes("\r\n", 'UTF-8'))
except Exception:
# fall back on py2 syntax
outbuf.write("\r\n") | python | def foldOneLine(outbuf, input, lineLength = 75):
if len(input) < lineLength:
try:
outbuf.write(bytes(input, 'UTF-8'))
except Exception:
outbuf.write(str_(input))
else:
start = 0
written = 0
counter = 0
decoded = to_unicode(input)
length = len(to_basestring(input))
while written < length:
s = decoded[start]
size = len(to_basestring(s))
if counter + size > lineLength:
try:
outbuf.write(bytes("\r\n ", 'UTF-8'))
except Exception:
outbuf.write("\r\n ")
counter = 1
if str is unicode_type:
outbuf.write(to_unicode(s))
else:
outbuf.write(s.encode('utf-8'))
written += size
counter += size
start += 1
try:
outbuf.write(bytes("\r\n", 'UTF-8'))
except Exception:
outbuf.write("\r\n") | [
"def",
"foldOneLine",
"(",
"outbuf",
",",
"input",
",",
"lineLength",
"=",
"75",
")",
":",
"if",
"len",
"(",
"input",
")",
"<",
"lineLength",
":",
"# Optimize for unfolded line case",
"try",
":",
"outbuf",
".",
"write",
"(",
"bytes",
"(",
"input",
",",
"'UTF-8'",
")",
")",
"except",
"Exception",
":",
"# fall back on py2 syntax",
"outbuf",
".",
"write",
"(",
"str_",
"(",
"input",
")",
")",
"else",
":",
"# Look for valid utf8 range and write that out",
"start",
"=",
"0",
"written",
"=",
"0",
"counter",
"=",
"0",
"# counts line size in bytes",
"decoded",
"=",
"to_unicode",
"(",
"input",
")",
"length",
"=",
"len",
"(",
"to_basestring",
"(",
"input",
")",
")",
"while",
"written",
"<",
"length",
":",
"s",
"=",
"decoded",
"[",
"start",
"]",
"# take one char",
"size",
"=",
"len",
"(",
"to_basestring",
"(",
"s",
")",
")",
"# calculate it's size in bytes",
"if",
"counter",
"+",
"size",
">",
"lineLength",
":",
"try",
":",
"outbuf",
".",
"write",
"(",
"bytes",
"(",
"\"\\r\\n \"",
",",
"'UTF-8'",
")",
")",
"except",
"Exception",
":",
"# fall back on py2 syntax",
"outbuf",
".",
"write",
"(",
"\"\\r\\n \"",
")",
"counter",
"=",
"1",
"# one for space",
"if",
"str",
"is",
"unicode_type",
":",
"outbuf",
".",
"write",
"(",
"to_unicode",
"(",
"s",
")",
")",
"else",
":",
"# fall back on py2 syntax",
"outbuf",
".",
"write",
"(",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"written",
"+=",
"size",
"counter",
"+=",
"size",
"start",
"+=",
"1",
"try",
":",
"outbuf",
".",
"write",
"(",
"bytes",
"(",
"\"\\r\\n\"",
",",
"'UTF-8'",
")",
")",
"except",
"Exception",
":",
"# fall back on py2 syntax",
"outbuf",
".",
"write",
"(",
"\"\\r\\n\"",
")"
]
| Folding line procedure that ensures multi-byte utf-8 sequences are not
broken across lines
TO-DO: This all seems odd. Is it still needed, especially in python3? | [
"Folding",
"line",
"procedure",
"that",
"ensures",
"multi",
"-",
"byte",
"utf",
"-",
"8",
"sequences",
"are",
"not",
"broken",
"across",
"lines"
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/base.py#L927-L974 |
eventable/vobject | docs/build/lib/vobject/base.py | defaultSerialize | def defaultSerialize(obj, buf, lineLength):
"""
Encode and fold obj and its children, write to buf or return a string.
"""
outbuf = buf or six.StringIO()
if isinstance(obj, Component):
if obj.group is None:
groupString = ''
else:
groupString = obj.group + '.'
if obj.useBegin:
foldOneLine(outbuf, "{0}BEGIN:{1}".format(groupString, obj.name),
lineLength)
for child in obj.getSortedChildren():
# validate is recursive, we only need to validate once
child.serialize(outbuf, lineLength, validate=False)
if obj.useBegin:
foldOneLine(outbuf, "{0}END:{1}".format(groupString, obj.name),
lineLength)
elif isinstance(obj, ContentLine):
startedEncoded = obj.encoded
if obj.behavior and not startedEncoded:
obj.behavior.encode(obj)
s = six.StringIO()
if obj.group is not None:
s.write(obj.group + '.')
s.write(obj.name.upper())
keys = sorted(obj.params.keys())
for key in keys:
paramstr = ','.join(dquoteEscape(p) for p in obj.params[key])
s.write(";{0}={1}".format(key, paramstr))
s.write(":{0}".format(str_(obj.value)))
if obj.behavior and not startedEncoded:
obj.behavior.decode(obj)
foldOneLine(outbuf, s.getvalue(), lineLength)
return buf or outbuf.getvalue() | python | def defaultSerialize(obj, buf, lineLength):
outbuf = buf or six.StringIO()
if isinstance(obj, Component):
if obj.group is None:
groupString = ''
else:
groupString = obj.group + '.'
if obj.useBegin:
foldOneLine(outbuf, "{0}BEGIN:{1}".format(groupString, obj.name),
lineLength)
for child in obj.getSortedChildren():
child.serialize(outbuf, lineLength, validate=False)
if obj.useBegin:
foldOneLine(outbuf, "{0}END:{1}".format(groupString, obj.name),
lineLength)
elif isinstance(obj, ContentLine):
startedEncoded = obj.encoded
if obj.behavior and not startedEncoded:
obj.behavior.encode(obj)
s = six.StringIO()
if obj.group is not None:
s.write(obj.group + '.')
s.write(obj.name.upper())
keys = sorted(obj.params.keys())
for key in keys:
paramstr = ','.join(dquoteEscape(p) for p in obj.params[key])
s.write(";{0}={1}".format(key, paramstr))
s.write(":{0}".format(str_(obj.value)))
if obj.behavior and not startedEncoded:
obj.behavior.decode(obj)
foldOneLine(outbuf, s.getvalue(), lineLength)
return buf or outbuf.getvalue() | [
"def",
"defaultSerialize",
"(",
"obj",
",",
"buf",
",",
"lineLength",
")",
":",
"outbuf",
"=",
"buf",
"or",
"six",
".",
"StringIO",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Component",
")",
":",
"if",
"obj",
".",
"group",
"is",
"None",
":",
"groupString",
"=",
"''",
"else",
":",
"groupString",
"=",
"obj",
".",
"group",
"+",
"'.'",
"if",
"obj",
".",
"useBegin",
":",
"foldOneLine",
"(",
"outbuf",
",",
"\"{0}BEGIN:{1}\"",
".",
"format",
"(",
"groupString",
",",
"obj",
".",
"name",
")",
",",
"lineLength",
")",
"for",
"child",
"in",
"obj",
".",
"getSortedChildren",
"(",
")",
":",
"# validate is recursive, we only need to validate once",
"child",
".",
"serialize",
"(",
"outbuf",
",",
"lineLength",
",",
"validate",
"=",
"False",
")",
"if",
"obj",
".",
"useBegin",
":",
"foldOneLine",
"(",
"outbuf",
",",
"\"{0}END:{1}\"",
".",
"format",
"(",
"groupString",
",",
"obj",
".",
"name",
")",
",",
"lineLength",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"ContentLine",
")",
":",
"startedEncoded",
"=",
"obj",
".",
"encoded",
"if",
"obj",
".",
"behavior",
"and",
"not",
"startedEncoded",
":",
"obj",
".",
"behavior",
".",
"encode",
"(",
"obj",
")",
"s",
"=",
"six",
".",
"StringIO",
"(",
")",
"if",
"obj",
".",
"group",
"is",
"not",
"None",
":",
"s",
".",
"write",
"(",
"obj",
".",
"group",
"+",
"'.'",
")",
"s",
".",
"write",
"(",
"obj",
".",
"name",
".",
"upper",
"(",
")",
")",
"keys",
"=",
"sorted",
"(",
"obj",
".",
"params",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"keys",
":",
"paramstr",
"=",
"','",
".",
"join",
"(",
"dquoteEscape",
"(",
"p",
")",
"for",
"p",
"in",
"obj",
".",
"params",
"[",
"key",
"]",
")",
"s",
".",
"write",
"(",
"\";{0}={1}\"",
".",
"format",
"(",
"key",
",",
"paramstr",
")",
")",
"s",
".",
"write",
"(",
"\":{0}\"",
".",
"format",
"(",
"str_",
"(",
"obj",
".",
"value",
")",
")",
")",
"if",
"obj",
".",
"behavior",
"and",
"not",
"startedEncoded",
":",
"obj",
".",
"behavior",
".",
"decode",
"(",
"obj",
")",
"foldOneLine",
"(",
"outbuf",
",",
"s",
".",
"getvalue",
"(",
")",
",",
"lineLength",
")",
"return",
"buf",
"or",
"outbuf",
".",
"getvalue",
"(",
")"
]
| Encode and fold obj and its children, write to buf or return a string. | [
"Encode",
"and",
"fold",
"obj",
"and",
"its",
"children",
"write",
"to",
"buf",
"or",
"return",
"a",
"string",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/base.py#L977-L1017 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | toUnicode | def toUnicode(s):
"""
Take a string or unicode, turn it into unicode, decoding as utf-8
"""
if isinstance(s, six.binary_type):
s = s.decode('utf-8')
return s | python | def toUnicode(s):
if isinstance(s, six.binary_type):
s = s.decode('utf-8')
return s | [
"def",
"toUnicode",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"binary_type",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"s"
]
| Take a string or unicode, turn it into unicode, decoding as utf-8 | [
"Take",
"a",
"string",
"or",
"unicode",
"turn",
"it",
"into",
"unicode",
"decoding",
"as",
"utf",
"-",
"8"
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L54-L60 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | numToDigits | def numToDigits(num, places):
"""
Helper, for converting numbers to textual digits.
"""
s = str(num)
if len(s) < places:
return ("0" * (places - len(s))) + s
elif len(s) > places:
return s[len(s)-places: ]
else:
return s | python | def numToDigits(num, places):
s = str(num)
if len(s) < places:
return ("0" * (places - len(s))) + s
elif len(s) > places:
return s[len(s)-places: ]
else:
return s | [
"def",
"numToDigits",
"(",
"num",
",",
"places",
")",
":",
"s",
"=",
"str",
"(",
"num",
")",
"if",
"len",
"(",
"s",
")",
"<",
"places",
":",
"return",
"(",
"\"0\"",
"*",
"(",
"places",
"-",
"len",
"(",
"s",
")",
")",
")",
"+",
"s",
"elif",
"len",
"(",
"s",
")",
">",
"places",
":",
"return",
"s",
"[",
"len",
"(",
"s",
")",
"-",
"places",
":",
"]",
"else",
":",
"return",
"s"
]
| Helper, for converting numbers to textual digits. | [
"Helper",
"for",
"converting",
"numbers",
"to",
"textual",
"digits",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1503-L1513 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | timedeltaToString | def timedeltaToString(delta):
"""
Convert timedelta to an ical DURATION.
"""
if delta.days == 0:
sign = 1
else:
sign = delta.days / abs(delta.days)
delta = abs(delta)
days = delta.days
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds % 3600) / 60)
seconds = int(delta.seconds % 60)
output = ''
if sign == -1:
output += '-'
output += 'P'
if days:
output += '{}D'.format(days)
if hours or minutes or seconds:
output += 'T'
elif not days: # Deal with zero duration
output += 'T0S'
if hours:
output += '{}H'.format(hours)
if minutes:
output += '{}M'.format(minutes)
if seconds:
output += '{}S'.format(seconds)
return output | python | def timedeltaToString(delta):
if delta.days == 0:
sign = 1
else:
sign = delta.days / abs(delta.days)
delta = abs(delta)
days = delta.days
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds % 3600) / 60)
seconds = int(delta.seconds % 60)
output = ''
if sign == -1:
output += '-'
output += 'P'
if days:
output += '{}D'.format(days)
if hours or minutes or seconds:
output += 'T'
elif not days:
output += 'T0S'
if hours:
output += '{}H'.format(hours)
if minutes:
output += '{}M'.format(minutes)
if seconds:
output += '{}S'.format(seconds)
return output | [
"def",
"timedeltaToString",
"(",
"delta",
")",
":",
"if",
"delta",
".",
"days",
"==",
"0",
":",
"sign",
"=",
"1",
"else",
":",
"sign",
"=",
"delta",
".",
"days",
"/",
"abs",
"(",
"delta",
".",
"days",
")",
"delta",
"=",
"abs",
"(",
"delta",
")",
"days",
"=",
"delta",
".",
"days",
"hours",
"=",
"int",
"(",
"delta",
".",
"seconds",
"/",
"3600",
")",
"minutes",
"=",
"int",
"(",
"(",
"delta",
".",
"seconds",
"%",
"3600",
")",
"/",
"60",
")",
"seconds",
"=",
"int",
"(",
"delta",
".",
"seconds",
"%",
"60",
")",
"output",
"=",
"''",
"if",
"sign",
"==",
"-",
"1",
":",
"output",
"+=",
"'-'",
"output",
"+=",
"'P'",
"if",
"days",
":",
"output",
"+=",
"'{}D'",
".",
"format",
"(",
"days",
")",
"if",
"hours",
"or",
"minutes",
"or",
"seconds",
":",
"output",
"+=",
"'T'",
"elif",
"not",
"days",
":",
"# Deal with zero duration",
"output",
"+=",
"'T0S'",
"if",
"hours",
":",
"output",
"+=",
"'{}H'",
".",
"format",
"(",
"hours",
")",
"if",
"minutes",
":",
"output",
"+=",
"'{}M'",
".",
"format",
"(",
"minutes",
")",
"if",
"seconds",
":",
"output",
"+=",
"'{}S'",
".",
"format",
"(",
"seconds",
")",
"return",
"output"
]
| Convert timedelta to an ical DURATION. | [
"Convert",
"timedelta",
"to",
"an",
"ical",
"DURATION",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1515-L1545 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | stringToTextValues | def stringToTextValues(s, listSeparator=',', charList=None, strict=False):
"""
Returns list of strings.
"""
if charList is None:
charList = escapableCharList
def escapableChar (c):
return c in charList
def error(msg):
if strict:
raise ParseError(msg)
else:
logging.error(msg)
# vars which control state machine
charIterator = enumerate(s)
state = "read normal"
current = []
results = []
while True:
try:
charIndex, char = next(charIterator)
except:
char = "eof"
if state == "read normal":
if char == '\\':
state = "read escaped char"
elif char == listSeparator:
state = "read normal"
current = "".join(current)
results.append(current)
current = []
elif char == "eof":
state = "end"
else:
state = "read normal"
current.append(char)
elif state == "read escaped char":
if escapableChar(char):
state = "read normal"
if char in 'nN':
current.append('\n')
else:
current.append(char)
else:
state = "read normal"
# leave unrecognized escaped characters for later passes
current.append('\\' + char)
elif state == "end": # an end state
if len(current) or len(results) == 0:
current = "".join(current)
results.append(current)
return results
elif state == "error": # an end state
return results
else:
state = "error"
error("unknown state: '{0!s}' reached in {1!s}".format(state, s)) | python | def stringToTextValues(s, listSeparator=',', charList=None, strict=False):
if charList is None:
charList = escapableCharList
def escapableChar (c):
return c in charList
def error(msg):
if strict:
raise ParseError(msg)
else:
logging.error(msg)
charIterator = enumerate(s)
state = "read normal"
current = []
results = []
while True:
try:
charIndex, char = next(charIterator)
except:
char = "eof"
if state == "read normal":
if char == '\\':
state = "read escaped char"
elif char == listSeparator:
state = "read normal"
current = "".join(current)
results.append(current)
current = []
elif char == "eof":
state = "end"
else:
state = "read normal"
current.append(char)
elif state == "read escaped char":
if escapableChar(char):
state = "read normal"
if char in 'nN':
current.append('\n')
else:
current.append(char)
else:
state = "read normal"
current.append('\\' + char)
elif state == "end":
if len(current) or len(results) == 0:
current = "".join(current)
results.append(current)
return results
elif state == "error":
return results
else:
state = "error"
error("unknown state: '{0!s}' reached in {1!s}".format(state, s)) | [
"def",
"stringToTextValues",
"(",
"s",
",",
"listSeparator",
"=",
"','",
",",
"charList",
"=",
"None",
",",
"strict",
"=",
"False",
")",
":",
"if",
"charList",
"is",
"None",
":",
"charList",
"=",
"escapableCharList",
"def",
"escapableChar",
"(",
"c",
")",
":",
"return",
"c",
"in",
"charList",
"def",
"error",
"(",
"msg",
")",
":",
"if",
"strict",
":",
"raise",
"ParseError",
"(",
"msg",
")",
"else",
":",
"logging",
".",
"error",
"(",
"msg",
")",
"# vars which control state machine",
"charIterator",
"=",
"enumerate",
"(",
"s",
")",
"state",
"=",
"\"read normal\"",
"current",
"=",
"[",
"]",
"results",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"charIndex",
",",
"char",
"=",
"next",
"(",
"charIterator",
")",
"except",
":",
"char",
"=",
"\"eof\"",
"if",
"state",
"==",
"\"read normal\"",
":",
"if",
"char",
"==",
"'\\\\'",
":",
"state",
"=",
"\"read escaped char\"",
"elif",
"char",
"==",
"listSeparator",
":",
"state",
"=",
"\"read normal\"",
"current",
"=",
"\"\"",
".",
"join",
"(",
"current",
")",
"results",
".",
"append",
"(",
"current",
")",
"current",
"=",
"[",
"]",
"elif",
"char",
"==",
"\"eof\"",
":",
"state",
"=",
"\"end\"",
"else",
":",
"state",
"=",
"\"read normal\"",
"current",
".",
"append",
"(",
"char",
")",
"elif",
"state",
"==",
"\"read escaped char\"",
":",
"if",
"escapableChar",
"(",
"char",
")",
":",
"state",
"=",
"\"read normal\"",
"if",
"char",
"in",
"'nN'",
":",
"current",
".",
"append",
"(",
"'\\n'",
")",
"else",
":",
"current",
".",
"append",
"(",
"char",
")",
"else",
":",
"state",
"=",
"\"read normal\"",
"# leave unrecognized escaped characters for later passes",
"current",
".",
"append",
"(",
"'\\\\'",
"+",
"char",
")",
"elif",
"state",
"==",
"\"end\"",
":",
"# an end state",
"if",
"len",
"(",
"current",
")",
"or",
"len",
"(",
"results",
")",
"==",
"0",
":",
"current",
"=",
"\"\"",
".",
"join",
"(",
"current",
")",
"results",
".",
"append",
"(",
"current",
")",
"return",
"results",
"elif",
"state",
"==",
"\"error\"",
":",
"# an end state",
"return",
"results",
"else",
":",
"state",
"=",
"\"error\"",
"error",
"(",
"\"unknown state: '{0!s}' reached in {1!s}\"",
".",
"format",
"(",
"state",
",",
"s",
")",
")"
]
| Returns list of strings. | [
"Returns",
"list",
"of",
"strings",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1636-L1702 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | stringToDurations | def stringToDurations(s, strict=False):
"""
Returns list of timedelta objects.
"""
def makeTimedelta(sign, week, day, hour, minute, sec):
if sign == "-": sign = -1
else: sign = 1
week = int(week)
day = int(day)
hour = int(hour)
minute = int(minute)
sec = int(sec)
return sign * datetime.timedelta(weeks=week, days=day, hours=hour,
minutes=minute, seconds=sec)
def error(msg):
if strict:
raise ParseError(msg)
else:
raise ParseError(msg)
# vars which control state machine
charIterator = enumerate(s)
state = "start"
durations = []
current = ""
sign = None
week = 0
day = 0
hour = 0
minute = 0
sec = 0
while True:
try:
charIndex, char = next(charIterator)
except:
char = "eof"
if state == "start":
if char == '+':
state = "start"
sign = char
elif char == '-':
state = "start"
sign = char
elif char.upper() == 'P':
state = "read field"
elif char == "eof":
state = "error"
error("got end-of-line while reading in duration: " + s)
elif char in string.digits:
state = "read field"
current = current + char # update this part when updating "read field"
else:
state = "error"
error("got unexpected character {0} reading in duration: {1}"
.format(char, s))
elif state == "read field":
if (char in string.digits):
state = "read field"
current = current + char # update part above when updating "read field"
elif char.upper() == 'T':
state = "read field"
elif char.upper() == 'W':
state = "read field"
week = current
current = ""
elif char.upper() == 'D':
state = "read field"
day = current
current = ""
elif char.upper() == 'H':
state = "read field"
hour = current
current = ""
elif char.upper() == 'M':
state = "read field"
minute = current
current = ""
elif char.upper() == 'S':
state = "read field"
sec = current
current = ""
elif char == ",":
state = "start"
durations.append(makeTimedelta(sign, week, day, hour, minute,
sec))
current = ""
sign = None
week = None
day = None
hour = None
minute = None
sec = None
elif char == "eof":
state = "end"
else:
state = "error"
error("got unexpected character reading in duration: " + s)
elif state == "end": # an end state
if (sign or week or day or hour or minute or sec):
durations.append(makeTimedelta(sign, week, day, hour, minute,
sec))
return durations
elif state == "error": # an end state
error("in error state")
return durations
else:
state = "error"
error("unknown state: '{0!s}' reached in {1!s}".format(state, s)) | python | def stringToDurations(s, strict=False):
def makeTimedelta(sign, week, day, hour, minute, sec):
if sign == "-": sign = -1
else: sign = 1
week = int(week)
day = int(day)
hour = int(hour)
minute = int(minute)
sec = int(sec)
return sign * datetime.timedelta(weeks=week, days=day, hours=hour,
minutes=minute, seconds=sec)
def error(msg):
if strict:
raise ParseError(msg)
else:
raise ParseError(msg)
charIterator = enumerate(s)
state = "start"
durations = []
current = ""
sign = None
week = 0
day = 0
hour = 0
minute = 0
sec = 0
while True:
try:
charIndex, char = next(charIterator)
except:
char = "eof"
if state == "start":
if char == '+':
state = "start"
sign = char
elif char == '-':
state = "start"
sign = char
elif char.upper() == 'P':
state = "read field"
elif char == "eof":
state = "error"
error("got end-of-line while reading in duration: " + s)
elif char in string.digits:
state = "read field"
current = current + char
else:
state = "error"
error("got unexpected character {0} reading in duration: {1}"
.format(char, s))
elif state == "read field":
if (char in string.digits):
state = "read field"
current = current + char
elif char.upper() == 'T':
state = "read field"
elif char.upper() == 'W':
state = "read field"
week = current
current = ""
elif char.upper() == 'D':
state = "read field"
day = current
current = ""
elif char.upper() == 'H':
state = "read field"
hour = current
current = ""
elif char.upper() == 'M':
state = "read field"
minute = current
current = ""
elif char.upper() == 'S':
state = "read field"
sec = current
current = ""
elif char == ",":
state = "start"
durations.append(makeTimedelta(sign, week, day, hour, minute,
sec))
current = ""
sign = None
week = None
day = None
hour = None
minute = None
sec = None
elif char == "eof":
state = "end"
else:
state = "error"
error("got unexpected character reading in duration: " + s)
elif state == "end":
if (sign or week or day or hour or minute or sec):
durations.append(makeTimedelta(sign, week, day, hour, minute,
sec))
return durations
elif state == "error":
error("in error state")
return durations
else:
state = "error"
error("unknown state: '{0!s}' reached in {1!s}".format(state, s)) | [
"def",
"stringToDurations",
"(",
"s",
",",
"strict",
"=",
"False",
")",
":",
"def",
"makeTimedelta",
"(",
"sign",
",",
"week",
",",
"day",
",",
"hour",
",",
"minute",
",",
"sec",
")",
":",
"if",
"sign",
"==",
"\"-\"",
":",
"sign",
"=",
"-",
"1",
"else",
":",
"sign",
"=",
"1",
"week",
"=",
"int",
"(",
"week",
")",
"day",
"=",
"int",
"(",
"day",
")",
"hour",
"=",
"int",
"(",
"hour",
")",
"minute",
"=",
"int",
"(",
"minute",
")",
"sec",
"=",
"int",
"(",
"sec",
")",
"return",
"sign",
"*",
"datetime",
".",
"timedelta",
"(",
"weeks",
"=",
"week",
",",
"days",
"=",
"day",
",",
"hours",
"=",
"hour",
",",
"minutes",
"=",
"minute",
",",
"seconds",
"=",
"sec",
")",
"def",
"error",
"(",
"msg",
")",
":",
"if",
"strict",
":",
"raise",
"ParseError",
"(",
"msg",
")",
"else",
":",
"raise",
"ParseError",
"(",
"msg",
")",
"# vars which control state machine",
"charIterator",
"=",
"enumerate",
"(",
"s",
")",
"state",
"=",
"\"start\"",
"durations",
"=",
"[",
"]",
"current",
"=",
"\"\"",
"sign",
"=",
"None",
"week",
"=",
"0",
"day",
"=",
"0",
"hour",
"=",
"0",
"minute",
"=",
"0",
"sec",
"=",
"0",
"while",
"True",
":",
"try",
":",
"charIndex",
",",
"char",
"=",
"next",
"(",
"charIterator",
")",
"except",
":",
"char",
"=",
"\"eof\"",
"if",
"state",
"==",
"\"start\"",
":",
"if",
"char",
"==",
"'+'",
":",
"state",
"=",
"\"start\"",
"sign",
"=",
"char",
"elif",
"char",
"==",
"'-'",
":",
"state",
"=",
"\"start\"",
"sign",
"=",
"char",
"elif",
"char",
".",
"upper",
"(",
")",
"==",
"'P'",
":",
"state",
"=",
"\"read field\"",
"elif",
"char",
"==",
"\"eof\"",
":",
"state",
"=",
"\"error\"",
"error",
"(",
"\"got end-of-line while reading in duration: \"",
"+",
"s",
")",
"elif",
"char",
"in",
"string",
".",
"digits",
":",
"state",
"=",
"\"read field\"",
"current",
"=",
"current",
"+",
"char",
"# update this part when updating \"read field\"",
"else",
":",
"state",
"=",
"\"error\"",
"error",
"(",
"\"got unexpected character {0} reading in duration: {1}\"",
".",
"format",
"(",
"char",
",",
"s",
")",
")",
"elif",
"state",
"==",
"\"read field\"",
":",
"if",
"(",
"char",
"in",
"string",
".",
"digits",
")",
":",
"state",
"=",
"\"read field\"",
"current",
"=",
"current",
"+",
"char",
"# update part above when updating \"read field\"",
"elif",
"char",
".",
"upper",
"(",
")",
"==",
"'T'",
":",
"state",
"=",
"\"read field\"",
"elif",
"char",
".",
"upper",
"(",
")",
"==",
"'W'",
":",
"state",
"=",
"\"read field\"",
"week",
"=",
"current",
"current",
"=",
"\"\"",
"elif",
"char",
".",
"upper",
"(",
")",
"==",
"'D'",
":",
"state",
"=",
"\"read field\"",
"day",
"=",
"current",
"current",
"=",
"\"\"",
"elif",
"char",
".",
"upper",
"(",
")",
"==",
"'H'",
":",
"state",
"=",
"\"read field\"",
"hour",
"=",
"current",
"current",
"=",
"\"\"",
"elif",
"char",
".",
"upper",
"(",
")",
"==",
"'M'",
":",
"state",
"=",
"\"read field\"",
"minute",
"=",
"current",
"current",
"=",
"\"\"",
"elif",
"char",
".",
"upper",
"(",
")",
"==",
"'S'",
":",
"state",
"=",
"\"read field\"",
"sec",
"=",
"current",
"current",
"=",
"\"\"",
"elif",
"char",
"==",
"\",\"",
":",
"state",
"=",
"\"start\"",
"durations",
".",
"append",
"(",
"makeTimedelta",
"(",
"sign",
",",
"week",
",",
"day",
",",
"hour",
",",
"minute",
",",
"sec",
")",
")",
"current",
"=",
"\"\"",
"sign",
"=",
"None",
"week",
"=",
"None",
"day",
"=",
"None",
"hour",
"=",
"None",
"minute",
"=",
"None",
"sec",
"=",
"None",
"elif",
"char",
"==",
"\"eof\"",
":",
"state",
"=",
"\"end\"",
"else",
":",
"state",
"=",
"\"error\"",
"error",
"(",
"\"got unexpected character reading in duration: \"",
"+",
"s",
")",
"elif",
"state",
"==",
"\"end\"",
":",
"# an end state",
"if",
"(",
"sign",
"or",
"week",
"or",
"day",
"or",
"hour",
"or",
"minute",
"or",
"sec",
")",
":",
"durations",
".",
"append",
"(",
"makeTimedelta",
"(",
"sign",
",",
"week",
",",
"day",
",",
"hour",
",",
"minute",
",",
"sec",
")",
")",
"return",
"durations",
"elif",
"state",
"==",
"\"error\"",
":",
"# an end state",
"error",
"(",
"\"in error state\"",
")",
"return",
"durations",
"else",
":",
"state",
"=",
"\"error\"",
"error",
"(",
"\"unknown state: '{0!s}' reached in {1!s}\"",
".",
"format",
"(",
"state",
",",
"s",
")",
")"
]
| Returns list of timedelta objects. | [
"Returns",
"list",
"of",
"timedelta",
"objects",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1705-L1820 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | parseDtstart | def parseDtstart(contentline, allowSignatureMismatch=False):
"""
Convert a contentline's value into a date or date-time.
A variety of clients don't serialize dates with the appropriate VALUE
parameter, so rather than failing on these (technically invalid) lines,
if allowSignatureMismatch is True, try to parse both varieties.
"""
tzinfo = getTzid(getattr(contentline, 'tzid_param', None))
valueParam = getattr(contentline, 'value_param', 'DATE-TIME').upper()
if valueParam == "DATE":
return stringToDate(contentline.value)
elif valueParam == "DATE-TIME":
try:
return stringToDateTime(contentline.value, tzinfo)
except:
if allowSignatureMismatch:
return stringToDate(contentline.value)
else:
raise | python | def parseDtstart(contentline, allowSignatureMismatch=False):
tzinfo = getTzid(getattr(contentline, 'tzid_param', None))
valueParam = getattr(contentline, 'value_param', 'DATE-TIME').upper()
if valueParam == "DATE":
return stringToDate(contentline.value)
elif valueParam == "DATE-TIME":
try:
return stringToDateTime(contentline.value, tzinfo)
except:
if allowSignatureMismatch:
return stringToDate(contentline.value)
else:
raise | [
"def",
"parseDtstart",
"(",
"contentline",
",",
"allowSignatureMismatch",
"=",
"False",
")",
":",
"tzinfo",
"=",
"getTzid",
"(",
"getattr",
"(",
"contentline",
",",
"'tzid_param'",
",",
"None",
")",
")",
"valueParam",
"=",
"getattr",
"(",
"contentline",
",",
"'value_param'",
",",
"'DATE-TIME'",
")",
".",
"upper",
"(",
")",
"if",
"valueParam",
"==",
"\"DATE\"",
":",
"return",
"stringToDate",
"(",
"contentline",
".",
"value",
")",
"elif",
"valueParam",
"==",
"\"DATE-TIME\"",
":",
"try",
":",
"return",
"stringToDateTime",
"(",
"contentline",
".",
"value",
",",
"tzinfo",
")",
"except",
":",
"if",
"allowSignatureMismatch",
":",
"return",
"stringToDate",
"(",
"contentline",
".",
"value",
")",
"else",
":",
"raise"
]
| Convert a contentline's value into a date or date-time.
A variety of clients don't serialize dates with the appropriate VALUE
parameter, so rather than failing on these (technically invalid) lines,
if allowSignatureMismatch is True, try to parse both varieties. | [
"Convert",
"a",
"contentline",
"s",
"value",
"into",
"a",
"date",
"or",
"date",
"-",
"time",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1823-L1842 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | getTransition | def getTransition(transitionTo, year, tzinfo):
"""
Return the datetime of the transition to/from DST, or None.
"""
def firstTransition(iterDates, test):
"""
Return the last date not matching test, or None if all tests matched.
"""
success = None
for dt in iterDates:
if not test(dt):
success = dt
else:
if success is not None:
return success
return success # may be None
def generateDates(year, month=None, day=None):
"""
Iterate over possible dates with unspecified values.
"""
months = range(1, 13)
days = range(1, 32)
hours = range(0, 24)
if month is None:
for month in months:
yield datetime.datetime(year, month, 1)
elif day is None:
for day in days:
try:
yield datetime.datetime(year, month, day)
except ValueError:
pass
else:
for hour in hours:
yield datetime.datetime(year, month, day, hour)
assert transitionTo in ('daylight', 'standard')
if transitionTo == 'daylight':
def test(dt):
try:
return tzinfo.dst(dt) != zeroDelta
except pytz.NonExistentTimeError:
return True # entering daylight time
except pytz.AmbiguousTimeError:
return False # entering standard time
elif transitionTo == 'standard':
def test(dt):
try:
return tzinfo.dst(dt) == zeroDelta
except pytz.NonExistentTimeError:
return False # entering daylight time
except pytz.AmbiguousTimeError:
return True # entering standard time
newyear = datetime.datetime(year, 1, 1)
monthDt = firstTransition(generateDates(year), test)
if monthDt is None:
return newyear
elif monthDt.month == 12:
return None
else:
# there was a good transition somewhere in a non-December month
month = monthDt.month
day = firstTransition(generateDates(year, month), test).day
uncorrected = firstTransition(generateDates(year, month, day), test)
if transitionTo == 'standard':
# assuming tzinfo.dst returns a new offset for the first
# possible hour, we need to add one hour for the offset change
# and another hour because firstTransition returns the hour
# before the transition
return uncorrected + datetime.timedelta(hours=2)
else:
return uncorrected + datetime.timedelta(hours=1) | python | def getTransition(transitionTo, year, tzinfo):
def firstTransition(iterDates, test):
success = None
for dt in iterDates:
if not test(dt):
success = dt
else:
if success is not None:
return success
return success
def generateDates(year, month=None, day=None):
months = range(1, 13)
days = range(1, 32)
hours = range(0, 24)
if month is None:
for month in months:
yield datetime.datetime(year, month, 1)
elif day is None:
for day in days:
try:
yield datetime.datetime(year, month, day)
except ValueError:
pass
else:
for hour in hours:
yield datetime.datetime(year, month, day, hour)
assert transitionTo in ('daylight', 'standard')
if transitionTo == 'daylight':
def test(dt):
try:
return tzinfo.dst(dt) != zeroDelta
except pytz.NonExistentTimeError:
return True
except pytz.AmbiguousTimeError:
return False
elif transitionTo == 'standard':
def test(dt):
try:
return tzinfo.dst(dt) == zeroDelta
except pytz.NonExistentTimeError:
return False
except pytz.AmbiguousTimeError:
return True
newyear = datetime.datetime(year, 1, 1)
monthDt = firstTransition(generateDates(year), test)
if monthDt is None:
return newyear
elif monthDt.month == 12:
return None
else:
month = monthDt.month
day = firstTransition(generateDates(year, month), test).day
uncorrected = firstTransition(generateDates(year, month, day), test)
if transitionTo == 'standard':
return uncorrected + datetime.timedelta(hours=2)
else:
return uncorrected + datetime.timedelta(hours=1) | [
"def",
"getTransition",
"(",
"transitionTo",
",",
"year",
",",
"tzinfo",
")",
":",
"def",
"firstTransition",
"(",
"iterDates",
",",
"test",
")",
":",
"\"\"\"\n Return the last date not matching test, or None if all tests matched.\n \"\"\"",
"success",
"=",
"None",
"for",
"dt",
"in",
"iterDates",
":",
"if",
"not",
"test",
"(",
"dt",
")",
":",
"success",
"=",
"dt",
"else",
":",
"if",
"success",
"is",
"not",
"None",
":",
"return",
"success",
"return",
"success",
"# may be None",
"def",
"generateDates",
"(",
"year",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
")",
":",
"\"\"\"\n Iterate over possible dates with unspecified values.\n \"\"\"",
"months",
"=",
"range",
"(",
"1",
",",
"13",
")",
"days",
"=",
"range",
"(",
"1",
",",
"32",
")",
"hours",
"=",
"range",
"(",
"0",
",",
"24",
")",
"if",
"month",
"is",
"None",
":",
"for",
"month",
"in",
"months",
":",
"yield",
"datetime",
".",
"datetime",
"(",
"year",
",",
"month",
",",
"1",
")",
"elif",
"day",
"is",
"None",
":",
"for",
"day",
"in",
"days",
":",
"try",
":",
"yield",
"datetime",
".",
"datetime",
"(",
"year",
",",
"month",
",",
"day",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"for",
"hour",
"in",
"hours",
":",
"yield",
"datetime",
".",
"datetime",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
")",
"assert",
"transitionTo",
"in",
"(",
"'daylight'",
",",
"'standard'",
")",
"if",
"transitionTo",
"==",
"'daylight'",
":",
"def",
"test",
"(",
"dt",
")",
":",
"try",
":",
"return",
"tzinfo",
".",
"dst",
"(",
"dt",
")",
"!=",
"zeroDelta",
"except",
"pytz",
".",
"NonExistentTimeError",
":",
"return",
"True",
"# entering daylight time",
"except",
"pytz",
".",
"AmbiguousTimeError",
":",
"return",
"False",
"# entering standard time",
"elif",
"transitionTo",
"==",
"'standard'",
":",
"def",
"test",
"(",
"dt",
")",
":",
"try",
":",
"return",
"tzinfo",
".",
"dst",
"(",
"dt",
")",
"==",
"zeroDelta",
"except",
"pytz",
".",
"NonExistentTimeError",
":",
"return",
"False",
"# entering daylight time",
"except",
"pytz",
".",
"AmbiguousTimeError",
":",
"return",
"True",
"# entering standard time",
"newyear",
"=",
"datetime",
".",
"datetime",
"(",
"year",
",",
"1",
",",
"1",
")",
"monthDt",
"=",
"firstTransition",
"(",
"generateDates",
"(",
"year",
")",
",",
"test",
")",
"if",
"monthDt",
"is",
"None",
":",
"return",
"newyear",
"elif",
"monthDt",
".",
"month",
"==",
"12",
":",
"return",
"None",
"else",
":",
"# there was a good transition somewhere in a non-December month",
"month",
"=",
"monthDt",
".",
"month",
"day",
"=",
"firstTransition",
"(",
"generateDates",
"(",
"year",
",",
"month",
")",
",",
"test",
")",
".",
"day",
"uncorrected",
"=",
"firstTransition",
"(",
"generateDates",
"(",
"year",
",",
"month",
",",
"day",
")",
",",
"test",
")",
"if",
"transitionTo",
"==",
"'standard'",
":",
"# assuming tzinfo.dst returns a new offset for the first",
"# possible hour, we need to add one hour for the offset change",
"# and another hour because firstTransition returns the hour",
"# before the transition",
"return",
"uncorrected",
"+",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"2",
")",
"else",
":",
"return",
"uncorrected",
"+",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"1",
")"
]
| Return the datetime of the transition to/from DST, or None. | [
"Return",
"the",
"datetime",
"of",
"the",
"transition",
"to",
"/",
"from",
"DST",
"or",
"None",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1855-L1927 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | tzinfo_eq | def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020):
"""
Compare offsets and DST transitions from startYear to endYear.
"""
if tzinfo1 == tzinfo2:
return True
elif tzinfo1 is None or tzinfo2 is None:
return False
def dt_test(dt):
if dt is None:
return True
return tzinfo1.utcoffset(dt) == tzinfo2.utcoffset(dt)
if not dt_test(datetime.datetime(startYear, 1, 1)):
return False
for year in range(startYear, endYear):
for transitionTo in 'daylight', 'standard':
t1=getTransition(transitionTo, year, tzinfo1)
t2=getTransition(transitionTo, year, tzinfo2)
if t1 != t2 or not dt_test(t1):
return False
return True | python | def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020):
if tzinfo1 == tzinfo2:
return True
elif tzinfo1 is None or tzinfo2 is None:
return False
def dt_test(dt):
if dt is None:
return True
return tzinfo1.utcoffset(dt) == tzinfo2.utcoffset(dt)
if not dt_test(datetime.datetime(startYear, 1, 1)):
return False
for year in range(startYear, endYear):
for transitionTo in 'daylight', 'standard':
t1=getTransition(transitionTo, year, tzinfo1)
t2=getTransition(transitionTo, year, tzinfo2)
if t1 != t2 or not dt_test(t1):
return False
return True | [
"def",
"tzinfo_eq",
"(",
"tzinfo1",
",",
"tzinfo2",
",",
"startYear",
"=",
"2000",
",",
"endYear",
"=",
"2020",
")",
":",
"if",
"tzinfo1",
"==",
"tzinfo2",
":",
"return",
"True",
"elif",
"tzinfo1",
"is",
"None",
"or",
"tzinfo2",
"is",
"None",
":",
"return",
"False",
"def",
"dt_test",
"(",
"dt",
")",
":",
"if",
"dt",
"is",
"None",
":",
"return",
"True",
"return",
"tzinfo1",
".",
"utcoffset",
"(",
"dt",
")",
"==",
"tzinfo2",
".",
"utcoffset",
"(",
"dt",
")",
"if",
"not",
"dt_test",
"(",
"datetime",
".",
"datetime",
"(",
"startYear",
",",
"1",
",",
"1",
")",
")",
":",
"return",
"False",
"for",
"year",
"in",
"range",
"(",
"startYear",
",",
"endYear",
")",
":",
"for",
"transitionTo",
"in",
"'daylight'",
",",
"'standard'",
":",
"t1",
"=",
"getTransition",
"(",
"transitionTo",
",",
"year",
",",
"tzinfo1",
")",
"t2",
"=",
"getTransition",
"(",
"transitionTo",
",",
"year",
",",
"tzinfo2",
")",
"if",
"t1",
"!=",
"t2",
"or",
"not",
"dt_test",
"(",
"t1",
")",
":",
"return",
"False",
"return",
"True"
]
| Compare offsets and DST transitions from startYear to endYear. | [
"Compare",
"offsets",
"and",
"DST",
"transitions",
"from",
"startYear",
"to",
"endYear",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1929-L1951 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | TimezoneComponent.registerTzinfo | def registerTzinfo(obj, tzinfo):
"""
Register tzinfo if it's not already registered, return its tzid.
"""
tzid = obj.pickTzid(tzinfo)
if tzid and not getTzid(tzid, False):
registerTzid(tzid, tzinfo)
return tzid | python | def registerTzinfo(obj, tzinfo):
tzid = obj.pickTzid(tzinfo)
if tzid and not getTzid(tzid, False):
registerTzid(tzid, tzinfo)
return tzid | [
"def",
"registerTzinfo",
"(",
"obj",
",",
"tzinfo",
")",
":",
"tzid",
"=",
"obj",
".",
"pickTzid",
"(",
"tzinfo",
")",
"if",
"tzid",
"and",
"not",
"getTzid",
"(",
"tzid",
",",
"False",
")",
":",
"registerTzid",
"(",
"tzid",
",",
"tzinfo",
")",
"return",
"tzid"
]
| Register tzinfo if it's not already registered, return its tzid. | [
"Register",
"tzinfo",
"if",
"it",
"s",
"not",
"already",
"registered",
"return",
"its",
"tzid",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L121-L128 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | TimezoneComponent.settzinfo | def settzinfo(self, tzinfo, start=2000, end=2030):
"""
Create appropriate objects in self to represent tzinfo.
Collapse DST transitions to rrules as much as possible.
Assumptions:
- DST <-> Standard transitions occur on the hour
- never within a month of one another
- twice or fewer times a year
- never in the month of December
- DST always moves offset exactly one hour later
- tzinfo classes dst method always treats times that could be in either
offset as being in the later regime
"""
def fromLastWeek(dt):
"""
How many weeks from the end of the month dt is, starting from 1.
"""
weekDelta = datetime.timedelta(weeks=1)
n = 1
current = dt + weekDelta
while current.month == dt.month:
n += 1
current += weekDelta
return n
# lists of dictionaries defining rules which are no longer in effect
completed = {'daylight' : [], 'standard' : []}
# dictionary defining rules which are currently in effect
working = {'daylight' : None, 'standard' : None}
# rule may be based on nth week of the month or the nth from the last
for year in range(start, end + 1):
newyear = datetime.datetime(year, 1, 1)
for transitionTo in 'daylight', 'standard':
transition = getTransition(transitionTo, year, tzinfo)
oldrule = working[transitionTo]
if transition == newyear:
# transitionTo is in effect for the whole year
rule = {'end' : None,
'start' : newyear,
'month' : 1,
'weekday' : None,
'hour' : None,
'plus' : None,
'minus' : None,
'name' : tzinfo.tzname(newyear),
'offset' : tzinfo.utcoffset(newyear),
'offsetfrom' : tzinfo.utcoffset(newyear)}
if oldrule is None:
# transitionTo was not yet in effect
working[transitionTo] = rule
else:
# transitionTo was already in effect
if (oldrule['offset'] !=
tzinfo.utcoffset(newyear)):
# old rule was different, it shouldn't continue
oldrule['end'] = year - 1
completed[transitionTo].append(oldrule)
working[transitionTo] = rule
elif transition is None:
# transitionTo is not in effect
if oldrule is not None:
# transitionTo used to be in effect
oldrule['end'] = year - 1
completed[transitionTo].append(oldrule)
working[transitionTo] = None
else:
# an offset transition was found
try:
old_offset = tzinfo.utcoffset(transition - twoHours)
name = tzinfo.tzname(transition)
offset = tzinfo.utcoffset(transition)
except (pytz.AmbiguousTimeError, pytz.NonExistentTimeError):
# guaranteed that tzinfo is a pytz timezone
is_dst = (transitionTo == "daylight")
old_offset = tzinfo.utcoffset(transition - twoHours, is_dst=is_dst)
name = tzinfo.tzname(transition, is_dst=is_dst)
offset = tzinfo.utcoffset(transition, is_dst=is_dst)
rule = {'end' : None, # None, or an integer year
'start' : transition, # the datetime of transition
'month' : transition.month,
'weekday' : transition.weekday(),
'hour' : transition.hour,
'name' : name,
'plus' : int(
(transition.day - 1)/ 7 + 1), # nth week of the month
'minus' : fromLastWeek(transition), # nth from last week
'offset' : offset,
'offsetfrom' : old_offset}
if oldrule is None:
working[transitionTo] = rule
else:
plusMatch = rule['plus'] == oldrule['plus']
minusMatch = rule['minus'] == oldrule['minus']
truth = plusMatch or minusMatch
for key in 'month', 'weekday', 'hour', 'offset':
truth = truth and rule[key] == oldrule[key]
if truth:
# the old rule is still true, limit to plus or minus
if not plusMatch:
oldrule['plus'] = None
if not minusMatch:
oldrule['minus'] = None
else:
# the new rule did not match the old
oldrule['end'] = year - 1
completed[transitionTo].append(oldrule)
working[transitionTo] = rule
for transitionTo in 'daylight', 'standard':
if working[transitionTo] is not None:
completed[transitionTo].append(working[transitionTo])
self.tzid = []
self.daylight = []
self.standard = []
self.add('tzid').value = self.pickTzid(tzinfo, True)
# old = None # unused?
for transitionTo in 'daylight', 'standard':
for rule in completed[transitionTo]:
comp = self.add(transitionTo)
dtstart = comp.add('dtstart')
dtstart.value = rule['start']
if rule['name'] is not None:
comp.add('tzname').value = rule['name']
line = comp.add('tzoffsetto')
line.value = deltaToOffset(rule['offset'])
line = comp.add('tzoffsetfrom')
line.value = deltaToOffset(rule['offsetfrom'])
if rule['plus'] is not None:
num = rule['plus']
elif rule['minus'] is not None:
num = -1 * rule['minus']
else:
num = None
if num is not None:
dayString = ";BYDAY=" + str(num) + WEEKDAYS[rule['weekday']]
else:
dayString = ""
if rule['end'] is not None:
if rule['hour'] is None:
# all year offset, with no rule
endDate = datetime.datetime(rule['end'], 1, 1)
else:
weekday = rrule.weekday(rule['weekday'], num)
du_rule = rrule.rrule(rrule.YEARLY,
bymonth = rule['month'],byweekday = weekday,
dtstart = datetime.datetime(
rule['end'], 1, 1, rule['hour'])
)
endDate = du_rule[0]
endDate = endDate.replace(tzinfo = utc) - rule['offsetfrom']
endString = ";UNTIL="+ dateTimeToString(endDate)
else:
endString = ''
new_rule = "FREQ=YEARLY{0!s};BYMONTH={1!s}{2!s}"\
.format(dayString, rule['month'], endString)
comp.add('rrule').value = new_rule | python | def settzinfo(self, tzinfo, start=2000, end=2030):
def fromLastWeek(dt):
weekDelta = datetime.timedelta(weeks=1)
n = 1
current = dt + weekDelta
while current.month == dt.month:
n += 1
current += weekDelta
return n
completed = {'daylight' : [], 'standard' : []}
working = {'daylight' : None, 'standard' : None}
for year in range(start, end + 1):
newyear = datetime.datetime(year, 1, 1)
for transitionTo in 'daylight', 'standard':
transition = getTransition(transitionTo, year, tzinfo)
oldrule = working[transitionTo]
if transition == newyear:
rule = {'end' : None,
'start' : newyear,
'month' : 1,
'weekday' : None,
'hour' : None,
'plus' : None,
'minus' : None,
'name' : tzinfo.tzname(newyear),
'offset' : tzinfo.utcoffset(newyear),
'offsetfrom' : tzinfo.utcoffset(newyear)}
if oldrule is None:
working[transitionTo] = rule
else:
if (oldrule['offset'] !=
tzinfo.utcoffset(newyear)):
oldrule['end'] = year - 1
completed[transitionTo].append(oldrule)
working[transitionTo] = rule
elif transition is None:
if oldrule is not None:
oldrule['end'] = year - 1
completed[transitionTo].append(oldrule)
working[transitionTo] = None
else:
try:
old_offset = tzinfo.utcoffset(transition - twoHours)
name = tzinfo.tzname(transition)
offset = tzinfo.utcoffset(transition)
except (pytz.AmbiguousTimeError, pytz.NonExistentTimeError):
is_dst = (transitionTo == "daylight")
old_offset = tzinfo.utcoffset(transition - twoHours, is_dst=is_dst)
name = tzinfo.tzname(transition, is_dst=is_dst)
offset = tzinfo.utcoffset(transition, is_dst=is_dst)
rule = {'end' : None,
'start' : transition,
'month' : transition.month,
'weekday' : transition.weekday(),
'hour' : transition.hour,
'name' : name,
'plus' : int(
(transition.day - 1)/ 7 + 1),
'minus' : fromLastWeek(transition),
'offset' : offset,
'offsetfrom' : old_offset}
if oldrule is None:
working[transitionTo] = rule
else:
plusMatch = rule['plus'] == oldrule['plus']
minusMatch = rule['minus'] == oldrule['minus']
truth = plusMatch or minusMatch
for key in 'month', 'weekday', 'hour', 'offset':
truth = truth and rule[key] == oldrule[key]
if truth:
if not plusMatch:
oldrule['plus'] = None
if not minusMatch:
oldrule['minus'] = None
else:
oldrule['end'] = year - 1
completed[transitionTo].append(oldrule)
working[transitionTo] = rule
for transitionTo in 'daylight', 'standard':
if working[transitionTo] is not None:
completed[transitionTo].append(working[transitionTo])
self.tzid = []
self.daylight = []
self.standard = []
self.add('tzid').value = self.pickTzid(tzinfo, True)
for transitionTo in 'daylight', 'standard':
for rule in completed[transitionTo]:
comp = self.add(transitionTo)
dtstart = comp.add('dtstart')
dtstart.value = rule['start']
if rule['name'] is not None:
comp.add('tzname').value = rule['name']
line = comp.add('tzoffsetto')
line.value = deltaToOffset(rule['offset'])
line = comp.add('tzoffsetfrom')
line.value = deltaToOffset(rule['offsetfrom'])
if rule['plus'] is not None:
num = rule['plus']
elif rule['minus'] is not None:
num = -1 * rule['minus']
else:
num = None
if num is not None:
dayString = ";BYDAY=" + str(num) + WEEKDAYS[rule['weekday']]
else:
dayString = ""
if rule['end'] is not None:
if rule['hour'] is None:
endDate = datetime.datetime(rule['end'], 1, 1)
else:
weekday = rrule.weekday(rule['weekday'], num)
du_rule = rrule.rrule(rrule.YEARLY,
bymonth = rule['month'],byweekday = weekday,
dtstart = datetime.datetime(
rule['end'], 1, 1, rule['hour'])
)
endDate = du_rule[0]
endDate = endDate.replace(tzinfo = utc) - rule['offsetfrom']
endString = ";UNTIL="+ dateTimeToString(endDate)
else:
endString = ''
new_rule = "FREQ=YEARLY{0!s};BYMONTH={1!s}{2!s}"\
.format(dayString, rule['month'], endString)
comp.add('rrule').value = new_rule | [
"def",
"settzinfo",
"(",
"self",
",",
"tzinfo",
",",
"start",
"=",
"2000",
",",
"end",
"=",
"2030",
")",
":",
"def",
"fromLastWeek",
"(",
"dt",
")",
":",
"\"\"\"\n How many weeks from the end of the month dt is, starting from 1.\n \"\"\"",
"weekDelta",
"=",
"datetime",
".",
"timedelta",
"(",
"weeks",
"=",
"1",
")",
"n",
"=",
"1",
"current",
"=",
"dt",
"+",
"weekDelta",
"while",
"current",
".",
"month",
"==",
"dt",
".",
"month",
":",
"n",
"+=",
"1",
"current",
"+=",
"weekDelta",
"return",
"n",
"# lists of dictionaries defining rules which are no longer in effect",
"completed",
"=",
"{",
"'daylight'",
":",
"[",
"]",
",",
"'standard'",
":",
"[",
"]",
"}",
"# dictionary defining rules which are currently in effect",
"working",
"=",
"{",
"'daylight'",
":",
"None",
",",
"'standard'",
":",
"None",
"}",
"# rule may be based on nth week of the month or the nth from the last",
"for",
"year",
"in",
"range",
"(",
"start",
",",
"end",
"+",
"1",
")",
":",
"newyear",
"=",
"datetime",
".",
"datetime",
"(",
"year",
",",
"1",
",",
"1",
")",
"for",
"transitionTo",
"in",
"'daylight'",
",",
"'standard'",
":",
"transition",
"=",
"getTransition",
"(",
"transitionTo",
",",
"year",
",",
"tzinfo",
")",
"oldrule",
"=",
"working",
"[",
"transitionTo",
"]",
"if",
"transition",
"==",
"newyear",
":",
"# transitionTo is in effect for the whole year",
"rule",
"=",
"{",
"'end'",
":",
"None",
",",
"'start'",
":",
"newyear",
",",
"'month'",
":",
"1",
",",
"'weekday'",
":",
"None",
",",
"'hour'",
":",
"None",
",",
"'plus'",
":",
"None",
",",
"'minus'",
":",
"None",
",",
"'name'",
":",
"tzinfo",
".",
"tzname",
"(",
"newyear",
")",
",",
"'offset'",
":",
"tzinfo",
".",
"utcoffset",
"(",
"newyear",
")",
",",
"'offsetfrom'",
":",
"tzinfo",
".",
"utcoffset",
"(",
"newyear",
")",
"}",
"if",
"oldrule",
"is",
"None",
":",
"# transitionTo was not yet in effect",
"working",
"[",
"transitionTo",
"]",
"=",
"rule",
"else",
":",
"# transitionTo was already in effect",
"if",
"(",
"oldrule",
"[",
"'offset'",
"]",
"!=",
"tzinfo",
".",
"utcoffset",
"(",
"newyear",
")",
")",
":",
"# old rule was different, it shouldn't continue",
"oldrule",
"[",
"'end'",
"]",
"=",
"year",
"-",
"1",
"completed",
"[",
"transitionTo",
"]",
".",
"append",
"(",
"oldrule",
")",
"working",
"[",
"transitionTo",
"]",
"=",
"rule",
"elif",
"transition",
"is",
"None",
":",
"# transitionTo is not in effect",
"if",
"oldrule",
"is",
"not",
"None",
":",
"# transitionTo used to be in effect",
"oldrule",
"[",
"'end'",
"]",
"=",
"year",
"-",
"1",
"completed",
"[",
"transitionTo",
"]",
".",
"append",
"(",
"oldrule",
")",
"working",
"[",
"transitionTo",
"]",
"=",
"None",
"else",
":",
"# an offset transition was found",
"try",
":",
"old_offset",
"=",
"tzinfo",
".",
"utcoffset",
"(",
"transition",
"-",
"twoHours",
")",
"name",
"=",
"tzinfo",
".",
"tzname",
"(",
"transition",
")",
"offset",
"=",
"tzinfo",
".",
"utcoffset",
"(",
"transition",
")",
"except",
"(",
"pytz",
".",
"AmbiguousTimeError",
",",
"pytz",
".",
"NonExistentTimeError",
")",
":",
"# guaranteed that tzinfo is a pytz timezone",
"is_dst",
"=",
"(",
"transitionTo",
"==",
"\"daylight\"",
")",
"old_offset",
"=",
"tzinfo",
".",
"utcoffset",
"(",
"transition",
"-",
"twoHours",
",",
"is_dst",
"=",
"is_dst",
")",
"name",
"=",
"tzinfo",
".",
"tzname",
"(",
"transition",
",",
"is_dst",
"=",
"is_dst",
")",
"offset",
"=",
"tzinfo",
".",
"utcoffset",
"(",
"transition",
",",
"is_dst",
"=",
"is_dst",
")",
"rule",
"=",
"{",
"'end'",
":",
"None",
",",
"# None, or an integer year",
"'start'",
":",
"transition",
",",
"# the datetime of transition",
"'month'",
":",
"transition",
".",
"month",
",",
"'weekday'",
":",
"transition",
".",
"weekday",
"(",
")",
",",
"'hour'",
":",
"transition",
".",
"hour",
",",
"'name'",
":",
"name",
",",
"'plus'",
":",
"int",
"(",
"(",
"transition",
".",
"day",
"-",
"1",
")",
"/",
"7",
"+",
"1",
")",
",",
"# nth week of the month",
"'minus'",
":",
"fromLastWeek",
"(",
"transition",
")",
",",
"# nth from last week",
"'offset'",
":",
"offset",
",",
"'offsetfrom'",
":",
"old_offset",
"}",
"if",
"oldrule",
"is",
"None",
":",
"working",
"[",
"transitionTo",
"]",
"=",
"rule",
"else",
":",
"plusMatch",
"=",
"rule",
"[",
"'plus'",
"]",
"==",
"oldrule",
"[",
"'plus'",
"]",
"minusMatch",
"=",
"rule",
"[",
"'minus'",
"]",
"==",
"oldrule",
"[",
"'minus'",
"]",
"truth",
"=",
"plusMatch",
"or",
"minusMatch",
"for",
"key",
"in",
"'month'",
",",
"'weekday'",
",",
"'hour'",
",",
"'offset'",
":",
"truth",
"=",
"truth",
"and",
"rule",
"[",
"key",
"]",
"==",
"oldrule",
"[",
"key",
"]",
"if",
"truth",
":",
"# the old rule is still true, limit to plus or minus",
"if",
"not",
"plusMatch",
":",
"oldrule",
"[",
"'plus'",
"]",
"=",
"None",
"if",
"not",
"minusMatch",
":",
"oldrule",
"[",
"'minus'",
"]",
"=",
"None",
"else",
":",
"# the new rule did not match the old",
"oldrule",
"[",
"'end'",
"]",
"=",
"year",
"-",
"1",
"completed",
"[",
"transitionTo",
"]",
".",
"append",
"(",
"oldrule",
")",
"working",
"[",
"transitionTo",
"]",
"=",
"rule",
"for",
"transitionTo",
"in",
"'daylight'",
",",
"'standard'",
":",
"if",
"working",
"[",
"transitionTo",
"]",
"is",
"not",
"None",
":",
"completed",
"[",
"transitionTo",
"]",
".",
"append",
"(",
"working",
"[",
"transitionTo",
"]",
")",
"self",
".",
"tzid",
"=",
"[",
"]",
"self",
".",
"daylight",
"=",
"[",
"]",
"self",
".",
"standard",
"=",
"[",
"]",
"self",
".",
"add",
"(",
"'tzid'",
")",
".",
"value",
"=",
"self",
".",
"pickTzid",
"(",
"tzinfo",
",",
"True",
")",
"# old = None # unused?",
"for",
"transitionTo",
"in",
"'daylight'",
",",
"'standard'",
":",
"for",
"rule",
"in",
"completed",
"[",
"transitionTo",
"]",
":",
"comp",
"=",
"self",
".",
"add",
"(",
"transitionTo",
")",
"dtstart",
"=",
"comp",
".",
"add",
"(",
"'dtstart'",
")",
"dtstart",
".",
"value",
"=",
"rule",
"[",
"'start'",
"]",
"if",
"rule",
"[",
"'name'",
"]",
"is",
"not",
"None",
":",
"comp",
".",
"add",
"(",
"'tzname'",
")",
".",
"value",
"=",
"rule",
"[",
"'name'",
"]",
"line",
"=",
"comp",
".",
"add",
"(",
"'tzoffsetto'",
")",
"line",
".",
"value",
"=",
"deltaToOffset",
"(",
"rule",
"[",
"'offset'",
"]",
")",
"line",
"=",
"comp",
".",
"add",
"(",
"'tzoffsetfrom'",
")",
"line",
".",
"value",
"=",
"deltaToOffset",
"(",
"rule",
"[",
"'offsetfrom'",
"]",
")",
"if",
"rule",
"[",
"'plus'",
"]",
"is",
"not",
"None",
":",
"num",
"=",
"rule",
"[",
"'plus'",
"]",
"elif",
"rule",
"[",
"'minus'",
"]",
"is",
"not",
"None",
":",
"num",
"=",
"-",
"1",
"*",
"rule",
"[",
"'minus'",
"]",
"else",
":",
"num",
"=",
"None",
"if",
"num",
"is",
"not",
"None",
":",
"dayString",
"=",
"\";BYDAY=\"",
"+",
"str",
"(",
"num",
")",
"+",
"WEEKDAYS",
"[",
"rule",
"[",
"'weekday'",
"]",
"]",
"else",
":",
"dayString",
"=",
"\"\"",
"if",
"rule",
"[",
"'end'",
"]",
"is",
"not",
"None",
":",
"if",
"rule",
"[",
"'hour'",
"]",
"is",
"None",
":",
"# all year offset, with no rule",
"endDate",
"=",
"datetime",
".",
"datetime",
"(",
"rule",
"[",
"'end'",
"]",
",",
"1",
",",
"1",
")",
"else",
":",
"weekday",
"=",
"rrule",
".",
"weekday",
"(",
"rule",
"[",
"'weekday'",
"]",
",",
"num",
")",
"du_rule",
"=",
"rrule",
".",
"rrule",
"(",
"rrule",
".",
"YEARLY",
",",
"bymonth",
"=",
"rule",
"[",
"'month'",
"]",
",",
"byweekday",
"=",
"weekday",
",",
"dtstart",
"=",
"datetime",
".",
"datetime",
"(",
"rule",
"[",
"'end'",
"]",
",",
"1",
",",
"1",
",",
"rule",
"[",
"'hour'",
"]",
")",
")",
"endDate",
"=",
"du_rule",
"[",
"0",
"]",
"endDate",
"=",
"endDate",
".",
"replace",
"(",
"tzinfo",
"=",
"utc",
")",
"-",
"rule",
"[",
"'offsetfrom'",
"]",
"endString",
"=",
"\";UNTIL=\"",
"+",
"dateTimeToString",
"(",
"endDate",
")",
"else",
":",
"endString",
"=",
"''",
"new_rule",
"=",
"\"FREQ=YEARLY{0!s};BYMONTH={1!s}{2!s}\"",
".",
"format",
"(",
"dayString",
",",
"rule",
"[",
"'month'",
"]",
",",
"endString",
")",
"comp",
".",
"add",
"(",
"'rrule'",
")",
".",
"value",
"=",
"new_rule"
]
| Create appropriate objects in self to represent tzinfo.
Collapse DST transitions to rrules as much as possible.
Assumptions:
- DST <-> Standard transitions occur on the hour
- never within a month of one another
- twice or fewer times a year
- never in the month of December
- DST always moves offset exactly one hour later
- tzinfo classes dst method always treats times that could be in either
offset as being in the later regime | [
"Create",
"appropriate",
"objects",
"in",
"self",
"to",
"represent",
"tzinfo",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L152-L318 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | TimezoneComponent.pickTzid | def pickTzid(tzinfo, allowUTC=False):
"""
Given a tzinfo class, use known APIs to determine TZID, or use tzname.
"""
if tzinfo is None or (not allowUTC and tzinfo_eq(tzinfo, utc)):
# If tzinfo is UTC, we don't need a TZID
return None
# try PyICU's tzid key
if hasattr(tzinfo, 'tzid'):
return toUnicode(tzinfo.tzid)
# try pytz zone key
if hasattr(tzinfo, 'zone'):
return toUnicode(tzinfo.zone)
# try tzical's tzid key
elif hasattr(tzinfo, '_tzid'):
return toUnicode(tzinfo._tzid)
else:
# return tzname for standard (non-DST) time
notDST = datetime.timedelta(0)
for month in range(1, 13):
dt = datetime.datetime(2000, month, 1)
if tzinfo.dst(dt) == notDST:
return toUnicode(tzinfo.tzname(dt))
# there was no standard time in 2000!
raise VObjectError("Unable to guess TZID for tzinfo {0!s}"
.format(tzinfo)) | python | def pickTzid(tzinfo, allowUTC=False):
if tzinfo is None or (not allowUTC and tzinfo_eq(tzinfo, utc)):
return None
if hasattr(tzinfo, 'tzid'):
return toUnicode(tzinfo.tzid)
if hasattr(tzinfo, 'zone'):
return toUnicode(tzinfo.zone)
elif hasattr(tzinfo, '_tzid'):
return toUnicode(tzinfo._tzid)
else:
notDST = datetime.timedelta(0)
for month in range(1, 13):
dt = datetime.datetime(2000, month, 1)
if tzinfo.dst(dt) == notDST:
return toUnicode(tzinfo.tzname(dt))
raise VObjectError("Unable to guess TZID for tzinfo {0!s}"
.format(tzinfo)) | [
"def",
"pickTzid",
"(",
"tzinfo",
",",
"allowUTC",
"=",
"False",
")",
":",
"if",
"tzinfo",
"is",
"None",
"or",
"(",
"not",
"allowUTC",
"and",
"tzinfo_eq",
"(",
"tzinfo",
",",
"utc",
")",
")",
":",
"# If tzinfo is UTC, we don't need a TZID",
"return",
"None",
"# try PyICU's tzid key",
"if",
"hasattr",
"(",
"tzinfo",
",",
"'tzid'",
")",
":",
"return",
"toUnicode",
"(",
"tzinfo",
".",
"tzid",
")",
"# try pytz zone key",
"if",
"hasattr",
"(",
"tzinfo",
",",
"'zone'",
")",
":",
"return",
"toUnicode",
"(",
"tzinfo",
".",
"zone",
")",
"# try tzical's tzid key",
"elif",
"hasattr",
"(",
"tzinfo",
",",
"'_tzid'",
")",
":",
"return",
"toUnicode",
"(",
"tzinfo",
".",
"_tzid",
")",
"else",
":",
"# return tzname for standard (non-DST) time",
"notDST",
"=",
"datetime",
".",
"timedelta",
"(",
"0",
")",
"for",
"month",
"in",
"range",
"(",
"1",
",",
"13",
")",
":",
"dt",
"=",
"datetime",
".",
"datetime",
"(",
"2000",
",",
"month",
",",
"1",
")",
"if",
"tzinfo",
".",
"dst",
"(",
"dt",
")",
"==",
"notDST",
":",
"return",
"toUnicode",
"(",
"tzinfo",
".",
"tzname",
"(",
"dt",
")",
")",
"# there was no standard time in 2000!",
"raise",
"VObjectError",
"(",
"\"Unable to guess TZID for tzinfo {0!s}\"",
".",
"format",
"(",
"tzinfo",
")",
")"
]
| Given a tzinfo class, use known APIs to determine TZID, or use tzname. | [
"Given",
"a",
"tzinfo",
"class",
"use",
"known",
"APIs",
"to",
"determine",
"TZID",
"or",
"use",
"tzname",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L325-L352 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | TextBehavior.decode | def decode(cls, line):
"""
Remove backslash escaping from line.value.
"""
if line.encoded:
encoding = getattr(line, 'encoding_param', None)
if encoding and encoding.upper() == cls.base64string:
line.value = codecs.decode(self.value.encode("utf-8"), "base64").decode(encoding)
else:
line.value = stringToTextValues(line.value)[0]
line.encoded=False | python | def decode(cls, line):
if line.encoded:
encoding = getattr(line, 'encoding_param', None)
if encoding and encoding.upper() == cls.base64string:
line.value = codecs.decode(self.value.encode("utf-8"), "base64").decode(encoding)
else:
line.value = stringToTextValues(line.value)[0]
line.encoded=False | [
"def",
"decode",
"(",
"cls",
",",
"line",
")",
":",
"if",
"line",
".",
"encoded",
":",
"encoding",
"=",
"getattr",
"(",
"line",
",",
"'encoding_param'",
",",
"None",
")",
"if",
"encoding",
"and",
"encoding",
".",
"upper",
"(",
")",
"==",
"cls",
".",
"base64string",
":",
"line",
".",
"value",
"=",
"codecs",
".",
"decode",
"(",
"self",
".",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"\"base64\"",
")",
".",
"decode",
"(",
"encoding",
")",
"else",
":",
"line",
".",
"value",
"=",
"stringToTextValues",
"(",
"line",
".",
"value",
")",
"[",
"0",
"]",
"line",
".",
"encoded",
"=",
"False"
]
| Remove backslash escaping from line.value. | [
"Remove",
"backslash",
"escaping",
"from",
"line",
".",
"value",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L629-L639 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | RecurringBehavior.transformToNative | def transformToNative(obj):
"""
Turn a recurring Component into a RecurringComponent.
"""
if not obj.isNative:
object.__setattr__(obj, '__class__', RecurringComponent)
obj.isNative = True
return obj | python | def transformToNative(obj):
if not obj.isNative:
object.__setattr__(obj, '__class__', RecurringComponent)
obj.isNative = True
return obj | [
"def",
"transformToNative",
"(",
"obj",
")",
":",
"if",
"not",
"obj",
".",
"isNative",
":",
"object",
".",
"__setattr__",
"(",
"obj",
",",
"'__class__'",
",",
"RecurringComponent",
")",
"obj",
".",
"isNative",
"=",
"True",
"return",
"obj"
]
| Turn a recurring Component into a RecurringComponent. | [
"Turn",
"a",
"recurring",
"Component",
"into",
"a",
"RecurringComponent",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L667-L674 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | RecurringBehavior.generateImplicitParameters | def generateImplicitParameters(obj):
"""
Generate a UID if one does not exist.
This is just a dummy implementation, for now.
"""
if not hasattr(obj, 'uid'):
rand = int(random.random() * 100000)
now = datetime.datetime.now(utc)
now = dateTimeToString(now)
host = socket.gethostname()
obj.add(ContentLine('UID', [], "{0} - {1}@{2}".format(now, rand,
host))) | python | def generateImplicitParameters(obj):
if not hasattr(obj, 'uid'):
rand = int(random.random() * 100000)
now = datetime.datetime.now(utc)
now = dateTimeToString(now)
host = socket.gethostname()
obj.add(ContentLine('UID', [], "{0} - {1}@{2}".format(now, rand,
host))) | [
"def",
"generateImplicitParameters",
"(",
"obj",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'uid'",
")",
":",
"rand",
"=",
"int",
"(",
"random",
".",
"random",
"(",
")",
"*",
"100000",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"utc",
")",
"now",
"=",
"dateTimeToString",
"(",
"now",
")",
"host",
"=",
"socket",
".",
"gethostname",
"(",
")",
"obj",
".",
"add",
"(",
"ContentLine",
"(",
"'UID'",
",",
"[",
"]",
",",
"\"{0} - {1}@{2}\"",
".",
"format",
"(",
"now",
",",
"rand",
",",
"host",
")",
")",
")"
]
| Generate a UID if one does not exist.
This is just a dummy implementation, for now. | [
"Generate",
"a",
"UID",
"if",
"one",
"does",
"not",
"exist",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L684-L696 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | DateOrDateTimeBehavior.transformToNative | def transformToNative(obj):
"""
Turn obj.value into a date or datetime.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
return obj
obj.value=obj.value
obj.value=parseDtstart(obj, allowSignatureMismatch=True)
if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME':
if hasattr(obj, 'tzid_param'):
# Keep a copy of the original TZID around
obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.tzid_param]
del obj.tzid_param
return obj | python | def transformToNative(obj):
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
return obj
obj.value=obj.value
obj.value=parseDtstart(obj, allowSignatureMismatch=True)
if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME':
if hasattr(obj, 'tzid_param'):
obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.tzid_param]
del obj.tzid_param
return obj | [
"def",
"transformToNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"isNative",
":",
"return",
"obj",
"obj",
".",
"isNative",
"=",
"True",
"if",
"obj",
".",
"value",
"==",
"''",
":",
"return",
"obj",
"obj",
".",
"value",
"=",
"obj",
".",
"value",
"obj",
".",
"value",
"=",
"parseDtstart",
"(",
"obj",
",",
"allowSignatureMismatch",
"=",
"True",
")",
"if",
"getattr",
"(",
"obj",
",",
"'value_param'",
",",
"'DATE-TIME'",
")",
".",
"upper",
"(",
")",
"==",
"'DATE-TIME'",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'tzid_param'",
")",
":",
"# Keep a copy of the original TZID around",
"obj",
".",
"params",
"[",
"'X-VOBJ-ORIGINAL-TZID'",
"]",
"=",
"[",
"obj",
".",
"tzid_param",
"]",
"del",
"obj",
".",
"tzid_param",
"return",
"obj"
]
| Turn obj.value into a date or datetime. | [
"Turn",
"obj",
".",
"value",
"into",
"a",
"date",
"or",
"datetime",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L762-L778 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | DateOrDateTimeBehavior.transformFromNative | def transformFromNative(obj):
"""
Replace the date or datetime in obj.value with an ISO 8601 string.
"""
if type(obj.value) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = dateToString(obj.value)
return obj
else:
return DateTimeBehavior.transformFromNative(obj) | python | def transformFromNative(obj):
if type(obj.value) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = dateToString(obj.value)
return obj
else:
return DateTimeBehavior.transformFromNative(obj) | [
"def",
"transformFromNative",
"(",
"obj",
")",
":",
"if",
"type",
"(",
"obj",
".",
"value",
")",
"==",
"datetime",
".",
"date",
":",
"obj",
".",
"isNative",
"=",
"False",
"obj",
".",
"value_param",
"=",
"'DATE'",
"obj",
".",
"value",
"=",
"dateToString",
"(",
"obj",
".",
"value",
")",
"return",
"obj",
"else",
":",
"return",
"DateTimeBehavior",
".",
"transformFromNative",
"(",
"obj",
")"
]
| Replace the date or datetime in obj.value with an ISO 8601 string. | [
"Replace",
"the",
"date",
"or",
"datetime",
"in",
"obj",
".",
"value",
"with",
"an",
"ISO",
"8601",
"string",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L781-L791 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | MultiDateBehavior.transformToNative | def transformToNative(obj):
"""
Turn obj.value into a list of dates, datetimes, or
(datetime, timedelta) tuples.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
obj.value = []
return obj
tzinfo = getTzid(getattr(obj, 'tzid_param', None))
valueParam = getattr(obj, 'value_param', "DATE-TIME").upper()
valTexts = obj.value.split(",")
if valueParam == "DATE":
obj.value = [stringToDate(x) for x in valTexts]
elif valueParam == "DATE-TIME":
obj.value = [stringToDateTime(x, tzinfo) for x in valTexts]
elif valueParam == "PERIOD":
obj.value = [stringToPeriod(x, tzinfo) for x in valTexts]
return obj | python | def transformToNative(obj):
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
obj.value = []
return obj
tzinfo = getTzid(getattr(obj, 'tzid_param', None))
valueParam = getattr(obj, 'value_param', "DATE-TIME").upper()
valTexts = obj.value.split(",")
if valueParam == "DATE":
obj.value = [stringToDate(x) for x in valTexts]
elif valueParam == "DATE-TIME":
obj.value = [stringToDateTime(x, tzinfo) for x in valTexts]
elif valueParam == "PERIOD":
obj.value = [stringToPeriod(x, tzinfo) for x in valTexts]
return obj | [
"def",
"transformToNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"isNative",
":",
"return",
"obj",
"obj",
".",
"isNative",
"=",
"True",
"if",
"obj",
".",
"value",
"==",
"''",
":",
"obj",
".",
"value",
"=",
"[",
"]",
"return",
"obj",
"tzinfo",
"=",
"getTzid",
"(",
"getattr",
"(",
"obj",
",",
"'tzid_param'",
",",
"None",
")",
")",
"valueParam",
"=",
"getattr",
"(",
"obj",
",",
"'value_param'",
",",
"\"DATE-TIME\"",
")",
".",
"upper",
"(",
")",
"valTexts",
"=",
"obj",
".",
"value",
".",
"split",
"(",
"\",\"",
")",
"if",
"valueParam",
"==",
"\"DATE\"",
":",
"obj",
".",
"value",
"=",
"[",
"stringToDate",
"(",
"x",
")",
"for",
"x",
"in",
"valTexts",
"]",
"elif",
"valueParam",
"==",
"\"DATE-TIME\"",
":",
"obj",
".",
"value",
"=",
"[",
"stringToDateTime",
"(",
"x",
",",
"tzinfo",
")",
"for",
"x",
"in",
"valTexts",
"]",
"elif",
"valueParam",
"==",
"\"PERIOD\"",
":",
"obj",
".",
"value",
"=",
"[",
"stringToPeriod",
"(",
"x",
",",
"tzinfo",
")",
"for",
"x",
"in",
"valTexts",
"]",
"return",
"obj"
]
| Turn obj.value into a list of dates, datetimes, or
(datetime, timedelta) tuples. | [
"Turn",
"obj",
".",
"value",
"into",
"a",
"list",
"of",
"dates",
"datetimes",
"or",
"(",
"datetime",
"timedelta",
")",
"tuples",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L802-L822 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | MultiDateBehavior.transformFromNative | def transformFromNative(obj):
"""
Replace the date, datetime or period tuples in obj.value with
appropriate strings.
"""
if obj.value and type(obj.value[0]) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = ','.join([dateToString(val) for val in obj.value])
return obj
# Fixme: handle PERIOD case
else:
if obj.isNative:
obj.isNative = False
transformed = []
tzid = None
for val in obj.value:
if tzid is None and type(val) == datetime.datetime:
tzid = TimezoneComponent.registerTzinfo(val.tzinfo)
if tzid is not None:
obj.tzid_param = tzid
transformed.append(dateTimeToString(val))
obj.value = ','.join(transformed)
return obj | python | def transformFromNative(obj):
if obj.value and type(obj.value[0]) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = ','.join([dateToString(val) for val in obj.value])
return obj
else:
if obj.isNative:
obj.isNative = False
transformed = []
tzid = None
for val in obj.value:
if tzid is None and type(val) == datetime.datetime:
tzid = TimezoneComponent.registerTzinfo(val.tzinfo)
if tzid is not None:
obj.tzid_param = tzid
transformed.append(dateTimeToString(val))
obj.value = ','.join(transformed)
return obj | [
"def",
"transformFromNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"value",
"and",
"type",
"(",
"obj",
".",
"value",
"[",
"0",
"]",
")",
"==",
"datetime",
".",
"date",
":",
"obj",
".",
"isNative",
"=",
"False",
"obj",
".",
"value_param",
"=",
"'DATE'",
"obj",
".",
"value",
"=",
"','",
".",
"join",
"(",
"[",
"dateToString",
"(",
"val",
")",
"for",
"val",
"in",
"obj",
".",
"value",
"]",
")",
"return",
"obj",
"# Fixme: handle PERIOD case",
"else",
":",
"if",
"obj",
".",
"isNative",
":",
"obj",
".",
"isNative",
"=",
"False",
"transformed",
"=",
"[",
"]",
"tzid",
"=",
"None",
"for",
"val",
"in",
"obj",
".",
"value",
":",
"if",
"tzid",
"is",
"None",
"and",
"type",
"(",
"val",
")",
"==",
"datetime",
".",
"datetime",
":",
"tzid",
"=",
"TimezoneComponent",
".",
"registerTzinfo",
"(",
"val",
".",
"tzinfo",
")",
"if",
"tzid",
"is",
"not",
"None",
":",
"obj",
".",
"tzid_param",
"=",
"tzid",
"transformed",
".",
"append",
"(",
"dateTimeToString",
"(",
"val",
")",
")",
"obj",
".",
"value",
"=",
"','",
".",
"join",
"(",
"transformed",
")",
"return",
"obj"
]
| Replace the date, datetime or period tuples in obj.value with
appropriate strings. | [
"Replace",
"the",
"date",
"datetime",
"or",
"period",
"tuples",
"in",
"obj",
".",
"value",
"with",
"appropriate",
"strings",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L825-L848 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | MultiTextBehavior.decode | def decode(cls, line):
"""
Remove backslash escaping from line.value, then split on commas.
"""
if line.encoded:
line.value = stringToTextValues(line.value,
listSeparator=cls.listSeparator)
line.encoded=False | python | def decode(cls, line):
if line.encoded:
line.value = stringToTextValues(line.value,
listSeparator=cls.listSeparator)
line.encoded=False | [
"def",
"decode",
"(",
"cls",
",",
"line",
")",
":",
"if",
"line",
".",
"encoded",
":",
"line",
".",
"value",
"=",
"stringToTextValues",
"(",
"line",
".",
"value",
",",
"listSeparator",
"=",
"cls",
".",
"listSeparator",
")",
"line",
".",
"encoded",
"=",
"False"
]
| Remove backslash escaping from line.value, then split on commas. | [
"Remove",
"backslash",
"escaping",
"from",
"line",
".",
"value",
"then",
"split",
"on",
"commas",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L860-L867 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | MultiTextBehavior.encode | def encode(cls, line):
"""
Backslash escape line.value.
"""
if not line.encoded:
line.value = cls.listSeparator.join(backslashEscape(val)
for val in line.value)
line.encoded=True | python | def encode(cls, line):
if not line.encoded:
line.value = cls.listSeparator.join(backslashEscape(val)
for val in line.value)
line.encoded=True | [
"def",
"encode",
"(",
"cls",
",",
"line",
")",
":",
"if",
"not",
"line",
".",
"encoded",
":",
"line",
".",
"value",
"=",
"cls",
".",
"listSeparator",
".",
"join",
"(",
"backslashEscape",
"(",
"val",
")",
"for",
"val",
"in",
"line",
".",
"value",
")",
"line",
".",
"encoded",
"=",
"True"
]
| Backslash escape line.value. | [
"Backslash",
"escape",
"line",
".",
"value",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L870-L877 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | VCalendar2_0.generateImplicitParameters | def generateImplicitParameters(cls, obj):
"""
Create PRODID, VERSION, and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist.
"""
for comp in obj.components():
if comp.behavior is not None:
comp.behavior.generateImplicitParameters(comp)
if not hasattr(obj, 'prodid'):
obj.add(ContentLine('PRODID', [], PRODID))
if not hasattr(obj, 'version'):
obj.add(ContentLine('VERSION', [], cls.versionString))
tzidsUsed = {}
def findTzids(obj, table):
if isinstance(obj, ContentLine) and (obj.behavior is None or
not obj.behavior.forceUTC):
if getattr(obj, 'tzid_param', None):
table[obj.tzid_param] = 1
else:
if type(obj.value) == list:
for item in obj.value:
tzinfo = getattr(obj.value, 'tzinfo', None)
tzid = TimezoneComponent.registerTzinfo(tzinfo)
if tzid:
table[tzid] = 1
else:
tzinfo = getattr(obj.value, 'tzinfo', None)
tzid = TimezoneComponent.registerTzinfo(tzinfo)
if tzid:
table[tzid] = 1
for child in obj.getChildren():
if obj.name != 'VTIMEZONE':
findTzids(child, table)
findTzids(obj, tzidsUsed)
oldtzids = [toUnicode(x.tzid.value) for x in getattr(obj, 'vtimezone_list', [])]
for tzid in tzidsUsed.keys():
tzid = toUnicode(tzid)
if tzid != u'UTC' and tzid not in oldtzids:
obj.add(TimezoneComponent(tzinfo=getTzid(tzid))) | python | def generateImplicitParameters(cls, obj):
for comp in obj.components():
if comp.behavior is not None:
comp.behavior.generateImplicitParameters(comp)
if not hasattr(obj, 'prodid'):
obj.add(ContentLine('PRODID', [], PRODID))
if not hasattr(obj, 'version'):
obj.add(ContentLine('VERSION', [], cls.versionString))
tzidsUsed = {}
def findTzids(obj, table):
if isinstance(obj, ContentLine) and (obj.behavior is None or
not obj.behavior.forceUTC):
if getattr(obj, 'tzid_param', None):
table[obj.tzid_param] = 1
else:
if type(obj.value) == list:
for item in obj.value:
tzinfo = getattr(obj.value, 'tzinfo', None)
tzid = TimezoneComponent.registerTzinfo(tzinfo)
if tzid:
table[tzid] = 1
else:
tzinfo = getattr(obj.value, 'tzinfo', None)
tzid = TimezoneComponent.registerTzinfo(tzinfo)
if tzid:
table[tzid] = 1
for child in obj.getChildren():
if obj.name != 'VTIMEZONE':
findTzids(child, table)
findTzids(obj, tzidsUsed)
oldtzids = [toUnicode(x.tzid.value) for x in getattr(obj, 'vtimezone_list', [])]
for tzid in tzidsUsed.keys():
tzid = toUnicode(tzid)
if tzid != u'UTC' and tzid not in oldtzids:
obj.add(TimezoneComponent(tzinfo=getTzid(tzid))) | [
"def",
"generateImplicitParameters",
"(",
"cls",
",",
"obj",
")",
":",
"for",
"comp",
"in",
"obj",
".",
"components",
"(",
")",
":",
"if",
"comp",
".",
"behavior",
"is",
"not",
"None",
":",
"comp",
".",
"behavior",
".",
"generateImplicitParameters",
"(",
"comp",
")",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'prodid'",
")",
":",
"obj",
".",
"add",
"(",
"ContentLine",
"(",
"'PRODID'",
",",
"[",
"]",
",",
"PRODID",
")",
")",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'version'",
")",
":",
"obj",
".",
"add",
"(",
"ContentLine",
"(",
"'VERSION'",
",",
"[",
"]",
",",
"cls",
".",
"versionString",
")",
")",
"tzidsUsed",
"=",
"{",
"}",
"def",
"findTzids",
"(",
"obj",
",",
"table",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ContentLine",
")",
"and",
"(",
"obj",
".",
"behavior",
"is",
"None",
"or",
"not",
"obj",
".",
"behavior",
".",
"forceUTC",
")",
":",
"if",
"getattr",
"(",
"obj",
",",
"'tzid_param'",
",",
"None",
")",
":",
"table",
"[",
"obj",
".",
"tzid_param",
"]",
"=",
"1",
"else",
":",
"if",
"type",
"(",
"obj",
".",
"value",
")",
"==",
"list",
":",
"for",
"item",
"in",
"obj",
".",
"value",
":",
"tzinfo",
"=",
"getattr",
"(",
"obj",
".",
"value",
",",
"'tzinfo'",
",",
"None",
")",
"tzid",
"=",
"TimezoneComponent",
".",
"registerTzinfo",
"(",
"tzinfo",
")",
"if",
"tzid",
":",
"table",
"[",
"tzid",
"]",
"=",
"1",
"else",
":",
"tzinfo",
"=",
"getattr",
"(",
"obj",
".",
"value",
",",
"'tzinfo'",
",",
"None",
")",
"tzid",
"=",
"TimezoneComponent",
".",
"registerTzinfo",
"(",
"tzinfo",
")",
"if",
"tzid",
":",
"table",
"[",
"tzid",
"]",
"=",
"1",
"for",
"child",
"in",
"obj",
".",
"getChildren",
"(",
")",
":",
"if",
"obj",
".",
"name",
"!=",
"'VTIMEZONE'",
":",
"findTzids",
"(",
"child",
",",
"table",
")",
"findTzids",
"(",
"obj",
",",
"tzidsUsed",
")",
"oldtzids",
"=",
"[",
"toUnicode",
"(",
"x",
".",
"tzid",
".",
"value",
")",
"for",
"x",
"in",
"getattr",
"(",
"obj",
",",
"'vtimezone_list'",
",",
"[",
"]",
")",
"]",
"for",
"tzid",
"in",
"tzidsUsed",
".",
"keys",
"(",
")",
":",
"tzid",
"=",
"toUnicode",
"(",
"tzid",
")",
"if",
"tzid",
"!=",
"u'UTC'",
"and",
"tzid",
"not",
"in",
"oldtzids",
":",
"obj",
".",
"add",
"(",
"TimezoneComponent",
"(",
"tzinfo",
"=",
"getTzid",
"(",
"tzid",
")",
")",
")"
]
| Create PRODID, VERSION, and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist. | [
"Create",
"PRODID",
"VERSION",
"and",
"VTIMEZONEs",
"if",
"needed",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L906-L948 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | VAlarm.generateImplicitParameters | def generateImplicitParameters(obj):
"""
Create default ACTION and TRIGGER if they're not set.
"""
try:
obj.action
except AttributeError:
obj.add('action').value = 'AUDIO'
try:
obj.trigger
except AttributeError:
obj.add('trigger').value = datetime.timedelta(0) | python | def generateImplicitParameters(obj):
try:
obj.action
except AttributeError:
obj.add('action').value = 'AUDIO'
try:
obj.trigger
except AttributeError:
obj.add('trigger').value = datetime.timedelta(0) | [
"def",
"generateImplicitParameters",
"(",
"obj",
")",
":",
"try",
":",
"obj",
".",
"action",
"except",
"AttributeError",
":",
"obj",
".",
"add",
"(",
"'action'",
")",
".",
"value",
"=",
"'AUDIO'",
"try",
":",
"obj",
".",
"trigger",
"except",
"AttributeError",
":",
"obj",
".",
"add",
"(",
"'trigger'",
")",
".",
"value",
"=",
"datetime",
".",
"timedelta",
"(",
"0",
")"
]
| Create default ACTION and TRIGGER if they're not set. | [
"Create",
"default",
"ACTION",
"and",
"TRIGGER",
"if",
"they",
"re",
"not",
"set",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1208-L1219 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | Duration.transformToNative | def transformToNative(obj):
"""
Turn obj.value into a datetime.timedelta.
"""
if obj.isNative:
return obj
obj.isNative = True
obj.value=obj.value
if obj.value == '':
return obj
else:
deltalist=stringToDurations(obj.value)
# When can DURATION have multiple durations? For now:
if len(deltalist) == 1:
obj.value = deltalist[0]
return obj
else:
raise ParseError("DURATION must have a single duration string.") | python | def transformToNative(obj):
if obj.isNative:
return obj
obj.isNative = True
obj.value=obj.value
if obj.value == '':
return obj
else:
deltalist=stringToDurations(obj.value)
if len(deltalist) == 1:
obj.value = deltalist[0]
return obj
else:
raise ParseError("DURATION must have a single duration string.") | [
"def",
"transformToNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"isNative",
":",
"return",
"obj",
"obj",
".",
"isNative",
"=",
"True",
"obj",
".",
"value",
"=",
"obj",
".",
"value",
"if",
"obj",
".",
"value",
"==",
"''",
":",
"return",
"obj",
"else",
":",
"deltalist",
"=",
"stringToDurations",
"(",
"obj",
".",
"value",
")",
"# When can DURATION have multiple durations? For now:",
"if",
"len",
"(",
"deltalist",
")",
"==",
"1",
":",
"obj",
".",
"value",
"=",
"deltalist",
"[",
"0",
"]",
"return",
"obj",
"else",
":",
"raise",
"ParseError",
"(",
"\"DURATION must have a single duration string.\"",
")"
]
| Turn obj.value into a datetime.timedelta. | [
"Turn",
"obj",
".",
"value",
"into",
"a",
"datetime",
".",
"timedelta",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1332-L1349 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | Duration.transformFromNative | def transformFromNative(obj):
"""
Replace the datetime.timedelta in obj.value with an RFC2445 string.
"""
if not obj.isNative:
return obj
obj.isNative = False
obj.value = timedeltaToString(obj.value)
return obj | python | def transformFromNative(obj):
if not obj.isNative:
return obj
obj.isNative = False
obj.value = timedeltaToString(obj.value)
return obj | [
"def",
"transformFromNative",
"(",
"obj",
")",
":",
"if",
"not",
"obj",
".",
"isNative",
":",
"return",
"obj",
"obj",
".",
"isNative",
"=",
"False",
"obj",
".",
"value",
"=",
"timedeltaToString",
"(",
"obj",
".",
"value",
")",
"return",
"obj"
]
| Replace the datetime.timedelta in obj.value with an RFC2445 string. | [
"Replace",
"the",
"datetime",
".",
"timedelta",
"in",
"obj",
".",
"value",
"with",
"an",
"RFC2445",
"string",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1352-L1360 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | Trigger.transformToNative | def transformToNative(obj):
"""
Turn obj.value into a timedelta or datetime.
"""
if obj.isNative:
return obj
value = getattr(obj, 'value_param', 'DURATION').upper()
if hasattr(obj, 'value_param'):
del obj.value_param
if obj.value == '':
obj.isNative = True
return obj
elif value == 'DURATION':
try:
return Duration.transformToNative(obj)
except ParseError:
logger.warning("TRIGGER not recognized as DURATION, trying "
"DATE-TIME, because iCal sometimes exports "
"DATE-TIMEs without setting VALUE=DATE-TIME")
try:
obj.isNative = False
dt = DateTimeBehavior.transformToNative(obj)
return dt
except:
msg = "TRIGGER with no VALUE not recognized as DURATION " \
"or as DATE-TIME"
raise ParseError(msg)
elif value == 'DATE-TIME':
# TRIGGERs with DATE-TIME values must be in UTC, we could validate
# that fact, for now we take it on faith.
return DateTimeBehavior.transformToNative(obj)
else:
raise ParseError("VALUE must be DURATION or DATE-TIME") | python | def transformToNative(obj):
if obj.isNative:
return obj
value = getattr(obj, 'value_param', 'DURATION').upper()
if hasattr(obj, 'value_param'):
del obj.value_param
if obj.value == '':
obj.isNative = True
return obj
elif value == 'DURATION':
try:
return Duration.transformToNative(obj)
except ParseError:
logger.warning("TRIGGER not recognized as DURATION, trying "
"DATE-TIME, because iCal sometimes exports "
"DATE-TIMEs without setting VALUE=DATE-TIME")
try:
obj.isNative = False
dt = DateTimeBehavior.transformToNative(obj)
return dt
except:
msg = "TRIGGER with no VALUE not recognized as DURATION " \
"or as DATE-TIME"
raise ParseError(msg)
elif value == 'DATE-TIME':
return DateTimeBehavior.transformToNative(obj)
else:
raise ParseError("VALUE must be DURATION or DATE-TIME") | [
"def",
"transformToNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"isNative",
":",
"return",
"obj",
"value",
"=",
"getattr",
"(",
"obj",
",",
"'value_param'",
",",
"'DURATION'",
")",
".",
"upper",
"(",
")",
"if",
"hasattr",
"(",
"obj",
",",
"'value_param'",
")",
":",
"del",
"obj",
".",
"value_param",
"if",
"obj",
".",
"value",
"==",
"''",
":",
"obj",
".",
"isNative",
"=",
"True",
"return",
"obj",
"elif",
"value",
"==",
"'DURATION'",
":",
"try",
":",
"return",
"Duration",
".",
"transformToNative",
"(",
"obj",
")",
"except",
"ParseError",
":",
"logger",
".",
"warning",
"(",
"\"TRIGGER not recognized as DURATION, trying \"",
"\"DATE-TIME, because iCal sometimes exports \"",
"\"DATE-TIMEs without setting VALUE=DATE-TIME\"",
")",
"try",
":",
"obj",
".",
"isNative",
"=",
"False",
"dt",
"=",
"DateTimeBehavior",
".",
"transformToNative",
"(",
"obj",
")",
"return",
"dt",
"except",
":",
"msg",
"=",
"\"TRIGGER with no VALUE not recognized as DURATION \"",
"\"or as DATE-TIME\"",
"raise",
"ParseError",
"(",
"msg",
")",
"elif",
"value",
"==",
"'DATE-TIME'",
":",
"# TRIGGERs with DATE-TIME values must be in UTC, we could validate",
"# that fact, for now we take it on faith.",
"return",
"DateTimeBehavior",
".",
"transformToNative",
"(",
"obj",
")",
"else",
":",
"raise",
"ParseError",
"(",
"\"VALUE must be DURATION or DATE-TIME\"",
")"
]
| Turn obj.value into a timedelta or datetime. | [
"Turn",
"obj",
".",
"value",
"into",
"a",
"timedelta",
"or",
"datetime",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1374-L1406 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | PeriodBehavior.transformToNative | def transformToNative(obj):
"""
Convert comma separated periods into tuples.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
obj.value = []
return obj
tzinfo = getTzid(getattr(obj, 'tzid_param', None))
obj.value = [stringToPeriod(x, tzinfo) for x in obj.value.split(",")]
return obj | python | def transformToNative(obj):
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
obj.value = []
return obj
tzinfo = getTzid(getattr(obj, 'tzid_param', None))
obj.value = [stringToPeriod(x, tzinfo) for x in obj.value.split(",")]
return obj | [
"def",
"transformToNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"isNative",
":",
"return",
"obj",
"obj",
".",
"isNative",
"=",
"True",
"if",
"obj",
".",
"value",
"==",
"''",
":",
"obj",
".",
"value",
"=",
"[",
"]",
"return",
"obj",
"tzinfo",
"=",
"getTzid",
"(",
"getattr",
"(",
"obj",
",",
"'tzid_param'",
",",
"None",
")",
")",
"obj",
".",
"value",
"=",
"[",
"stringToPeriod",
"(",
"x",
",",
"tzinfo",
")",
"for",
"x",
"in",
"obj",
".",
"value",
".",
"split",
"(",
"\",\"",
")",
"]",
"return",
"obj"
]
| Convert comma separated periods into tuples. | [
"Convert",
"comma",
"separated",
"periods",
"into",
"tuples",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1428-L1440 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | PeriodBehavior.transformFromNative | def transformFromNative(cls, obj):
"""
Convert the list of tuples in obj.value to strings.
"""
if obj.isNative:
obj.isNative = False
transformed = []
for tup in obj.value:
transformed.append(periodToString(tup, cls.forceUTC))
if len(transformed) > 0:
tzid = TimezoneComponent.registerTzinfo(tup[0].tzinfo)
if not cls.forceUTC and tzid is not None:
obj.tzid_param = tzid
obj.value = ','.join(transformed)
return obj | python | def transformFromNative(cls, obj):
if obj.isNative:
obj.isNative = False
transformed = []
for tup in obj.value:
transformed.append(periodToString(tup, cls.forceUTC))
if len(transformed) > 0:
tzid = TimezoneComponent.registerTzinfo(tup[0].tzinfo)
if not cls.forceUTC and tzid is not None:
obj.tzid_param = tzid
obj.value = ','.join(transformed)
return obj | [
"def",
"transformFromNative",
"(",
"cls",
",",
"obj",
")",
":",
"if",
"obj",
".",
"isNative",
":",
"obj",
".",
"isNative",
"=",
"False",
"transformed",
"=",
"[",
"]",
"for",
"tup",
"in",
"obj",
".",
"value",
":",
"transformed",
".",
"append",
"(",
"periodToString",
"(",
"tup",
",",
"cls",
".",
"forceUTC",
")",
")",
"if",
"len",
"(",
"transformed",
")",
">",
"0",
":",
"tzid",
"=",
"TimezoneComponent",
".",
"registerTzinfo",
"(",
"tup",
"[",
"0",
"]",
".",
"tzinfo",
")",
"if",
"not",
"cls",
".",
"forceUTC",
"and",
"tzid",
"is",
"not",
"None",
":",
"obj",
".",
"tzid_param",
"=",
"tzid",
"obj",
".",
"value",
"=",
"','",
".",
"join",
"(",
"transformed",
")",
"return",
"obj"
]
| Convert the list of tuples in obj.value to strings. | [
"Convert",
"the",
"list",
"of",
"tuples",
"in",
"obj",
".",
"value",
"to",
"strings",
"."
]
| train | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1443-L1459 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.