id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
15,100
JamesPHoughton/pysd
pysd/py_backend/functions.py
xidz
def xidz(numerator, denominator, value_if_denom_is_zero): """ Implements Vensim's XIDZ function. This function executes a division, robust to denominator being zero. In the case of zero denominator, the final argument is returned. Parameters ---------- numerator: float denominator: float Components of the division operation value_if_denom_is_zero: float The value to return if the denominator is zero Returns ------- numerator / denominator if denominator > 1e-6 otherwise, returns value_if_denom_is_zero """ small = 1e-6 # What is considered zero according to Vensim Help if abs(denominator) < small: return value_if_denom_is_zero else: return numerator * 1.0 / denominator
python
def xidz(numerator, denominator, value_if_denom_is_zero): """ Implements Vensim's XIDZ function. This function executes a division, robust to denominator being zero. In the case of zero denominator, the final argument is returned. Parameters ---------- numerator: float denominator: float Components of the division operation value_if_denom_is_zero: float The value to return if the denominator is zero Returns ------- numerator / denominator if denominator > 1e-6 otherwise, returns value_if_denom_is_zero """ small = 1e-6 # What is considered zero according to Vensim Help if abs(denominator) < small: return value_if_denom_is_zero else: return numerator * 1.0 / denominator
[ "def", "xidz", "(", "numerator", ",", "denominator", ",", "value_if_denom_is_zero", ")", ":", "small", "=", "1e-6", "# What is considered zero according to Vensim Help", "if", "abs", "(", "denominator", ")", "<", "small", ":", "return", "value_if_denom_is_zero", "else", ":", "return", "numerator", "*", "1.0", "/", "denominator" ]
Implements Vensim's XIDZ function. This function executes a division, robust to denominator being zero. In the case of zero denominator, the final argument is returned. Parameters ---------- numerator: float denominator: float Components of the division operation value_if_denom_is_zero: float The value to return if the denominator is zero Returns ------- numerator / denominator if denominator > 1e-6 otherwise, returns value_if_denom_is_zero
[ "Implements", "Vensim", "s", "XIDZ", "function", ".", "This", "function", "executes", "a", "division", "robust", "to", "denominator", "being", "zero", ".", "In", "the", "case", "of", "zero", "denominator", "the", "final", "argument", "is", "returned", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L950-L973
15,101
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.initialize
def initialize(self, initialization_order=None): """ This function tries to initialize the stateful objects. In the case where an initialization function for `Stock A` depends on the value of `Stock B`, if we try to initialize `Stock A` before `Stock B` then we will get an error, as the value will not yet exist. In this case, just skip initializing `Stock A` for now, and go on to the other state initializations. Then come back to it and try again. """ # Initialize time if self.time is None: if self.time_initialization is None: self.time = Time() else: self.time = self.time_initialization() # if self.time is None: # self.time = time # self.components.time = self.time # self.components.functions.time = self.time # rewrite functions so we don't need this self.components._init_outer_references({ 'scope': self, 'time': self.time }) remaining = set(self._stateful_elements) while remaining: progress = set() for element in remaining: try: element.initialize() progress.add(element) except (KeyError, TypeError, AttributeError): pass if progress: remaining.difference_update(progress) else: raise KeyError('Unresolvable Reference: Probable circular initialization' + '\n'.join([repr(e) for e in remaining]))
python
def initialize(self, initialization_order=None): """ This function tries to initialize the stateful objects. In the case where an initialization function for `Stock A` depends on the value of `Stock B`, if we try to initialize `Stock A` before `Stock B` then we will get an error, as the value will not yet exist. In this case, just skip initializing `Stock A` for now, and go on to the other state initializations. Then come back to it and try again. """ # Initialize time if self.time is None: if self.time_initialization is None: self.time = Time() else: self.time = self.time_initialization() # if self.time is None: # self.time = time # self.components.time = self.time # self.components.functions.time = self.time # rewrite functions so we don't need this self.components._init_outer_references({ 'scope': self, 'time': self.time }) remaining = set(self._stateful_elements) while remaining: progress = set() for element in remaining: try: element.initialize() progress.add(element) except (KeyError, TypeError, AttributeError): pass if progress: remaining.difference_update(progress) else: raise KeyError('Unresolvable Reference: Probable circular initialization' + '\n'.join([repr(e) for e in remaining]))
[ "def", "initialize", "(", "self", ",", "initialization_order", "=", "None", ")", ":", "# Initialize time", "if", "self", ".", "time", "is", "None", ":", "if", "self", ".", "time_initialization", "is", "None", ":", "self", ".", "time", "=", "Time", "(", ")", "else", ":", "self", ".", "time", "=", "self", ".", "time_initialization", "(", ")", "# if self.time is None:", "# self.time = time", "# self.components.time = self.time", "# self.components.functions.time = self.time # rewrite functions so we don't need this", "self", ".", "components", ".", "_init_outer_references", "(", "{", "'scope'", ":", "self", ",", "'time'", ":", "self", ".", "time", "}", ")", "remaining", "=", "set", "(", "self", ".", "_stateful_elements", ")", "while", "remaining", ":", "progress", "=", "set", "(", ")", "for", "element", "in", "remaining", ":", "try", ":", "element", ".", "initialize", "(", ")", "progress", ".", "add", "(", "element", ")", "except", "(", "KeyError", ",", "TypeError", ",", "AttributeError", ")", ":", "pass", "if", "progress", ":", "remaining", ".", "difference_update", "(", "progress", ")", "else", ":", "raise", "KeyError", "(", "'Unresolvable Reference: Probable circular initialization'", "+", "'\\n'", ".", "join", "(", "[", "repr", "(", "e", ")", "for", "e", "in", "remaining", "]", ")", ")" ]
This function tries to initialize the stateful objects. In the case where an initialization function for `Stock A` depends on the value of `Stock B`, if we try to initialize `Stock A` before `Stock B` then we will get an error, as the value will not yet exist. In this case, just skip initializing `Stock A` for now, and go on to the other state initializations. Then come back to it and try again.
[ "This", "function", "tries", "to", "initialize", "the", "stateful", "objects", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L320-L363
15,102
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.set_components
def set_components(self, params): """ Set the value of exogenous model elements. Element values can be passed as keyword=value pairs in the function call. Values can be numeric type or pandas Series. Series will be interpolated by integrator. Examples -------- >>> model.set_components({'birth_rate': 10}) >>> model.set_components({'Birth Rate': 10}) >>> br = pandas.Series(index=range(30), values=np.sin(range(30)) >>> model.set_components({'birth_rate': br}) """ # It might make sense to allow the params argument to take a pandas series, where # the indices of the series are variable names. This would make it easier to # do a Pandas apply on a DataFrame of parameter values. However, this may conflict # with a pandas series being passed in as a dictionary element. for key, value in params.items(): if isinstance(value, pd.Series): new_function = self._timeseries_component(value) elif callable(value): new_function = value else: new_function = self._constant_component(value) func_name = utils.get_value_by_insensitive_key_or_value(key, self.components._namespace) if func_name is None: raise NameError('%s is not recognized as a model component' % key) if '_integ_' + func_name in dir(self.components): # this won't handle other statefuls... warnings.warn("Replacing the equation of stock {} with params".format(key), stacklevel=2) setattr(self.components, func_name, new_function)
python
def set_components(self, params): """ Set the value of exogenous model elements. Element values can be passed as keyword=value pairs in the function call. Values can be numeric type or pandas Series. Series will be interpolated by integrator. Examples -------- >>> model.set_components({'birth_rate': 10}) >>> model.set_components({'Birth Rate': 10}) >>> br = pandas.Series(index=range(30), values=np.sin(range(30)) >>> model.set_components({'birth_rate': br}) """ # It might make sense to allow the params argument to take a pandas series, where # the indices of the series are variable names. This would make it easier to # do a Pandas apply on a DataFrame of parameter values. However, this may conflict # with a pandas series being passed in as a dictionary element. for key, value in params.items(): if isinstance(value, pd.Series): new_function = self._timeseries_component(value) elif callable(value): new_function = value else: new_function = self._constant_component(value) func_name = utils.get_value_by_insensitive_key_or_value(key, self.components._namespace) if func_name is None: raise NameError('%s is not recognized as a model component' % key) if '_integ_' + func_name in dir(self.components): # this won't handle other statefuls... warnings.warn("Replacing the equation of stock {} with params".format(key), stacklevel=2) setattr(self.components, func_name, new_function)
[ "def", "set_components", "(", "self", ",", "params", ")", ":", "# It might make sense to allow the params argument to take a pandas series, where", "# the indices of the series are variable names. This would make it easier to", "# do a Pandas apply on a DataFrame of parameter values. However, this may conflict", "# with a pandas series being passed in as a dictionary element.", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "pd", ".", "Series", ")", ":", "new_function", "=", "self", ".", "_timeseries_component", "(", "value", ")", "elif", "callable", "(", "value", ")", ":", "new_function", "=", "value", "else", ":", "new_function", "=", "self", ".", "_constant_component", "(", "value", ")", "func_name", "=", "utils", ".", "get_value_by_insensitive_key_or_value", "(", "key", ",", "self", ".", "components", ".", "_namespace", ")", "if", "func_name", "is", "None", ":", "raise", "NameError", "(", "'%s is not recognized as a model component'", "%", "key", ")", "if", "'_integ_'", "+", "func_name", "in", "dir", "(", "self", ".", "components", ")", ":", "# this won't handle other statefuls...", "warnings", ".", "warn", "(", "\"Replacing the equation of stock {} with params\"", ".", "format", "(", "key", ")", ",", "stacklevel", "=", "2", ")", "setattr", "(", "self", ".", "components", ",", "func_name", ",", "new_function", ")" ]
Set the value of exogenous model elements. Element values can be passed as keyword=value pairs in the function call. Values can be numeric type or pandas Series. Series will be interpolated by integrator. Examples -------- >>> model.set_components({'birth_rate': 10}) >>> model.set_components({'Birth Rate': 10}) >>> br = pandas.Series(index=range(30), values=np.sin(range(30)) >>> model.set_components({'birth_rate': br})
[ "Set", "the", "value", "of", "exogenous", "model", "elements", ".", "Element", "values", "can", "be", "passed", "as", "keyword", "=", "value", "pairs", "in", "the", "function", "call", ".", "Values", "can", "be", "numeric", "type", "or", "pandas", "Series", ".", "Series", "will", "be", "interpolated", "by", "integrator", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L376-L415
15,103
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro._timeseries_component
def _timeseries_component(self, series): """ Internal function for creating a timeseries model element """ # this is only called if the set_component function recognizes a pandas series # Todo: raise a warning if extrapolating from the end of the series. return lambda: np.interp(self.time(), series.index, series.values)
python
def _timeseries_component(self, series): """ Internal function for creating a timeseries model element """ # this is only called if the set_component function recognizes a pandas series # Todo: raise a warning if extrapolating from the end of the series. return lambda: np.interp(self.time(), series.index, series.values)
[ "def", "_timeseries_component", "(", "self", ",", "series", ")", ":", "# this is only called if the set_component function recognizes a pandas series", "# Todo: raise a warning if extrapolating from the end of the series.", "return", "lambda", ":", "np", ".", "interp", "(", "self", ".", "time", "(", ")", ",", "series", ".", "index", ",", "series", ".", "values", ")" ]
Internal function for creating a timeseries model element
[ "Internal", "function", "for", "creating", "a", "timeseries", "model", "element" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L417-L421
15,104
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.set_state
def set_state(self, t, state): """ Set the system state. Parameters ---------- t : numeric The system time state : dict A (possibly partial) dictionary of the system state. The keys to this dictionary may be either pysafe names or original model file names """ self.time.update(t) for key, value in state.items(): # TODO Implement map with reference between component and stateful element? component_name = utils.get_value_by_insensitive_key_or_value(key, self.components._namespace) if component_name is not None: stateful_name = '_integ_%s' % component_name else: component_name = key stateful_name = key # Try to update stateful component if hasattr(self.components, stateful_name): try: element = getattr(self.components, stateful_name) element.update(value) except AttributeError: print("'%s' has no state elements, assignment failed") raise else: # Try to override component try: setattr(self.components, component_name, self._constant_component(value)) except AttributeError: print("'%s' has no component, assignment failed") raise
python
def set_state(self, t, state): """ Set the system state. Parameters ---------- t : numeric The system time state : dict A (possibly partial) dictionary of the system state. The keys to this dictionary may be either pysafe names or original model file names """ self.time.update(t) for key, value in state.items(): # TODO Implement map with reference between component and stateful element? component_name = utils.get_value_by_insensitive_key_or_value(key, self.components._namespace) if component_name is not None: stateful_name = '_integ_%s' % component_name else: component_name = key stateful_name = key # Try to update stateful component if hasattr(self.components, stateful_name): try: element = getattr(self.components, stateful_name) element.update(value) except AttributeError: print("'%s' has no state elements, assignment failed") raise else: # Try to override component try: setattr(self.components, component_name, self._constant_component(value)) except AttributeError: print("'%s' has no component, assignment failed") raise
[ "def", "set_state", "(", "self", ",", "t", ",", "state", ")", ":", "self", ".", "time", ".", "update", "(", "t", ")", "for", "key", ",", "value", "in", "state", ".", "items", "(", ")", ":", "# TODO Implement map with reference between component and stateful element?", "component_name", "=", "utils", ".", "get_value_by_insensitive_key_or_value", "(", "key", ",", "self", ".", "components", ".", "_namespace", ")", "if", "component_name", "is", "not", "None", ":", "stateful_name", "=", "'_integ_%s'", "%", "component_name", "else", ":", "component_name", "=", "key", "stateful_name", "=", "key", "# Try to update stateful component", "if", "hasattr", "(", "self", ".", "components", ",", "stateful_name", ")", ":", "try", ":", "element", "=", "getattr", "(", "self", ".", "components", ",", "stateful_name", ")", "element", ".", "update", "(", "value", ")", "except", "AttributeError", ":", "print", "(", "\"'%s' has no state elements, assignment failed\"", ")", "raise", "else", ":", "# Try to override component", "try", ":", "setattr", "(", "self", ".", "components", ",", "component_name", ",", "self", ".", "_constant_component", "(", "value", ")", ")", "except", "AttributeError", ":", "print", "(", "\"'%s' has no component, assignment failed\"", ")", "raise" ]
Set the system state. Parameters ---------- t : numeric The system time state : dict A (possibly partial) dictionary of the system state. The keys to this dictionary may be either pysafe names or original model file names
[ "Set", "the", "system", "state", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L427-L464
15,105
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.clear_caches
def clear_caches(self): """ Clears the Caches for all model elements """ for element_name in dir(self.components): element = getattr(self.components, element_name) if hasattr(element, 'cache_val'): delattr(element, 'cache_val')
python
def clear_caches(self): """ Clears the Caches for all model elements """ for element_name in dir(self.components): element = getattr(self.components, element_name) if hasattr(element, 'cache_val'): delattr(element, 'cache_val')
[ "def", "clear_caches", "(", "self", ")", ":", "for", "element_name", "in", "dir", "(", "self", ".", "components", ")", ":", "element", "=", "getattr", "(", "self", ".", "components", ",", "element_name", ")", "if", "hasattr", "(", "element", ",", "'cache_val'", ")", ":", "delattr", "(", "element", ",", "'cache_val'", ")" ]
Clears the Caches for all model elements
[ "Clears", "the", "Caches", "for", "all", "model", "elements" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L466-L471
15,106
JamesPHoughton/pysd
pysd/py_backend/functions.py
Macro.doc
def doc(self): """ Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: - Real names - Python safe identifiers (as used in model.components) - Units string - Documentation strings from the original model file """ collector = [] for name, varname in self.components._namespace.items(): try: docstring = getattr(self.components, varname).__doc__ lines = docstring.split('\n') collector.append({'Real Name': name, 'Py Name': varname, 'Eqn': lines[2].replace("Original Eqn:", "").strip(), 'Unit': lines[3].replace("Units:", "").strip(), 'Lims': lines[4].replace("Limits:", "").strip(), 'Type': lines[5].replace("Type:", "").strip(), 'Comment': '\n'.join(lines[7:]).strip()}) except: pass docs_df = _pd.DataFrame(collector) docs_df.fillna('None', inplace=True) order = ['Real Name', 'Py Name', 'Unit', 'Lims', 'Type', 'Eqn', 'Comment'] return docs_df[order].sort_values(by='Real Name').reset_index(drop=True)
python
def doc(self): """ Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: - Real names - Python safe identifiers (as used in model.components) - Units string - Documentation strings from the original model file """ collector = [] for name, varname in self.components._namespace.items(): try: docstring = getattr(self.components, varname).__doc__ lines = docstring.split('\n') collector.append({'Real Name': name, 'Py Name': varname, 'Eqn': lines[2].replace("Original Eqn:", "").strip(), 'Unit': lines[3].replace("Units:", "").strip(), 'Lims': lines[4].replace("Limits:", "").strip(), 'Type': lines[5].replace("Type:", "").strip(), 'Comment': '\n'.join(lines[7:]).strip()}) except: pass docs_df = _pd.DataFrame(collector) docs_df.fillna('None', inplace=True) order = ['Real Name', 'Py Name', 'Unit', 'Lims', 'Type', 'Eqn', 'Comment'] return docs_df[order].sort_values(by='Real Name').reset_index(drop=True)
[ "def", "doc", "(", "self", ")", ":", "collector", "=", "[", "]", "for", "name", ",", "varname", "in", "self", ".", "components", ".", "_namespace", ".", "items", "(", ")", ":", "try", ":", "docstring", "=", "getattr", "(", "self", ".", "components", ",", "varname", ")", ".", "__doc__", "lines", "=", "docstring", ".", "split", "(", "'\\n'", ")", "collector", ".", "append", "(", "{", "'Real Name'", ":", "name", ",", "'Py Name'", ":", "varname", ",", "'Eqn'", ":", "lines", "[", "2", "]", ".", "replace", "(", "\"Original Eqn:\"", ",", "\"\"", ")", ".", "strip", "(", ")", ",", "'Unit'", ":", "lines", "[", "3", "]", ".", "replace", "(", "\"Units:\"", ",", "\"\"", ")", ".", "strip", "(", ")", ",", "'Lims'", ":", "lines", "[", "4", "]", ".", "replace", "(", "\"Limits:\"", ",", "\"\"", ")", ".", "strip", "(", ")", ",", "'Type'", ":", "lines", "[", "5", "]", ".", "replace", "(", "\"Type:\"", ",", "\"\"", ")", ".", "strip", "(", ")", ",", "'Comment'", ":", "'\\n'", ".", "join", "(", "lines", "[", "7", ":", "]", ")", ".", "strip", "(", ")", "}", ")", "except", ":", "pass", "docs_df", "=", "_pd", ".", "DataFrame", "(", "collector", ")", "docs_df", ".", "fillna", "(", "'None'", ",", "inplace", "=", "True", ")", "order", "=", "[", "'Real Name'", ",", "'Py Name'", ",", "'Unit'", ",", "'Lims'", ",", "'Type'", ",", "'Eqn'", ",", "'Comment'", "]", "return", "docs_df", "[", "order", "]", ".", "sort_values", "(", "by", "=", "'Real Name'", ")", ".", "reset_index", "(", "drop", "=", "True", ")" ]
Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: - Real names - Python safe identifiers (as used in model.components) - Units string - Documentation strings from the original model file
[ "Formats", "a", "table", "of", "documentation", "strings", "to", "help", "users", "remember", "variable", "names", "and", "understand", "how", "they", "are", "translated", "into", "python", "safe", "names", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L473-L506
15,107
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model.initialize
def initialize(self): """ Initializes the simulation model """ self.time.update(self.components.initial_time()) self.time.stage = 'Initialization' super(Model, self).initialize()
python
def initialize(self): """ Initializes the simulation model """ self.time.update(self.components.initial_time()) self.time.stage = 'Initialization' super(Model, self).initialize()
[ "def", "initialize", "(", "self", ")", ":", "self", ".", "time", ".", "update", "(", "self", ".", "components", ".", "initial_time", "(", ")", ")", "self", ".", "time", ".", "stage", "=", "'Initialization'", "super", "(", "Model", ",", "self", ")", ".", "initialize", "(", ")" ]
Initializes the simulation model
[ "Initializes", "the", "simulation", "model" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L547-L551
15,108
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model._format_return_timestamps
def _format_return_timestamps(self, return_timestamps=None): """ Format the passed in return timestamps value as a numpy array. If no value is passed, build up array of timestamps based upon model start and end times, and the 'saveper' value. """ if return_timestamps is None: # Build based upon model file Start, Stop times and Saveper # Vensim's standard is to expect that the data set includes the `final time`, # so we have to add an extra period to make sure we get that value in what # numpy's `arange` gives us. return_timestamps_array = np.arange( self.components.initial_time(), self.components.final_time() + self.components.saveper(), self.components.saveper(), dtype=np.float64 ) elif inspect.isclass(range) and isinstance(return_timestamps, range): return_timestamps_array = np.array(return_timestamps, ndmin=1) elif isinstance(return_timestamps, (list, int, float, np.ndarray)): return_timestamps_array = np.array(return_timestamps, ndmin=1) elif isinstance(return_timestamps, _pd.Series): return_timestamps_array = return_timestamps.as_matrix() else: raise TypeError('`return_timestamps` expects a list, array, pandas Series, ' 'or numeric value') return return_timestamps_array
python
def _format_return_timestamps(self, return_timestamps=None): """ Format the passed in return timestamps value as a numpy array. If no value is passed, build up array of timestamps based upon model start and end times, and the 'saveper' value. """ if return_timestamps is None: # Build based upon model file Start, Stop times and Saveper # Vensim's standard is to expect that the data set includes the `final time`, # so we have to add an extra period to make sure we get that value in what # numpy's `arange` gives us. return_timestamps_array = np.arange( self.components.initial_time(), self.components.final_time() + self.components.saveper(), self.components.saveper(), dtype=np.float64 ) elif inspect.isclass(range) and isinstance(return_timestamps, range): return_timestamps_array = np.array(return_timestamps, ndmin=1) elif isinstance(return_timestamps, (list, int, float, np.ndarray)): return_timestamps_array = np.array(return_timestamps, ndmin=1) elif isinstance(return_timestamps, _pd.Series): return_timestamps_array = return_timestamps.as_matrix() else: raise TypeError('`return_timestamps` expects a list, array, pandas Series, ' 'or numeric value') return return_timestamps_array
[ "def", "_format_return_timestamps", "(", "self", ",", "return_timestamps", "=", "None", ")", ":", "if", "return_timestamps", "is", "None", ":", "# Build based upon model file Start, Stop times and Saveper", "# Vensim's standard is to expect that the data set includes the `final time`,", "# so we have to add an extra period to make sure we get that value in what", "# numpy's `arange` gives us.", "return_timestamps_array", "=", "np", ".", "arange", "(", "self", ".", "components", ".", "initial_time", "(", ")", ",", "self", ".", "components", ".", "final_time", "(", ")", "+", "self", ".", "components", ".", "saveper", "(", ")", ",", "self", ".", "components", ".", "saveper", "(", ")", ",", "dtype", "=", "np", ".", "float64", ")", "elif", "inspect", ".", "isclass", "(", "range", ")", "and", "isinstance", "(", "return_timestamps", ",", "range", ")", ":", "return_timestamps_array", "=", "np", ".", "array", "(", "return_timestamps", ",", "ndmin", "=", "1", ")", "elif", "isinstance", "(", "return_timestamps", ",", "(", "list", ",", "int", ",", "float", ",", "np", ".", "ndarray", ")", ")", ":", "return_timestamps_array", "=", "np", ".", "array", "(", "return_timestamps", ",", "ndmin", "=", "1", ")", "elif", "isinstance", "(", "return_timestamps", ",", "_pd", ".", "Series", ")", ":", "return_timestamps_array", "=", "return_timestamps", ".", "as_matrix", "(", ")", "else", ":", "raise", "TypeError", "(", "'`return_timestamps` expects a list, array, pandas Series, '", "'or numeric value'", ")", "return", "return_timestamps_array" ]
Format the passed in return timestamps value as a numpy array. If no value is passed, build up array of timestamps based upon model start and end times, and the 'saveper' value.
[ "Format", "the", "passed", "in", "return", "timestamps", "value", "as", "a", "numpy", "array", ".", "If", "no", "value", "is", "passed", "build", "up", "array", "of", "timestamps", "based", "upon", "model", "start", "and", "end", "times", "and", "the", "saveper", "value", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L588-L613
15,109
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model.run
def run(self, params=None, return_columns=None, return_timestamps=None, initial_condition='original', reload=False): """ Simulate the model's behavior over time. Return a pandas dataframe with timestamps as rows, model elements as columns. Parameters ---------- params : dictionary Keys are strings of model component names. Values are numeric or pandas Series. Numeric values represent constants over the model integration. Timeseries will be interpolated to give time-varying input. return_timestamps : list, numeric, numpy array(1-D) Timestamps in model execution at which to return state information. Defaults to model-file specified timesteps. return_columns : list of string model component names Returned dataframe will have corresponding columns. Defaults to model stock values. initial_condition : 'original'/'o', 'current'/'c', (t, {state}) The starting time, and the state of the system (the values of all the stocks) at that starting time. * 'original' (default) uses model-file specified initial condition * 'current' uses the state of the model after the previous execution * (t, {state}) lets the user specify a starting time and (possibly partial) list of stock values. reload : bool If true, reloads the model from the translated model file before making changes Examples -------- >>> model.run(params={'exogenous_constant': 42}) >>> model.run(params={'exogenous_variable': timeseries_input}) >>> model.run(return_timestamps=[1, 2, 3.1415, 4, 10]) >>> model.run(return_timestamps=10) >>> model.run(return_timestamps=np.linspace(1, 10, 20)) See Also -------- pysd.set_components : handles setting model parameters pysd.set_initial_condition : handles setting initial conditions """ if reload: self.reload() if params: self.set_components(params) self.set_initial_condition(initial_condition) return_timestamps = self._format_return_timestamps(return_timestamps) t_series = self._build_euler_timeseries(return_timestamps) if return_columns is None: return_columns = self._default_return_columns() self.time.stage = 'Run' self.clear_caches() capture_elements, return_addresses = utils.get_return_elements( return_columns, self.components._namespace, self.components._subscript_dict) res = self._integrate(t_series, capture_elements, return_timestamps) return_df = utils.make_flat_df(res, return_addresses) return_df.index = return_timestamps return return_df
python
def run(self, params=None, return_columns=None, return_timestamps=None, initial_condition='original', reload=False): """ Simulate the model's behavior over time. Return a pandas dataframe with timestamps as rows, model elements as columns. Parameters ---------- params : dictionary Keys are strings of model component names. Values are numeric or pandas Series. Numeric values represent constants over the model integration. Timeseries will be interpolated to give time-varying input. return_timestamps : list, numeric, numpy array(1-D) Timestamps in model execution at which to return state information. Defaults to model-file specified timesteps. return_columns : list of string model component names Returned dataframe will have corresponding columns. Defaults to model stock values. initial_condition : 'original'/'o', 'current'/'c', (t, {state}) The starting time, and the state of the system (the values of all the stocks) at that starting time. * 'original' (default) uses model-file specified initial condition * 'current' uses the state of the model after the previous execution * (t, {state}) lets the user specify a starting time and (possibly partial) list of stock values. reload : bool If true, reloads the model from the translated model file before making changes Examples -------- >>> model.run(params={'exogenous_constant': 42}) >>> model.run(params={'exogenous_variable': timeseries_input}) >>> model.run(return_timestamps=[1, 2, 3.1415, 4, 10]) >>> model.run(return_timestamps=10) >>> model.run(return_timestamps=np.linspace(1, 10, 20)) See Also -------- pysd.set_components : handles setting model parameters pysd.set_initial_condition : handles setting initial conditions """ if reload: self.reload() if params: self.set_components(params) self.set_initial_condition(initial_condition) return_timestamps = self._format_return_timestamps(return_timestamps) t_series = self._build_euler_timeseries(return_timestamps) if return_columns is None: return_columns = self._default_return_columns() self.time.stage = 'Run' self.clear_caches() capture_elements, return_addresses = utils.get_return_elements( return_columns, self.components._namespace, self.components._subscript_dict) res = self._integrate(t_series, capture_elements, return_timestamps) return_df = utils.make_flat_df(res, return_addresses) return_df.index = return_timestamps return return_df
[ "def", "run", "(", "self", ",", "params", "=", "None", ",", "return_columns", "=", "None", ",", "return_timestamps", "=", "None", ",", "initial_condition", "=", "'original'", ",", "reload", "=", "False", ")", ":", "if", "reload", ":", "self", ".", "reload", "(", ")", "if", "params", ":", "self", ".", "set_components", "(", "params", ")", "self", ".", "set_initial_condition", "(", "initial_condition", ")", "return_timestamps", "=", "self", ".", "_format_return_timestamps", "(", "return_timestamps", ")", "t_series", "=", "self", ".", "_build_euler_timeseries", "(", "return_timestamps", ")", "if", "return_columns", "is", "None", ":", "return_columns", "=", "self", ".", "_default_return_columns", "(", ")", "self", ".", "time", ".", "stage", "=", "'Run'", "self", ".", "clear_caches", "(", ")", "capture_elements", ",", "return_addresses", "=", "utils", ".", "get_return_elements", "(", "return_columns", ",", "self", ".", "components", ".", "_namespace", ",", "self", ".", "components", ".", "_subscript_dict", ")", "res", "=", "self", ".", "_integrate", "(", "t_series", ",", "capture_elements", ",", "return_timestamps", ")", "return_df", "=", "utils", ".", "make_flat_df", "(", "res", ",", "return_addresses", ")", "return_df", ".", "index", "=", "return_timestamps", "return", "return_df" ]
Simulate the model's behavior over time. Return a pandas dataframe with timestamps as rows, model elements as columns. Parameters ---------- params : dictionary Keys are strings of model component names. Values are numeric or pandas Series. Numeric values represent constants over the model integration. Timeseries will be interpolated to give time-varying input. return_timestamps : list, numeric, numpy array(1-D) Timestamps in model execution at which to return state information. Defaults to model-file specified timesteps. return_columns : list of string model component names Returned dataframe will have corresponding columns. Defaults to model stock values. initial_condition : 'original'/'o', 'current'/'c', (t, {state}) The starting time, and the state of the system (the values of all the stocks) at that starting time. * 'original' (default) uses model-file specified initial condition * 'current' uses the state of the model after the previous execution * (t, {state}) lets the user specify a starting time and (possibly partial) list of stock values. reload : bool If true, reloads the model from the translated model file before making changes Examples -------- >>> model.run(params={'exogenous_constant': 42}) >>> model.run(params={'exogenous_variable': timeseries_input}) >>> model.run(return_timestamps=[1, 2, 3.1415, 4, 10]) >>> model.run(return_timestamps=10) >>> model.run(return_timestamps=np.linspace(1, 10, 20)) See Also -------- pysd.set_components : handles setting model parameters pysd.set_initial_condition : handles setting initial conditions
[ "Simulate", "the", "model", "s", "behavior", "over", "time", ".", "Return", "a", "pandas", "dataframe", "with", "timestamps", "as", "rows", "model", "elements", "as", "columns", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L615-L690
15,110
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model._default_return_columns
def _default_return_columns(self): """ Return a list of the model elements that does not include lookup functions or other functions that take parameters. """ return_columns = [] parsed_expr = [] for key, value in self.components._namespace.items(): if hasattr(self.components, value): sig = signature(getattr(self.components, value)) # The `*args` reference handles the py2.7 decorator. if len(set(sig.parameters) - {'args'}) == 0: expr = self.components._namespace[key] if not expr in parsed_expr: return_columns.append(key) parsed_expr.append(expr) return return_columns
python
def _default_return_columns(self): """ Return a list of the model elements that does not include lookup functions or other functions that take parameters. """ return_columns = [] parsed_expr = [] for key, value in self.components._namespace.items(): if hasattr(self.components, value): sig = signature(getattr(self.components, value)) # The `*args` reference handles the py2.7 decorator. if len(set(sig.parameters) - {'args'}) == 0: expr = self.components._namespace[key] if not expr in parsed_expr: return_columns.append(key) parsed_expr.append(expr) return return_columns
[ "def", "_default_return_columns", "(", "self", ")", ":", "return_columns", "=", "[", "]", "parsed_expr", "=", "[", "]", "for", "key", ",", "value", "in", "self", ".", "components", ".", "_namespace", ".", "items", "(", ")", ":", "if", "hasattr", "(", "self", ".", "components", ",", "value", ")", ":", "sig", "=", "signature", "(", "getattr", "(", "self", ".", "components", ",", "value", ")", ")", "# The `*args` reference handles the py2.7 decorator.", "if", "len", "(", "set", "(", "sig", ".", "parameters", ")", "-", "{", "'args'", "}", ")", "==", "0", ":", "expr", "=", "self", ".", "components", ".", "_namespace", "[", "key", "]", "if", "not", "expr", "in", "parsed_expr", ":", "return_columns", ".", "append", "(", "key", ")", "parsed_expr", ".", "append", "(", "expr", ")", "return", "return_columns" ]
Return a list of the model elements that does not include lookup functions or other functions that take parameters.
[ "Return", "a", "list", "of", "the", "model", "elements", "that", "does", "not", "include", "lookup", "functions", "or", "other", "functions", "that", "take", "parameters", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L698-L716
15,111
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model.set_initial_condition
def set_initial_condition(self, initial_condition): """ Set the initial conditions of the integration. Parameters ---------- initial_condition : <string> or <tuple> Takes on one of the following sets of values: * 'original'/'o' : Reset to the model-file specified initial condition. * 'current'/'c' : Use the current state of the system to start the next simulation. This includes the simulation time, so this initial condition must be paired with new return timestamps * (t, {state}) : Lets the user specify a starting time and list of stock values. >>> model.set_initial_condition('original') >>> model.set_initial_condition('current') >>> model.set_initial_condition((10, {'teacup_temperature': 50})) See Also -------- PySD.set_state() """ if isinstance(initial_condition, tuple): # Todo: check the values more than just seeing if they are a tuple. self.set_state(*initial_condition) elif isinstance(initial_condition, str): if initial_condition.lower() in ['original', 'o']: self.initialize() elif initial_condition.lower() in ['current', 'c']: pass else: raise ValueError('Valid initial condition strings include: \n' + ' "original"/"o", \n' + ' "current"/"c"') else: raise TypeError('Check documentation for valid entries')
python
def set_initial_condition(self, initial_condition): """ Set the initial conditions of the integration. Parameters ---------- initial_condition : <string> or <tuple> Takes on one of the following sets of values: * 'original'/'o' : Reset to the model-file specified initial condition. * 'current'/'c' : Use the current state of the system to start the next simulation. This includes the simulation time, so this initial condition must be paired with new return timestamps * (t, {state}) : Lets the user specify a starting time and list of stock values. >>> model.set_initial_condition('original') >>> model.set_initial_condition('current') >>> model.set_initial_condition((10, {'teacup_temperature': 50})) See Also -------- PySD.set_state() """ if isinstance(initial_condition, tuple): # Todo: check the values more than just seeing if they are a tuple. self.set_state(*initial_condition) elif isinstance(initial_condition, str): if initial_condition.lower() in ['original', 'o']: self.initialize() elif initial_condition.lower() in ['current', 'c']: pass else: raise ValueError('Valid initial condition strings include: \n' + ' "original"/"o", \n' + ' "current"/"c"') else: raise TypeError('Check documentation for valid entries')
[ "def", "set_initial_condition", "(", "self", ",", "initial_condition", ")", ":", "if", "isinstance", "(", "initial_condition", ",", "tuple", ")", ":", "# Todo: check the values more than just seeing if they are a tuple.", "self", ".", "set_state", "(", "*", "initial_condition", ")", "elif", "isinstance", "(", "initial_condition", ",", "str", ")", ":", "if", "initial_condition", ".", "lower", "(", ")", "in", "[", "'original'", ",", "'o'", "]", ":", "self", ".", "initialize", "(", ")", "elif", "initial_condition", ".", "lower", "(", ")", "in", "[", "'current'", ",", "'c'", "]", ":", "pass", "else", ":", "raise", "ValueError", "(", "'Valid initial condition strings include: \\n'", "+", "' \"original\"/\"o\", \\n'", "+", "' \"current\"/\"c\"'", ")", "else", ":", "raise", "TypeError", "(", "'Check documentation for valid entries'", ")" ]
Set the initial conditions of the integration. Parameters ---------- initial_condition : <string> or <tuple> Takes on one of the following sets of values: * 'original'/'o' : Reset to the model-file specified initial condition. * 'current'/'c' : Use the current state of the system to start the next simulation. This includes the simulation time, so this initial condition must be paired with new return timestamps * (t, {state}) : Lets the user specify a starting time and list of stock values. >>> model.set_initial_condition('original') >>> model.set_initial_condition('current') >>> model.set_initial_condition((10, {'teacup_temperature': 50})) See Also -------- PySD.set_state()
[ "Set", "the", "initial", "conditions", "of", "the", "integration", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L718-L755
15,112
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model._euler_step
def _euler_step(self, dt): """ Performs a single step in the euler integration, updating stateful components Parameters ---------- dt : float This is the amount to increase time by this step """ self.state = self.state + self.ddt() * dt
python
def _euler_step(self, dt): """ Performs a single step in the euler integration, updating stateful components Parameters ---------- dt : float This is the amount to increase time by this step """ self.state = self.state + self.ddt() * dt
[ "def", "_euler_step", "(", "self", ",", "dt", ")", ":", "self", ".", "state", "=", "self", ".", "state", "+", "self", ".", "ddt", "(", ")", "*", "dt" ]
Performs a single step in the euler integration, updating stateful components Parameters ---------- dt : float This is the amount to increase time by this step
[ "Performs", "a", "single", "step", "in", "the", "euler", "integration", "updating", "stateful", "components" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L757-L766
15,113
JamesPHoughton/pysd
pysd/py_backend/functions.py
Model._integrate
def _integrate(self, time_steps, capture_elements, return_timestamps): """ Performs euler integration Parameters ---------- time_steps: iterable the time steps that the integrator progresses over capture_elements: list which model elements to capture - uses pysafe names return_timestamps: which subset of 'timesteps' should be values be returned? Returns ------- outputs: list of dictionaries """ # Todo: consider adding the timestamp to the return elements, and using that as the index outputs = [] for t2 in time_steps[1:]: if self.time() in return_timestamps: outputs.append({key: getattr(self.components, key)() for key in capture_elements}) self._euler_step(t2 - self.time()) self.time.update(t2) # this will clear the stepwise caches # need to add one more time step, because we run only the state updates in the previous # loop and thus may be one short. if self.time() in return_timestamps: outputs.append({key: getattr(self.components, key)() for key in capture_elements}) return outputs
python
def _integrate(self, time_steps, capture_elements, return_timestamps): """ Performs euler integration Parameters ---------- time_steps: iterable the time steps that the integrator progresses over capture_elements: list which model elements to capture - uses pysafe names return_timestamps: which subset of 'timesteps' should be values be returned? Returns ------- outputs: list of dictionaries """ # Todo: consider adding the timestamp to the return elements, and using that as the index outputs = [] for t2 in time_steps[1:]: if self.time() in return_timestamps: outputs.append({key: getattr(self.components, key)() for key in capture_elements}) self._euler_step(t2 - self.time()) self.time.update(t2) # this will clear the stepwise caches # need to add one more time step, because we run only the state updates in the previous # loop and thus may be one short. if self.time() in return_timestamps: outputs.append({key: getattr(self.components, key)() for key in capture_elements}) return outputs
[ "def", "_integrate", "(", "self", ",", "time_steps", ",", "capture_elements", ",", "return_timestamps", ")", ":", "# Todo: consider adding the timestamp to the return elements, and using that as the index", "outputs", "=", "[", "]", "for", "t2", "in", "time_steps", "[", "1", ":", "]", ":", "if", "self", ".", "time", "(", ")", "in", "return_timestamps", ":", "outputs", ".", "append", "(", "{", "key", ":", "getattr", "(", "self", ".", "components", ",", "key", ")", "(", ")", "for", "key", "in", "capture_elements", "}", ")", "self", ".", "_euler_step", "(", "t2", "-", "self", ".", "time", "(", ")", ")", "self", ".", "time", ".", "update", "(", "t2", ")", "# this will clear the stepwise caches", "# need to add one more time step, because we run only the state updates in the previous", "# loop and thus may be one short.", "if", "self", ".", "time", "(", ")", "in", "return_timestamps", ":", "outputs", ".", "append", "(", "{", "key", ":", "getattr", "(", "self", ".", "components", ",", "key", ")", "(", ")", "for", "key", "in", "capture_elements", "}", ")", "return", "outputs" ]
Performs euler integration Parameters ---------- time_steps: iterable the time steps that the integrator progresses over capture_elements: list which model elements to capture - uses pysafe names return_timestamps: which subset of 'timesteps' should be values be returned? Returns ------- outputs: list of dictionaries
[ "Performs", "euler", "integration" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L768-L800
15,114
JamesPHoughton/pysd
pysd/py_backend/builder.py
merge_partial_elements
def merge_partial_elements(element_list): """ merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list Returns ------- """ outs = dict() # output data structure for element in element_list: if element['py_expr'] != "None": # for name = element['py_name'] if name not in outs: # Use 'expr' for Vensim models, and 'eqn' for Xmile (This makes the Vensim equation prettier.) eqn = element['expr'] if 'expr' in element else element['eqn'] outs[name] = { 'py_name': element['py_name'], 'real_name': element['real_name'], 'doc': element['doc'], 'py_expr': [element['py_expr']], # in a list 'unit': element['unit'], 'subs': [element['subs']], 'lims': element['lims'], 'eqn': eqn, 'kind': element['kind'], 'arguments': element['arguments'] } else: outs[name]['doc'] = outs[name]['doc'] or element['doc'] outs[name]['unit'] = outs[name]['unit'] or element['unit'] outs[name]['lims'] = outs[name]['lims'] or element['lims'] outs[name]['eqn'] = outs[name]['eqn'] or element['eqn'] outs[name]['py_expr'] += [element['py_expr']] outs[name]['subs'] += [element['subs']] outs[name]['arguments'] = element['arguments'] return list(outs.values())
python
def merge_partial_elements(element_list): """ merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list Returns ------- """ outs = dict() # output data structure for element in element_list: if element['py_expr'] != "None": # for name = element['py_name'] if name not in outs: # Use 'expr' for Vensim models, and 'eqn' for Xmile (This makes the Vensim equation prettier.) eqn = element['expr'] if 'expr' in element else element['eqn'] outs[name] = { 'py_name': element['py_name'], 'real_name': element['real_name'], 'doc': element['doc'], 'py_expr': [element['py_expr']], # in a list 'unit': element['unit'], 'subs': [element['subs']], 'lims': element['lims'], 'eqn': eqn, 'kind': element['kind'], 'arguments': element['arguments'] } else: outs[name]['doc'] = outs[name]['doc'] or element['doc'] outs[name]['unit'] = outs[name]['unit'] or element['unit'] outs[name]['lims'] = outs[name]['lims'] or element['lims'] outs[name]['eqn'] = outs[name]['eqn'] or element['eqn'] outs[name]['py_expr'] += [element['py_expr']] outs[name]['subs'] += [element['subs']] outs[name]['arguments'] = element['arguments'] return list(outs.values())
[ "def", "merge_partial_elements", "(", "element_list", ")", ":", "outs", "=", "dict", "(", ")", "# output data structure", "for", "element", "in", "element_list", ":", "if", "element", "[", "'py_expr'", "]", "!=", "\"None\"", ":", "# for", "name", "=", "element", "[", "'py_name'", "]", "if", "name", "not", "in", "outs", ":", "# Use 'expr' for Vensim models, and 'eqn' for Xmile (This makes the Vensim equation prettier.)", "eqn", "=", "element", "[", "'expr'", "]", "if", "'expr'", "in", "element", "else", "element", "[", "'eqn'", "]", "outs", "[", "name", "]", "=", "{", "'py_name'", ":", "element", "[", "'py_name'", "]", ",", "'real_name'", ":", "element", "[", "'real_name'", "]", ",", "'doc'", ":", "element", "[", "'doc'", "]", ",", "'py_expr'", ":", "[", "element", "[", "'py_expr'", "]", "]", ",", "# in a list", "'unit'", ":", "element", "[", "'unit'", "]", ",", "'subs'", ":", "[", "element", "[", "'subs'", "]", "]", ",", "'lims'", ":", "element", "[", "'lims'", "]", ",", "'eqn'", ":", "eqn", ",", "'kind'", ":", "element", "[", "'kind'", "]", ",", "'arguments'", ":", "element", "[", "'arguments'", "]", "}", "else", ":", "outs", "[", "name", "]", "[", "'doc'", "]", "=", "outs", "[", "name", "]", "[", "'doc'", "]", "or", "element", "[", "'doc'", "]", "outs", "[", "name", "]", "[", "'unit'", "]", "=", "outs", "[", "name", "]", "[", "'unit'", "]", "or", "element", "[", "'unit'", "]", "outs", "[", "name", "]", "[", "'lims'", "]", "=", "outs", "[", "name", "]", "[", "'lims'", "]", "or", "element", "[", "'lims'", "]", "outs", "[", "name", "]", "[", "'eqn'", "]", "=", "outs", "[", "name", "]", "[", "'eqn'", "]", "or", "element", "[", "'eqn'", "]", "outs", "[", "name", "]", "[", "'py_expr'", "]", "+=", "[", "element", "[", "'py_expr'", "]", "]", "outs", "[", "name", "]", "[", "'subs'", "]", "+=", "[", "element", "[", "'subs'", "]", "]", "outs", "[", "name", "]", "[", "'arguments'", "]", "=", "element", "[", "'arguments'", "]", "return", "list", "(", "outs", ".", "values", "(", ")", ")" ]
merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list Returns -------
[ "merges", "model", "elements", "which", "collectively", "all", "define", "the", "model", "component", "mostly", "for", "multidimensional", "subscripts" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L187-L229
15,115
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_n_delay
def add_n_delay(delay_input, delay_time, initial_value, order, subs, subscript_dict): """ Creates code to instantiate a stateful 'Delay' object, and provides reference to that object's output. The name of the stateful object is based upon the passed in parameters, so if there are multiple places where identical delay functions are referenced, the translated python file will only maintain one stateful object, and reference it multiple times. Parameters ---------- delay_input: <string> Reference to the model component that is the input to the delay delay_time: <string> Can be a number (in string format) or a reference to another model element which will calculate the delay. This is calculated throughout the simulation at runtime. initial_value: <string> This is used to initialize the stocks that are present in the delay. We initialize the stocks with equal values so that the outflow in the first timestep is equal to this value. order: string The number of stocks in the delay pipeline. As we construct the delays at build time, this must be an integer and cannot be calculated from other model components. Anything else will yield a ValueError. Returns ------- reference: basestring reference to the delay object `__call__` method, which will return the output of the delay process new_structure: list list of element construction dictionaries for the builder to assemble """ # the py name has to be unique to all the passed parameters, or if there are two things # that delay the output by different amounts, they'll overwrite the original function... stateful = { 'py_name': utils.make_python_identifier('_delay_%s_%s_%s_%s' % (delay_input, delay_time, initial_value, order))[0], 'real_name': 'Delay of %s' % delay_input, 'doc': 'Delay time: %s \n Delay initial value %s \n Delay order %s' % ( delay_time, initial_value, order), 'py_expr': 'functions.Delay(lambda: %s, lambda: %s, lambda: %s, lambda: %s)' % ( delay_input, delay_time, initial_value, order), 'unit': 'None', 'lims': 'None', 'eqn': 'None', 'subs': '', 'kind': 'stateful', 'arguments': '' } return "%s()" % stateful['py_name'], [stateful]
python
def add_n_delay(delay_input, delay_time, initial_value, order, subs, subscript_dict): """ Creates code to instantiate a stateful 'Delay' object, and provides reference to that object's output. The name of the stateful object is based upon the passed in parameters, so if there are multiple places where identical delay functions are referenced, the translated python file will only maintain one stateful object, and reference it multiple times. Parameters ---------- delay_input: <string> Reference to the model component that is the input to the delay delay_time: <string> Can be a number (in string format) or a reference to another model element which will calculate the delay. This is calculated throughout the simulation at runtime. initial_value: <string> This is used to initialize the stocks that are present in the delay. We initialize the stocks with equal values so that the outflow in the first timestep is equal to this value. order: string The number of stocks in the delay pipeline. As we construct the delays at build time, this must be an integer and cannot be calculated from other model components. Anything else will yield a ValueError. Returns ------- reference: basestring reference to the delay object `__call__` method, which will return the output of the delay process new_structure: list list of element construction dictionaries for the builder to assemble """ # the py name has to be unique to all the passed parameters, or if there are two things # that delay the output by different amounts, they'll overwrite the original function... stateful = { 'py_name': utils.make_python_identifier('_delay_%s_%s_%s_%s' % (delay_input, delay_time, initial_value, order))[0], 'real_name': 'Delay of %s' % delay_input, 'doc': 'Delay time: %s \n Delay initial value %s \n Delay order %s' % ( delay_time, initial_value, order), 'py_expr': 'functions.Delay(lambda: %s, lambda: %s, lambda: %s, lambda: %s)' % ( delay_input, delay_time, initial_value, order), 'unit': 'None', 'lims': 'None', 'eqn': 'None', 'subs': '', 'kind': 'stateful', 'arguments': '' } return "%s()" % stateful['py_name'], [stateful]
[ "def", "add_n_delay", "(", "delay_input", ",", "delay_time", ",", "initial_value", ",", "order", ",", "subs", ",", "subscript_dict", ")", ":", "# the py name has to be unique to all the passed parameters, or if there are two things", "# that delay the output by different amounts, they'll overwrite the original function...", "stateful", "=", "{", "'py_name'", ":", "utils", ".", "make_python_identifier", "(", "'_delay_%s_%s_%s_%s'", "%", "(", "delay_input", ",", "delay_time", ",", "initial_value", ",", "order", ")", ")", "[", "0", "]", ",", "'real_name'", ":", "'Delay of %s'", "%", "delay_input", ",", "'doc'", ":", "'Delay time: %s \\n Delay initial value %s \\n Delay order %s'", "%", "(", "delay_time", ",", "initial_value", ",", "order", ")", ",", "'py_expr'", ":", "'functions.Delay(lambda: %s, lambda: %s, lambda: %s, lambda: %s)'", "%", "(", "delay_input", ",", "delay_time", ",", "initial_value", ",", "order", ")", ",", "'unit'", ":", "'None'", ",", "'lims'", ":", "'None'", ",", "'eqn'", ":", "'None'", ",", "'subs'", ":", "''", ",", "'kind'", ":", "'stateful'", ",", "'arguments'", ":", "''", "}", "return", "\"%s()\"", "%", "stateful", "[", "'py_name'", "]", ",", "[", "stateful", "]" ]
Creates code to instantiate a stateful 'Delay' object, and provides reference to that object's output. The name of the stateful object is based upon the passed in parameters, so if there are multiple places where identical delay functions are referenced, the translated python file will only maintain one stateful object, and reference it multiple times. Parameters ---------- delay_input: <string> Reference to the model component that is the input to the delay delay_time: <string> Can be a number (in string format) or a reference to another model element which will calculate the delay. This is calculated throughout the simulation at runtime. initial_value: <string> This is used to initialize the stocks that are present in the delay. We initialize the stocks with equal values so that the outflow in the first timestep is equal to this value. order: string The number of stocks in the delay pipeline. As we construct the delays at build time, this must be an integer and cannot be calculated from other model components. Anything else will yield a ValueError. Returns ------- reference: basestring reference to the delay object `__call__` method, which will return the output of the delay process new_structure: list list of element construction dictionaries for the builder to assemble
[ "Creates", "code", "to", "instantiate", "a", "stateful", "Delay", "object", "and", "provides", "reference", "to", "that", "object", "s", "output", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L340-L401
15,116
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_n_smooth
def add_n_smooth(smooth_input, smooth_time, initial_value, order, subs, subscript_dict): """Constructs stock and flow chains that implement the calculation of a smoothing function. Parameters ---------- smooth_input: <string> Reference to the model component that is the input to the smoothing function smooth_time: <string> Can be a number (in string format) or a reference to another model element which will calculate the delay. This is calculated throughout the simulation at runtime. initial_value: <string> This is used to initialize the stocks that are present in the delay. We initialize the stocks with equal values so that the outflow in the first timestep is equal to this value. order: string The number of stocks in the delay pipeline. As we construct the delays at build time, this must be an integer and cannot be calculated from other model components. Anything else will yield a ValueError. subs: list of strings List of strings of subscript indices that correspond to the list of expressions, and collectively define the shape of the output See `builder.add_flaux` for more info Returns ------- reference: basestring reference to the smooth object `__call__` method, which will return the output of the smooth process new_structure: list list of element construction dictionaries for the builder to assemble """ stateful = { 'py_name': utils.make_python_identifier('_smooth_%s_%s_%s_%s' % (smooth_input, smooth_time, initial_value, order))[0], 'real_name': 'Smooth of %s' % smooth_input, 'doc': 'Smooth time: %s \n Smooth initial value %s \n Smooth order %s' % ( smooth_time, initial_value, order), 'py_expr': 'functions.Smooth(lambda: %s, lambda: %s, lambda: %s, lambda: %s)' % ( smooth_input, smooth_time, initial_value, order), 'unit': 'None', 'lims': 'None', 'eqn': 'None', 'subs': '', 'kind': 'stateful', 'arguments': '' } return "%s()" % stateful['py_name'], [stateful]
python
def add_n_smooth(smooth_input, smooth_time, initial_value, order, subs, subscript_dict): """Constructs stock and flow chains that implement the calculation of a smoothing function. Parameters ---------- smooth_input: <string> Reference to the model component that is the input to the smoothing function smooth_time: <string> Can be a number (in string format) or a reference to another model element which will calculate the delay. This is calculated throughout the simulation at runtime. initial_value: <string> This is used to initialize the stocks that are present in the delay. We initialize the stocks with equal values so that the outflow in the first timestep is equal to this value. order: string The number of stocks in the delay pipeline. As we construct the delays at build time, this must be an integer and cannot be calculated from other model components. Anything else will yield a ValueError. subs: list of strings List of strings of subscript indices that correspond to the list of expressions, and collectively define the shape of the output See `builder.add_flaux` for more info Returns ------- reference: basestring reference to the smooth object `__call__` method, which will return the output of the smooth process new_structure: list list of element construction dictionaries for the builder to assemble """ stateful = { 'py_name': utils.make_python_identifier('_smooth_%s_%s_%s_%s' % (smooth_input, smooth_time, initial_value, order))[0], 'real_name': 'Smooth of %s' % smooth_input, 'doc': 'Smooth time: %s \n Smooth initial value %s \n Smooth order %s' % ( smooth_time, initial_value, order), 'py_expr': 'functions.Smooth(lambda: %s, lambda: %s, lambda: %s, lambda: %s)' % ( smooth_input, smooth_time, initial_value, order), 'unit': 'None', 'lims': 'None', 'eqn': 'None', 'subs': '', 'kind': 'stateful', 'arguments': '' } return "%s()" % stateful['py_name'], [stateful]
[ "def", "add_n_smooth", "(", "smooth_input", ",", "smooth_time", ",", "initial_value", ",", "order", ",", "subs", ",", "subscript_dict", ")", ":", "stateful", "=", "{", "'py_name'", ":", "utils", ".", "make_python_identifier", "(", "'_smooth_%s_%s_%s_%s'", "%", "(", "smooth_input", ",", "smooth_time", ",", "initial_value", ",", "order", ")", ")", "[", "0", "]", ",", "'real_name'", ":", "'Smooth of %s'", "%", "smooth_input", ",", "'doc'", ":", "'Smooth time: %s \\n Smooth initial value %s \\n Smooth order %s'", "%", "(", "smooth_time", ",", "initial_value", ",", "order", ")", ",", "'py_expr'", ":", "'functions.Smooth(lambda: %s, lambda: %s, lambda: %s, lambda: %s)'", "%", "(", "smooth_input", ",", "smooth_time", ",", "initial_value", ",", "order", ")", ",", "'unit'", ":", "'None'", ",", "'lims'", ":", "'None'", ",", "'eqn'", ":", "'None'", ",", "'subs'", ":", "''", ",", "'kind'", ":", "'stateful'", ",", "'arguments'", ":", "''", "}", "return", "\"%s()\"", "%", "stateful", "[", "'py_name'", "]", ",", "[", "stateful", "]" ]
Constructs stock and flow chains that implement the calculation of a smoothing function. Parameters ---------- smooth_input: <string> Reference to the model component that is the input to the smoothing function smooth_time: <string> Can be a number (in string format) or a reference to another model element which will calculate the delay. This is calculated throughout the simulation at runtime. initial_value: <string> This is used to initialize the stocks that are present in the delay. We initialize the stocks with equal values so that the outflow in the first timestep is equal to this value. order: string The number of stocks in the delay pipeline. As we construct the delays at build time, this must be an integer and cannot be calculated from other model components. Anything else will yield a ValueError. subs: list of strings List of strings of subscript indices that correspond to the list of expressions, and collectively define the shape of the output See `builder.add_flaux` for more info Returns ------- reference: basestring reference to the smooth object `__call__` method, which will return the output of the smooth process new_structure: list list of element construction dictionaries for the builder to assemble
[ "Constructs", "stock", "and", "flow", "chains", "that", "implement", "the", "calculation", "of", "a", "smoothing", "function", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L404-L461
15,117
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_initial
def add_initial(initial_input): """ Constructs a stateful object for handling vensim's 'Initial' functionality Parameters ---------- initial_input: basestring The expression which will be evaluated, and the first value of which returned Returns ------- reference: basestring reference to the Initial object `__call__` method, which will return the first calculated value of `initial_input` new_structure: list list of element construction dictionaries for the builder to assemble """ stateful = { 'py_name': utils.make_python_identifier('_initial_%s' % initial_input)[0], 'real_name': 'Smooth of %s' % initial_input, 'doc': 'Returns the value taken on during the initialization phase', 'py_expr': 'functions.Initial(lambda: %s)' % ( initial_input), 'unit': 'None', 'lims': 'None', 'eqn': 'None', 'subs': '', 'kind': 'stateful', 'arguments': '' } return "%s()" % stateful['py_name'], [stateful]
python
def add_initial(initial_input): """ Constructs a stateful object for handling vensim's 'Initial' functionality Parameters ---------- initial_input: basestring The expression which will be evaluated, and the first value of which returned Returns ------- reference: basestring reference to the Initial object `__call__` method, which will return the first calculated value of `initial_input` new_structure: list list of element construction dictionaries for the builder to assemble """ stateful = { 'py_name': utils.make_python_identifier('_initial_%s' % initial_input)[0], 'real_name': 'Smooth of %s' % initial_input, 'doc': 'Returns the value taken on during the initialization phase', 'py_expr': 'functions.Initial(lambda: %s)' % ( initial_input), 'unit': 'None', 'lims': 'None', 'eqn': 'None', 'subs': '', 'kind': 'stateful', 'arguments': '' } return "%s()" % stateful['py_name'], [stateful]
[ "def", "add_initial", "(", "initial_input", ")", ":", "stateful", "=", "{", "'py_name'", ":", "utils", ".", "make_python_identifier", "(", "'_initial_%s'", "%", "initial_input", ")", "[", "0", "]", ",", "'real_name'", ":", "'Smooth of %s'", "%", "initial_input", ",", "'doc'", ":", "'Returns the value taken on during the initialization phase'", ",", "'py_expr'", ":", "'functions.Initial(lambda: %s)'", "%", "(", "initial_input", ")", ",", "'unit'", ":", "'None'", ",", "'lims'", ":", "'None'", ",", "'eqn'", ":", "'None'", ",", "'subs'", ":", "''", ",", "'kind'", ":", "'stateful'", ",", "'arguments'", ":", "''", "}", "return", "\"%s()\"", "%", "stateful", "[", "'py_name'", "]", ",", "[", "stateful", "]" ]
Constructs a stateful object for handling vensim's 'Initial' functionality Parameters ---------- initial_input: basestring The expression which will be evaluated, and the first value of which returned Returns ------- reference: basestring reference to the Initial object `__call__` method, which will return the first calculated value of `initial_input` new_structure: list list of element construction dictionaries for the builder to assemble
[ "Constructs", "a", "stateful", "object", "for", "handling", "vensim", "s", "Initial", "functionality" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L511-L544
15,118
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_macro
def add_macro(macro_name, filename, arg_names, arg_vals): """ Constructs a stateful object instantiating a 'Macro' Parameters ---------- macro_name: basestring python safe name for macro filename: basestring filepath to macro definition func_args: dict dictionary of values to be passed to macro {key: function} Returns ------- reference: basestring reference to the Initial object `__call__` method, which will return the first calculated value of `initial_input` new_structure: list list of element construction dictionaries for the builder to assemble """ func_args = '{ %s }' % ', '.join(["'%s': lambda: %s" % (key, val) for key, val in zip(arg_names, arg_vals)]) stateful = { 'py_name': '_macro_' + macro_name + '_' + '_'.join( [utils.make_python_identifier(f)[0] for f in arg_vals]), 'real_name': 'Macro Instantiation of ' + macro_name, 'doc': 'Instantiates the Macro', 'py_expr': "functions.Macro('%s', %s, '%s', time_initialization=lambda: __data['time'])" % (filename, func_args, macro_name), 'unit': 'None', 'lims': 'None', 'eqn': 'None', 'subs': '', 'kind': 'stateful', 'arguments': '' } return "%s()" % stateful['py_name'], [stateful]
python
def add_macro(macro_name, filename, arg_names, arg_vals): """ Constructs a stateful object instantiating a 'Macro' Parameters ---------- macro_name: basestring python safe name for macro filename: basestring filepath to macro definition func_args: dict dictionary of values to be passed to macro {key: function} Returns ------- reference: basestring reference to the Initial object `__call__` method, which will return the first calculated value of `initial_input` new_structure: list list of element construction dictionaries for the builder to assemble """ func_args = '{ %s }' % ', '.join(["'%s': lambda: %s" % (key, val) for key, val in zip(arg_names, arg_vals)]) stateful = { 'py_name': '_macro_' + macro_name + '_' + '_'.join( [utils.make_python_identifier(f)[0] for f in arg_vals]), 'real_name': 'Macro Instantiation of ' + macro_name, 'doc': 'Instantiates the Macro', 'py_expr': "functions.Macro('%s', %s, '%s', time_initialization=lambda: __data['time'])" % (filename, func_args, macro_name), 'unit': 'None', 'lims': 'None', 'eqn': 'None', 'subs': '', 'kind': 'stateful', 'arguments': '' } return "%s()" % stateful['py_name'], [stateful]
[ "def", "add_macro", "(", "macro_name", ",", "filename", ",", "arg_names", ",", "arg_vals", ")", ":", "func_args", "=", "'{ %s }'", "%", "', '", ".", "join", "(", "[", "\"'%s': lambda: %s\"", "%", "(", "key", ",", "val", ")", "for", "key", ",", "val", "in", "zip", "(", "arg_names", ",", "arg_vals", ")", "]", ")", "stateful", "=", "{", "'py_name'", ":", "'_macro_'", "+", "macro_name", "+", "'_'", "+", "'_'", ".", "join", "(", "[", "utils", ".", "make_python_identifier", "(", "f", ")", "[", "0", "]", "for", "f", "in", "arg_vals", "]", ")", ",", "'real_name'", ":", "'Macro Instantiation of '", "+", "macro_name", ",", "'doc'", ":", "'Instantiates the Macro'", ",", "'py_expr'", ":", "\"functions.Macro('%s', %s, '%s', time_initialization=lambda: __data['time'])\"", "%", "(", "filename", ",", "func_args", ",", "macro_name", ")", ",", "'unit'", ":", "'None'", ",", "'lims'", ":", "'None'", ",", "'eqn'", ":", "'None'", ",", "'subs'", ":", "''", ",", "'kind'", ":", "'stateful'", ",", "'arguments'", ":", "''", "}", "return", "\"%s()\"", "%", "stateful", "[", "'py_name'", "]", ",", "[", "stateful", "]" ]
Constructs a stateful object instantiating a 'Macro' Parameters ---------- macro_name: basestring python safe name for macro filename: basestring filepath to macro definition func_args: dict dictionary of values to be passed to macro {key: function} Returns ------- reference: basestring reference to the Initial object `__call__` method, which will return the first calculated value of `initial_input` new_structure: list list of element construction dictionaries for the builder to assemble
[ "Constructs", "a", "stateful", "object", "instantiating", "a", "Macro" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L547-L588
15,119
JamesPHoughton/pysd
pysd/py_backend/builder.py
add_incomplete
def add_incomplete(var_name, dependencies): """ Incomplete functions don't really need to be 'builders' as they add no new real structure, but it's helpful to have a function in which we can raise a warning about the incomplete equation at translate time. """ warnings.warn('%s has no equation specified' % var_name, SyntaxWarning, stacklevel=2) # first arg is `self` reference return "functions.incomplete(%s)" % ', '.join(dependencies[1:]), []
python
def add_incomplete(var_name, dependencies): """ Incomplete functions don't really need to be 'builders' as they add no new real structure, but it's helpful to have a function in which we can raise a warning about the incomplete equation at translate time. """ warnings.warn('%s has no equation specified' % var_name, SyntaxWarning, stacklevel=2) # first arg is `self` reference return "functions.incomplete(%s)" % ', '.join(dependencies[1:]), []
[ "def", "add_incomplete", "(", "var_name", ",", "dependencies", ")", ":", "warnings", ".", "warn", "(", "'%s has no equation specified'", "%", "var_name", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "# first arg is `self` reference", "return", "\"functions.incomplete(%s)\"", "%", "', '", ".", "join", "(", "dependencies", "[", "1", ":", "]", ")", ",", "[", "]" ]
Incomplete functions don't really need to be 'builders' as they add no new real structure, but it's helpful to have a function in which we can raise a warning about the incomplete equation at translate time.
[ "Incomplete", "functions", "don", "t", "really", "need", "to", "be", "builders", "as", "they", "add", "no", "new", "real", "structure", "but", "it", "s", "helpful", "to", "have", "a", "function", "in", "which", "we", "can", "raise", "a", "warning", "about", "the", "incomplete", "equation", "at", "translate", "time", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L591-L602
15,120
JamesPHoughton/pysd
pysd/py_backend/vensim/vensim2py.py
get_model_elements
def get_model_elements(model_str): """ Takes in a string representing model text and splits it into elements I think we're making the assumption that all newline characters are removed... Parameters ---------- model_str : string Returns ------- entries : array of dictionaries Each dictionary contains the components of a different model element, separated into the equation, units, and docstring. Examples -------- # Basic Parsing: >>> get_model_elements(r'a~b~c| d~e~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Special characters are escaped within double-quotes: >>> get_model_elements(r'a~b~c| d~e"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Double-quotes within escape groups are themselves escaped with backslashes: >>> get_model_elements(r'a~b~c| d~e"\\\"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"\\\\"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"\\\"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"\\\\"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e"x\\nx"~f| g~h~|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"x\\\\nx"', 'eqn': 'd'}, {'doc': '', 'unit': 'h', 'eqn': 'g'}] # Todo: Handle model-level or section-level documentation >>> get_model_elements(r'*** .model doc ***~ Docstring!| d~e~f| g~h~i|') [{'doc': 'Docstring!', 'unit': '', 'eqn': ''}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle control sections, returning appropriate docstring pieces >>> get_model_elements(r'a~b~c| ****.Control***~ Simulation Control Parameters | g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle the model display elements (ignore them) >>> get_model_elements(r'a~b~c| d~e~f| \\\---///junk|junk~junk') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}] Notes ----- - Tildes and pipes are not allowed in element docstrings, but we should still handle them there """ model_structure_grammar = _include_common_grammar(r""" model = (entry / section)+ sketch? entry = element "~" element "~" element ("~" element)? "|" section = element "~" element "|" sketch = ~r".*" #anything # Either an escape group, or a character that is not tilde or pipe element = (escape_group / ~r"[^~|]")* """) parser = parsimonious.Grammar(model_structure_grammar) tree = parser.parse(model_str) class ModelParser(parsimonious.NodeVisitor): def __init__(self, ast): self.entries = [] self.visit(ast) def visit_entry(self, n, vc): units, lims = parse_units(vc[2].strip()) self.entries.append({'eqn': vc[0].strip(), 'unit': units, 'lims': str(lims), 'doc': vc[4].strip(), 'kind': 'entry'}) def visit_section(self, n, vc): if vc[2].strip() != "Simulation Control Parameters": self.entries.append({'eqn': '', 'unit': '', 'lims': '', 'doc': vc[2].strip(), 'kind': 'section'}) def generic_visit(self, n, vc): return ''.join(filter(None, vc)) or n.text or '' return ModelParser(tree).entries
python
def get_model_elements(model_str): """ Takes in a string representing model text and splits it into elements I think we're making the assumption that all newline characters are removed... Parameters ---------- model_str : string Returns ------- entries : array of dictionaries Each dictionary contains the components of a different model element, separated into the equation, units, and docstring. Examples -------- # Basic Parsing: >>> get_model_elements(r'a~b~c| d~e~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Special characters are escaped within double-quotes: >>> get_model_elements(r'a~b~c| d~e"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Double-quotes within escape groups are themselves escaped with backslashes: >>> get_model_elements(r'a~b~c| d~e"\\\"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"\\\\"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"\\\"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"\\\\"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e"x\\nx"~f| g~h~|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"x\\\\nx"', 'eqn': 'd'}, {'doc': '', 'unit': 'h', 'eqn': 'g'}] # Todo: Handle model-level or section-level documentation >>> get_model_elements(r'*** .model doc ***~ Docstring!| d~e~f| g~h~i|') [{'doc': 'Docstring!', 'unit': '', 'eqn': ''}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle control sections, returning appropriate docstring pieces >>> get_model_elements(r'a~b~c| ****.Control***~ Simulation Control Parameters | g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle the model display elements (ignore them) >>> get_model_elements(r'a~b~c| d~e~f| \\\---///junk|junk~junk') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}] Notes ----- - Tildes and pipes are not allowed in element docstrings, but we should still handle them there """ model_structure_grammar = _include_common_grammar(r""" model = (entry / section)+ sketch? entry = element "~" element "~" element ("~" element)? "|" section = element "~" element "|" sketch = ~r".*" #anything # Either an escape group, or a character that is not tilde or pipe element = (escape_group / ~r"[^~|]")* """) parser = parsimonious.Grammar(model_structure_grammar) tree = parser.parse(model_str) class ModelParser(parsimonious.NodeVisitor): def __init__(self, ast): self.entries = [] self.visit(ast) def visit_entry(self, n, vc): units, lims = parse_units(vc[2].strip()) self.entries.append({'eqn': vc[0].strip(), 'unit': units, 'lims': str(lims), 'doc': vc[4].strip(), 'kind': 'entry'}) def visit_section(self, n, vc): if vc[2].strip() != "Simulation Control Parameters": self.entries.append({'eqn': '', 'unit': '', 'lims': '', 'doc': vc[2].strip(), 'kind': 'section'}) def generic_visit(self, n, vc): return ''.join(filter(None, vc)) or n.text or '' return ModelParser(tree).entries
[ "def", "get_model_elements", "(", "model_str", ")", ":", "model_structure_grammar", "=", "_include_common_grammar", "(", "r\"\"\"\n model = (entry / section)+ sketch?\n entry = element \"~\" element \"~\" element (\"~\" element)? \"|\"\n section = element \"~\" element \"|\"\n sketch = ~r\".*\" #anything\n\n # Either an escape group, or a character that is not tilde or pipe\n element = (escape_group / ~r\"[^~|]\")*\n \"\"\"", ")", "parser", "=", "parsimonious", ".", "Grammar", "(", "model_structure_grammar", ")", "tree", "=", "parser", ".", "parse", "(", "model_str", ")", "class", "ModelParser", "(", "parsimonious", ".", "NodeVisitor", ")", ":", "def", "__init__", "(", "self", ",", "ast", ")", ":", "self", ".", "entries", "=", "[", "]", "self", ".", "visit", "(", "ast", ")", "def", "visit_entry", "(", "self", ",", "n", ",", "vc", ")", ":", "units", ",", "lims", "=", "parse_units", "(", "vc", "[", "2", "]", ".", "strip", "(", ")", ")", "self", ".", "entries", ".", "append", "(", "{", "'eqn'", ":", "vc", "[", "0", "]", ".", "strip", "(", ")", ",", "'unit'", ":", "units", ",", "'lims'", ":", "str", "(", "lims", ")", ",", "'doc'", ":", "vc", "[", "4", "]", ".", "strip", "(", ")", ",", "'kind'", ":", "'entry'", "}", ")", "def", "visit_section", "(", "self", ",", "n", ",", "vc", ")", ":", "if", "vc", "[", "2", "]", ".", "strip", "(", ")", "!=", "\"Simulation Control Parameters\"", ":", "self", ".", "entries", ".", "append", "(", "{", "'eqn'", ":", "''", ",", "'unit'", ":", "''", ",", "'lims'", ":", "''", ",", "'doc'", ":", "vc", "[", "2", "]", ".", "strip", "(", ")", ",", "'kind'", ":", "'section'", "}", ")", "def", "generic_visit", "(", "self", ",", "n", ",", "vc", ")", ":", "return", "''", ".", "join", "(", "filter", "(", "None", ",", "vc", ")", ")", "or", "n", ".", "text", "or", "''", "return", "ModelParser", "(", "tree", ")", ".", "entries" ]
Takes in a string representing model text and splits it into elements I think we're making the assumption that all newline characters are removed... Parameters ---------- model_str : string Returns ------- entries : array of dictionaries Each dictionary contains the components of a different model element, separated into the equation, units, and docstring. Examples -------- # Basic Parsing: >>> get_model_elements(r'a~b~c| d~e~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Special characters are escaped within double-quotes: >>> get_model_elements(r'a~b~c| d~e"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Double-quotes within escape groups are themselves escaped with backslashes: >>> get_model_elements(r'a~b~c| d~e"\\\"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"\\\\"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"\\\"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"\\\\"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e"x\\nx"~f| g~h~|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"x\\\\nx"', 'eqn': 'd'}, {'doc': '', 'unit': 'h', 'eqn': 'g'}] # Todo: Handle model-level or section-level documentation >>> get_model_elements(r'*** .model doc ***~ Docstring!| d~e~f| g~h~i|') [{'doc': 'Docstring!', 'unit': '', 'eqn': ''}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle control sections, returning appropriate docstring pieces >>> get_model_elements(r'a~b~c| ****.Control***~ Simulation Control Parameters | g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle the model display elements (ignore them) >>> get_model_elements(r'a~b~c| d~e~f| \\\---///junk|junk~junk') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}] Notes ----- - Tildes and pipes are not allowed in element docstrings, but we should still handle them there
[ "Takes", "in", "a", "string", "representing", "model", "text", "and", "splits", "it", "into", "elements" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L87-L181
15,121
JamesPHoughton/pysd
pysd/py_backend/vensim/vensim2py.py
get_equation_components
def get_equation_components(equation_str): """ Breaks down a string representing only the equation part of a model element. Recognizes the various types of model elements that may exist, and identifies them. Parameters ---------- equation_str : basestring the first section in each model element - the full equation. Returns ------- Returns a dictionary containing the following: real_name: basestring The name of the element as given in the original vensim file subs: list of strings list of subscripts or subscript elements expr: basestring kind: basestring What type of equation have we found? - *component* - normal model expression or constant - *lookup* - a lookup table - *subdef* - a subscript definition Examples -------- >>> get_equation_components(r'constant = 25') {'expr': '25', 'kind': 'component', 'subs': [], 'real_name': 'constant'} Notes ----- in this function we dont create python identifiers, we use real names. This is so that when everything comes back together, we can manage any potential namespace conflicts properly """ component_structure_grammar = _include_common_grammar(r""" entry = component / subscript_definition / lookup_definition component = name _ subscriptlist? _ "=" _ expression subscript_definition = name _ ":" _ subscript _ ("," _ subscript)* lookup_definition = name _ &"(" _ expression # uses lookahead assertion to capture whole group name = basic_id / escape_group subscriptlist = '[' _ subscript _ ("," _ subscript)* _ ']' expression = ~r".*" # expression could be anything, at this point. subscript = basic_id / escape_group """) # replace any amount of whitespace with a single space equation_str = equation_str.replace('\\t', ' ') equation_str = re.sub(r"\s+", ' ', equation_str) parser = parsimonious.Grammar(component_structure_grammar) tree = parser.parse(equation_str) class ComponentParser(parsimonious.NodeVisitor): def __init__(self, ast): self.subscripts = [] self.real_name = None self.expression = None self.kind = None self.visit(ast) def visit_subscript_definition(self, n, vc): self.kind = 'subdef' def visit_lookup_definition(self, n, vc): self.kind = 'lookup' def visit_component(self, n, vc): self.kind = 'component' def visit_name(self, n, vc): (name,) = vc self.real_name = name.strip() def visit_subscript(self, n, vc): (subscript,) = vc self.subscripts.append(subscript.strip()) def visit_expression(self, n, vc): self.expression = n.text.strip() def generic_visit(self, n, vc): return ''.join(filter(None, vc)) or n.text def visit__(self, n, vc): return ' ' parse_object = ComponentParser(tree) return {'real_name': parse_object.real_name, 'subs': parse_object.subscripts, 'expr': parse_object.expression, 'kind': parse_object.kind}
python
def get_equation_components(equation_str): """ Breaks down a string representing only the equation part of a model element. Recognizes the various types of model elements that may exist, and identifies them. Parameters ---------- equation_str : basestring the first section in each model element - the full equation. Returns ------- Returns a dictionary containing the following: real_name: basestring The name of the element as given in the original vensim file subs: list of strings list of subscripts or subscript elements expr: basestring kind: basestring What type of equation have we found? - *component* - normal model expression or constant - *lookup* - a lookup table - *subdef* - a subscript definition Examples -------- >>> get_equation_components(r'constant = 25') {'expr': '25', 'kind': 'component', 'subs': [], 'real_name': 'constant'} Notes ----- in this function we dont create python identifiers, we use real names. This is so that when everything comes back together, we can manage any potential namespace conflicts properly """ component_structure_grammar = _include_common_grammar(r""" entry = component / subscript_definition / lookup_definition component = name _ subscriptlist? _ "=" _ expression subscript_definition = name _ ":" _ subscript _ ("," _ subscript)* lookup_definition = name _ &"(" _ expression # uses lookahead assertion to capture whole group name = basic_id / escape_group subscriptlist = '[' _ subscript _ ("," _ subscript)* _ ']' expression = ~r".*" # expression could be anything, at this point. subscript = basic_id / escape_group """) # replace any amount of whitespace with a single space equation_str = equation_str.replace('\\t', ' ') equation_str = re.sub(r"\s+", ' ', equation_str) parser = parsimonious.Grammar(component_structure_grammar) tree = parser.parse(equation_str) class ComponentParser(parsimonious.NodeVisitor): def __init__(self, ast): self.subscripts = [] self.real_name = None self.expression = None self.kind = None self.visit(ast) def visit_subscript_definition(self, n, vc): self.kind = 'subdef' def visit_lookup_definition(self, n, vc): self.kind = 'lookup' def visit_component(self, n, vc): self.kind = 'component' def visit_name(self, n, vc): (name,) = vc self.real_name = name.strip() def visit_subscript(self, n, vc): (subscript,) = vc self.subscripts.append(subscript.strip()) def visit_expression(self, n, vc): self.expression = n.text.strip() def generic_visit(self, n, vc): return ''.join(filter(None, vc)) or n.text def visit__(self, n, vc): return ' ' parse_object = ComponentParser(tree) return {'real_name': parse_object.real_name, 'subs': parse_object.subscripts, 'expr': parse_object.expression, 'kind': parse_object.kind}
[ "def", "get_equation_components", "(", "equation_str", ")", ":", "component_structure_grammar", "=", "_include_common_grammar", "(", "r\"\"\"\n entry = component / subscript_definition / lookup_definition\n component = name _ subscriptlist? _ \"=\" _ expression\n subscript_definition = name _ \":\" _ subscript _ (\",\" _ subscript)*\n lookup_definition = name _ &\"(\" _ expression # uses lookahead assertion to capture whole group\n\n name = basic_id / escape_group\n subscriptlist = '[' _ subscript _ (\",\" _ subscript)* _ ']'\n expression = ~r\".*\" # expression could be anything, at this point.\n\n subscript = basic_id / escape_group\n \"\"\"", ")", "# replace any amount of whitespace with a single space", "equation_str", "=", "equation_str", ".", "replace", "(", "'\\\\t'", ",", "' '", ")", "equation_str", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "' '", ",", "equation_str", ")", "parser", "=", "parsimonious", ".", "Grammar", "(", "component_structure_grammar", ")", "tree", "=", "parser", ".", "parse", "(", "equation_str", ")", "class", "ComponentParser", "(", "parsimonious", ".", "NodeVisitor", ")", ":", "def", "__init__", "(", "self", ",", "ast", ")", ":", "self", ".", "subscripts", "=", "[", "]", "self", ".", "real_name", "=", "None", "self", ".", "expression", "=", "None", "self", ".", "kind", "=", "None", "self", ".", "visit", "(", "ast", ")", "def", "visit_subscript_definition", "(", "self", ",", "n", ",", "vc", ")", ":", "self", ".", "kind", "=", "'subdef'", "def", "visit_lookup_definition", "(", "self", ",", "n", ",", "vc", ")", ":", "self", ".", "kind", "=", "'lookup'", "def", "visit_component", "(", "self", ",", "n", ",", "vc", ")", ":", "self", ".", "kind", "=", "'component'", "def", "visit_name", "(", "self", ",", "n", ",", "vc", ")", ":", "(", "name", ",", ")", "=", "vc", "self", ".", "real_name", "=", "name", ".", "strip", "(", ")", "def", "visit_subscript", "(", "self", ",", "n", ",", "vc", ")", ":", "(", "subscript", ",", ")", "=", "vc", "self", ".", "subscripts", ".", "append", "(", "subscript", ".", "strip", "(", ")", ")", "def", "visit_expression", "(", "self", ",", "n", ",", "vc", ")", ":", "self", ".", "expression", "=", "n", ".", "text", ".", "strip", "(", ")", "def", "generic_visit", "(", "self", ",", "n", ",", "vc", ")", ":", "return", "''", ".", "join", "(", "filter", "(", "None", ",", "vc", ")", ")", "or", "n", ".", "text", "def", "visit__", "(", "self", ",", "n", ",", "vc", ")", ":", "return", "' '", "parse_object", "=", "ComponentParser", "(", "tree", ")", "return", "{", "'real_name'", ":", "parse_object", ".", "real_name", ",", "'subs'", ":", "parse_object", ".", "subscripts", ",", "'expr'", ":", "parse_object", ".", "expression", ",", "'kind'", ":", "parse_object", ".", "kind", "}" ]
Breaks down a string representing only the equation part of a model element. Recognizes the various types of model elements that may exist, and identifies them. Parameters ---------- equation_str : basestring the first section in each model element - the full equation. Returns ------- Returns a dictionary containing the following: real_name: basestring The name of the element as given in the original vensim file subs: list of strings list of subscripts or subscript elements expr: basestring kind: basestring What type of equation have we found? - *component* - normal model expression or constant - *lookup* - a lookup table - *subdef* - a subscript definition Examples -------- >>> get_equation_components(r'constant = 25') {'expr': '25', 'kind': 'component', 'subs': [], 'real_name': 'constant'} Notes ----- in this function we dont create python identifiers, we use real names. This is so that when everything comes back together, we can manage any potential namespace conflicts properly
[ "Breaks", "down", "a", "string", "representing", "only", "the", "equation", "part", "of", "a", "model", "element", ".", "Recognizes", "the", "various", "types", "of", "model", "elements", "that", "may", "exist", "and", "identifies", "them", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L206-L305
15,122
JamesPHoughton/pysd
pysd/py_backend/vensim/vensim2py.py
parse_units
def parse_units(units_str): """ Extract and parse the units Extract the bounds over which the expression is assumed to apply. Parameters ---------- units_str Returns ------- Examples -------- >>> parse_units('Widgets/Month [-10,10,1]') ('Widgets/Month', (-10,10,1)) >>> parse_units('Month [0,?]') ('Month', [-10, None]) >>> parse_units('Widgets [0,100]') ('Widgets', (0, 100)) >>> parse_units('Widgets') ('Widgets', (None, None)) >>> parse_units('[0, 100]') ('', (0, 100)) """ if not len(units_str): return units_str, (None, None) if units_str[-1] == ']': units, lims = units_str.rsplit('[') # type: str, str else: units = units_str lims = '?, ?]' lims = tuple([float(x) if x.strip() != '?' else None for x in lims.strip(']').split(',')]) return units.strip(), lims
python
def parse_units(units_str): """ Extract and parse the units Extract the bounds over which the expression is assumed to apply. Parameters ---------- units_str Returns ------- Examples -------- >>> parse_units('Widgets/Month [-10,10,1]') ('Widgets/Month', (-10,10,1)) >>> parse_units('Month [0,?]') ('Month', [-10, None]) >>> parse_units('Widgets [0,100]') ('Widgets', (0, 100)) >>> parse_units('Widgets') ('Widgets', (None, None)) >>> parse_units('[0, 100]') ('', (0, 100)) """ if not len(units_str): return units_str, (None, None) if units_str[-1] == ']': units, lims = units_str.rsplit('[') # type: str, str else: units = units_str lims = '?, ?]' lims = tuple([float(x) if x.strip() != '?' else None for x in lims.strip(']').split(',')]) return units.strip(), lims
[ "def", "parse_units", "(", "units_str", ")", ":", "if", "not", "len", "(", "units_str", ")", ":", "return", "units_str", ",", "(", "None", ",", "None", ")", "if", "units_str", "[", "-", "1", "]", "==", "']'", ":", "units", ",", "lims", "=", "units_str", ".", "rsplit", "(", "'['", ")", "# type: str, str", "else", ":", "units", "=", "units_str", "lims", "=", "'?, ?]'", "lims", "=", "tuple", "(", "[", "float", "(", "x", ")", "if", "x", ".", "strip", "(", ")", "!=", "'?'", "else", "None", "for", "x", "in", "lims", ".", "strip", "(", "']'", ")", ".", "split", "(", "','", ")", "]", ")", "return", "units", ".", "strip", "(", ")", ",", "lims" ]
Extract and parse the units Extract the bounds over which the expression is assumed to apply. Parameters ---------- units_str Returns ------- Examples -------- >>> parse_units('Widgets/Month [-10,10,1]') ('Widgets/Month', (-10,10,1)) >>> parse_units('Month [0,?]') ('Month', [-10, None]) >>> parse_units('Widgets [0,100]') ('Widgets', (0, 100)) >>> parse_units('Widgets') ('Widgets', (None, None)) >>> parse_units('[0, 100]') ('', (0, 100))
[ "Extract", "and", "parse", "the", "units", "Extract", "the", "bounds", "over", "which", "the", "expression", "is", "assumed", "to", "apply", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L308-L349
15,123
JamesPHoughton/pysd
pysd/py_backend/vensim/vensim2py.py
parse_lookup_expression
def parse_lookup_expression(element): """ This syntax parses lookups that are defined with their own element """ lookup_grammar = r""" lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")" number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?" _ = ~r"[\s\\]*" # whitespace character range = _ "[" ~r"[^\]]*" "]" _ "," """ parser = parsimonious.Grammar(lookup_grammar) tree = parser.parse(element['expr']) class LookupParser(parsimonious.NodeVisitor): def __init__(self, ast): self.translation = "" self.new_structure = [] self.visit(ast) def visit__(self, n, vc): # remove whitespace return '' def visit_lookup(self, n, vc): pairs = max(vc, key=len) mixed_list = pairs.replace('(', '').replace(')', '').split(',') xs = mixed_list[::2] ys = mixed_list[1::2] string = "functions.lookup(x, [%(xs)s], [%(ys)s])" % { 'xs': ','.join(xs), 'ys': ','.join(ys) } self.translation = string def generic_visit(self, n, vc): return ''.join(filter(None, vc)) or n.text parse_object = LookupParser(tree) return {'py_expr': parse_object.translation, 'arguments': 'x'}
python
def parse_lookup_expression(element): """ This syntax parses lookups that are defined with their own element """ lookup_grammar = r""" lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")" number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?" _ = ~r"[\s\\]*" # whitespace character range = _ "[" ~r"[^\]]*" "]" _ "," """ parser = parsimonious.Grammar(lookup_grammar) tree = parser.parse(element['expr']) class LookupParser(parsimonious.NodeVisitor): def __init__(self, ast): self.translation = "" self.new_structure = [] self.visit(ast) def visit__(self, n, vc): # remove whitespace return '' def visit_lookup(self, n, vc): pairs = max(vc, key=len) mixed_list = pairs.replace('(', '').replace(')', '').split(',') xs = mixed_list[::2] ys = mixed_list[1::2] string = "functions.lookup(x, [%(xs)s], [%(ys)s])" % { 'xs': ','.join(xs), 'ys': ','.join(ys) } self.translation = string def generic_visit(self, n, vc): return ''.join(filter(None, vc)) or n.text parse_object = LookupParser(tree) return {'py_expr': parse_object.translation, 'arguments': 'x'}
[ "def", "parse_lookup_expression", "(", "element", ")", ":", "lookup_grammar", "=", "r\"\"\"\n lookup = _ \"(\" range? _ ( \"(\" _ number _ \",\" _ number _ \")\" _ \",\"? _ )+ \")\"\n number = (\"+\"/\"-\")? ~r\"\\d+\\.?\\d*(e[+-]\\d+)?\"\n _ = ~r\"[\\s\\\\]*\" # whitespace character\n\trange = _ \"[\" ~r\"[^\\]]*\" \"]\" _ \",\"\n \"\"\"", "parser", "=", "parsimonious", ".", "Grammar", "(", "lookup_grammar", ")", "tree", "=", "parser", ".", "parse", "(", "element", "[", "'expr'", "]", ")", "class", "LookupParser", "(", "parsimonious", ".", "NodeVisitor", ")", ":", "def", "__init__", "(", "self", ",", "ast", ")", ":", "self", ".", "translation", "=", "\"\"", "self", ".", "new_structure", "=", "[", "]", "self", ".", "visit", "(", "ast", ")", "def", "visit__", "(", "self", ",", "n", ",", "vc", ")", ":", "# remove whitespace", "return", "''", "def", "visit_lookup", "(", "self", ",", "n", ",", "vc", ")", ":", "pairs", "=", "max", "(", "vc", ",", "key", "=", "len", ")", "mixed_list", "=", "pairs", ".", "replace", "(", "'('", ",", "''", ")", ".", "replace", "(", "')'", ",", "''", ")", ".", "split", "(", "','", ")", "xs", "=", "mixed_list", "[", ":", ":", "2", "]", "ys", "=", "mixed_list", "[", "1", ":", ":", "2", "]", "string", "=", "\"functions.lookup(x, [%(xs)s], [%(ys)s])\"", "%", "{", "'xs'", ":", "','", ".", "join", "(", "xs", ")", ",", "'ys'", ":", "','", ".", "join", "(", "ys", ")", "}", "self", ".", "translation", "=", "string", "def", "generic_visit", "(", "self", ",", "n", ",", "vc", ")", ":", "return", "''", ".", "join", "(", "filter", "(", "None", ",", "vc", ")", ")", "or", "n", ".", "text", "parse_object", "=", "LookupParser", "(", "tree", ")", "return", "{", "'py_expr'", ":", "parse_object", ".", "translation", ",", "'arguments'", ":", "'x'", "}" ]
This syntax parses lookups that are defined with their own element
[ "This", "syntax", "parses", "lookups", "that", "are", "defined", "with", "their", "own", "element" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L807-L845
15,124
JamesPHoughton/pysd
pysd/py_backend/utils.py
dict_find
def dict_find(in_dict, value): """ Helper function for looking up directory keys by their values. This isn't robust to repeated values Parameters ---------- in_dict : dictionary A dictionary containing `value` value : any type What we wish to find in the dictionary Returns ------- key: basestring The key at which the value can be found Examples -------- >>> dict_find({'Key1': 'A', 'Key2': 'B'}, 'B') 'Key2' """ # Todo: make this robust to repeated values # Todo: make this robust to missing values return list(in_dict.keys())[list(in_dict.values()).index(value)]
python
def dict_find(in_dict, value): """ Helper function for looking up directory keys by their values. This isn't robust to repeated values Parameters ---------- in_dict : dictionary A dictionary containing `value` value : any type What we wish to find in the dictionary Returns ------- key: basestring The key at which the value can be found Examples -------- >>> dict_find({'Key1': 'A', 'Key2': 'B'}, 'B') 'Key2' """ # Todo: make this robust to repeated values # Todo: make this robust to missing values return list(in_dict.keys())[list(in_dict.values()).index(value)]
[ "def", "dict_find", "(", "in_dict", ",", "value", ")", ":", "# Todo: make this robust to repeated values", "# Todo: make this robust to missing values", "return", "list", "(", "in_dict", ".", "keys", "(", ")", ")", "[", "list", "(", "in_dict", ".", "values", "(", ")", ")", ".", "index", "(", "value", ")", "]" ]
Helper function for looking up directory keys by their values. This isn't robust to repeated values Parameters ---------- in_dict : dictionary A dictionary containing `value` value : any type What we wish to find in the dictionary Returns ------- key: basestring The key at which the value can be found Examples -------- >>> dict_find({'Key1': 'A', 'Key2': 'B'}, 'B') 'Key2'
[ "Helper", "function", "for", "looking", "up", "directory", "keys", "by", "their", "values", ".", "This", "isn", "t", "robust", "to", "repeated", "values" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L9-L34
15,125
JamesPHoughton/pysd
pysd/py_backend/utils.py
find_subscript_name
def find_subscript_name(subscript_dict, element): """ Given a subscript dictionary, and a member of a subscript family, return the first key of which the member is within the value list. If element is already a subscript name, return that Parameters ---------- subscript_dict: dictionary Follows the {'subscript name':['list','of','subscript','elements']} format element: string Returns ------- Examples: >>> find_subscript_name({'Dim1': ['A', 'B'], ... 'Dim2': ['C', 'D', 'E'], ... 'Dim3': ['F', 'G', 'H', 'I']}, ... 'D') 'Dim2' """ if element in subscript_dict.keys(): return element for name, elements in subscript_dict.items(): if element in elements: return name
python
def find_subscript_name(subscript_dict, element): """ Given a subscript dictionary, and a member of a subscript family, return the first key of which the member is within the value list. If element is already a subscript name, return that Parameters ---------- subscript_dict: dictionary Follows the {'subscript name':['list','of','subscript','elements']} format element: string Returns ------- Examples: >>> find_subscript_name({'Dim1': ['A', 'B'], ... 'Dim2': ['C', 'D', 'E'], ... 'Dim3': ['F', 'G', 'H', 'I']}, ... 'D') 'Dim2' """ if element in subscript_dict.keys(): return element for name, elements in subscript_dict.items(): if element in elements: return name
[ "def", "find_subscript_name", "(", "subscript_dict", ",", "element", ")", ":", "if", "element", "in", "subscript_dict", ".", "keys", "(", ")", ":", "return", "element", "for", "name", ",", "elements", "in", "subscript_dict", ".", "items", "(", ")", ":", "if", "element", "in", "elements", ":", "return", "name" ]
Given a subscript dictionary, and a member of a subscript family, return the first key of which the member is within the value list. If element is already a subscript name, return that Parameters ---------- subscript_dict: dictionary Follows the {'subscript name':['list','of','subscript','elements']} format element: string Returns ------- Examples: >>> find_subscript_name({'Dim1': ['A', 'B'], ... 'Dim2': ['C', 'D', 'E'], ... 'Dim3': ['F', 'G', 'H', 'I']}, ... 'D') 'Dim2'
[ "Given", "a", "subscript", "dictionary", "and", "a", "member", "of", "a", "subscript", "family", "return", "the", "first", "key", "of", "which", "the", "member", "is", "within", "the", "value", "list", ".", "If", "element", "is", "already", "a", "subscript", "name", "return", "that" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L65-L93
15,126
JamesPHoughton/pysd
pysd/py_backend/utils.py
make_coord_dict
def make_coord_dict(subs, subscript_dict, terse=True): """ This is for assisting with the lookup of a particular element, such that the output of this function would take the place of %s in this expression `variable.loc[%s]` Parameters ---------- subs: list of strings coordinates, either as names of dimensions, or positions within a dimension subscript_dict: dict the full dictionary of subscript names and values terse: Binary Flag - If true, includes only elements that do not cover the full range of values in their respective dimension - If false, returns all dimensions Returns ------- coordinates: dictionary Coordinates needed to access the xarray quantities we're interested in. Examples -------- >>> make_coord_dict(['Dim1', 'D'], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}) {'Dim2': ['D']} >>> make_coord_dict(['Dim1', 'D'], {'Dim1': ['A', 'B', 'C'], 'Dim2':['D', 'E', 'F']}, >>> terse=False) {'Dim2': ['D'], 'Dim1': ['A', 'B', 'C']} """ sub_elems_list = [y for x in subscript_dict.values() for y in x] coordinates = {} for sub in subs: if sub in sub_elems_list: name = find_subscript_name(subscript_dict, sub) coordinates[name] = [sub] elif not terse: coordinates[sub] = subscript_dict[sub] return coordinates
python
def make_coord_dict(subs, subscript_dict, terse=True): """ This is for assisting with the lookup of a particular element, such that the output of this function would take the place of %s in this expression `variable.loc[%s]` Parameters ---------- subs: list of strings coordinates, either as names of dimensions, or positions within a dimension subscript_dict: dict the full dictionary of subscript names and values terse: Binary Flag - If true, includes only elements that do not cover the full range of values in their respective dimension - If false, returns all dimensions Returns ------- coordinates: dictionary Coordinates needed to access the xarray quantities we're interested in. Examples -------- >>> make_coord_dict(['Dim1', 'D'], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}) {'Dim2': ['D']} >>> make_coord_dict(['Dim1', 'D'], {'Dim1': ['A', 'B', 'C'], 'Dim2':['D', 'E', 'F']}, >>> terse=False) {'Dim2': ['D'], 'Dim1': ['A', 'B', 'C']} """ sub_elems_list = [y for x in subscript_dict.values() for y in x] coordinates = {} for sub in subs: if sub in sub_elems_list: name = find_subscript_name(subscript_dict, sub) coordinates[name] = [sub] elif not terse: coordinates[sub] = subscript_dict[sub] return coordinates
[ "def", "make_coord_dict", "(", "subs", ",", "subscript_dict", ",", "terse", "=", "True", ")", ":", "sub_elems_list", "=", "[", "y", "for", "x", "in", "subscript_dict", ".", "values", "(", ")", "for", "y", "in", "x", "]", "coordinates", "=", "{", "}", "for", "sub", "in", "subs", ":", "if", "sub", "in", "sub_elems_list", ":", "name", "=", "find_subscript_name", "(", "subscript_dict", ",", "sub", ")", "coordinates", "[", "name", "]", "=", "[", "sub", "]", "elif", "not", "terse", ":", "coordinates", "[", "sub", "]", "=", "subscript_dict", "[", "sub", "]", "return", "coordinates" ]
This is for assisting with the lookup of a particular element, such that the output of this function would take the place of %s in this expression `variable.loc[%s]` Parameters ---------- subs: list of strings coordinates, either as names of dimensions, or positions within a dimension subscript_dict: dict the full dictionary of subscript names and values terse: Binary Flag - If true, includes only elements that do not cover the full range of values in their respective dimension - If false, returns all dimensions Returns ------- coordinates: dictionary Coordinates needed to access the xarray quantities we're interested in. Examples -------- >>> make_coord_dict(['Dim1', 'D'], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}) {'Dim2': ['D']} >>> make_coord_dict(['Dim1', 'D'], {'Dim1': ['A', 'B', 'C'], 'Dim2':['D', 'E', 'F']}, >>> terse=False) {'Dim2': ['D'], 'Dim1': ['A', 'B', 'C']}
[ "This", "is", "for", "assisting", "with", "the", "lookup", "of", "a", "particular", "element", "such", "that", "the", "output", "of", "this", "function", "would", "take", "the", "place", "of", "%s", "in", "this", "expression" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L96-L135
15,127
JamesPHoughton/pysd
pysd/py_backend/utils.py
make_python_identifier
def make_python_identifier(string, namespace=None, reserved_words=None, convert='drop', handle='force'): """ Takes an arbitrary string and creates a valid Python identifier. If the input string is in the namespace, return its value. If the python identifier created is already in the namespace, but the input string is not (ie, two similar strings resolve to the same python identifier) or if the identifier is a reserved word in the reserved_words list, or is a python default reserved word, adds _1, or if _1 is in the namespace, _2, etc. Parameters ---------- string : <basestring> The text to be converted into a valid python identifier namespace : <dictionary> Map of existing translations into python safe identifiers. This is to ensure that two strings are not translated into the same python identifier reserved_words : <list of strings> List of words that are reserved (because they have other meanings in this particular program, such as also being the names of libraries, etc. convert : <string> Tells the function what to do with characters that are not valid in python identifiers - 'hex' implies that they will be converted to their hexidecimal representation. This is handy if you have variables that have a lot of reserved characters, or you don't want the name to be dependent on when things were added to the namespace - 'drop' implies that they will just be dropped altogether handle : <string> Tells the function how to deal with namespace conflicts - 'force' will create a representation which is not in conflict by appending _n to the resulting variable where n is the lowest number necessary to avoid a conflict - 'throw' will raise an exception Returns ------- identifier : <string> A vaild python identifier based on the input string namespace : <dictionary> An updated map of the translations of words to python identifiers, including the passed in 'string'. Examples -------- >>> make_python_identifier('Capital') ('capital', {'Capital': 'capital'}) >>> make_python_identifier('multiple words') ('multiple_words', {'multiple words': 'multiple_words'}) >>> make_python_identifier('multiple spaces') ('multiple_spaces', {'multiple spaces': 'multiple_spaces'}) When the name is a python keyword, add '_1' to differentiate it >>> make_python_identifier('for') ('for_1', {'for': 'for_1'}) Remove leading and trailing whitespace >>> make_python_identifier(' whitespace ') ('whitespace', {' whitespace ': 'whitespace'}) Remove most special characters outright: >>> make_python_identifier('H@t tr!ck') ('ht_trck', {'H@t tr!ck': 'ht_trck'}) Replace special characters with their hex representations >>> make_python_identifier('H@t tr!ck', convert='hex') ('h40t_tr21ck', {'H@t tr!ck': 'h40t_tr21ck'}) remove leading digits >>> make_python_identifier('123abc') ('abc', {'123abc': 'abc'}) already in namespace >>> make_python_identifier('Variable$', namespace={'Variable$': 'variable'}) ('variable', {'Variable$': 'variable'}) namespace conflicts >>> make_python_identifier('Variable$', namespace={'Variable@': 'variable'}) ('variable_1', {'Variable@': 'variable', 'Variable$': 'variable_1'}) >>> make_python_identifier('Variable$', namespace={'Variable@': 'variable', >>> 'Variable%': 'variable_1'}) ('variable_2', {'Variable@': 'variable', 'Variable%': 'variable_1', 'Variable$': 'variable_2'}) throw exception instead >>> make_python_identifier('Variable$', namespace={'Variable@': 'variable'}, handle='throw') Traceback (most recent call last): ... NameError: variable already exists in namespace or is a reserved word References ---------- Identifiers must follow the convention outlined here: https://docs.python.org/2/reference/lexical_analysis.html#identifiers """ if namespace is None: namespace = dict() if reserved_words is None: reserved_words = list() if string in namespace: return namespace[string], namespace # create a working copy (and make it lowercase, while we're at it) s = string.lower() # remove leading and trailing whitespace s = s.strip() # Make spaces into underscores s = re.sub('[\\s\\t\\n]+', '_', s) if convert == 'hex': # Convert invalid characters to hex. Note: \p{l} designates all Unicode letter characters (any language), # \p{m} designates all mark symbols (e.g., vowel marks in Indian scrips, such as the final) # and \p{n} designates all numbers. We allow any of these to be present in the regex. s = ''.join([c.encode("hex") if re.findall('[^\p{l}\p{m}\p{n}_]', c) else c for c in s]) elif convert == 'drop': # Remove invalid characters s = re.sub('[^\p{l}\p{m}\p{n}_]', '', s) # Remove leading characters until we find a letter or underscore. Only letters can be leading characters. s = re.sub('^[^\p{l}_]+', '', s) # Check that the string is not a python identifier while (s in keyword.kwlist or s in namespace.values() or s in reserved_words): if handle == 'throw': raise NameError(s + ' already exists in namespace or is a reserved word') if handle == 'force': if re.match(".*?_\d+$", s): i = re.match(".*?_(\d+)$", s).groups()[0] s = s.strip('_' + i) + '_' + str(int(i) + 1) else: s += '_1' namespace[string] = s return s, namespace
python
def make_python_identifier(string, namespace=None, reserved_words=None, convert='drop', handle='force'): """ Takes an arbitrary string and creates a valid Python identifier. If the input string is in the namespace, return its value. If the python identifier created is already in the namespace, but the input string is not (ie, two similar strings resolve to the same python identifier) or if the identifier is a reserved word in the reserved_words list, or is a python default reserved word, adds _1, or if _1 is in the namespace, _2, etc. Parameters ---------- string : <basestring> The text to be converted into a valid python identifier namespace : <dictionary> Map of existing translations into python safe identifiers. This is to ensure that two strings are not translated into the same python identifier reserved_words : <list of strings> List of words that are reserved (because they have other meanings in this particular program, such as also being the names of libraries, etc. convert : <string> Tells the function what to do with characters that are not valid in python identifiers - 'hex' implies that they will be converted to their hexidecimal representation. This is handy if you have variables that have a lot of reserved characters, or you don't want the name to be dependent on when things were added to the namespace - 'drop' implies that they will just be dropped altogether handle : <string> Tells the function how to deal with namespace conflicts - 'force' will create a representation which is not in conflict by appending _n to the resulting variable where n is the lowest number necessary to avoid a conflict - 'throw' will raise an exception Returns ------- identifier : <string> A vaild python identifier based on the input string namespace : <dictionary> An updated map of the translations of words to python identifiers, including the passed in 'string'. Examples -------- >>> make_python_identifier('Capital') ('capital', {'Capital': 'capital'}) >>> make_python_identifier('multiple words') ('multiple_words', {'multiple words': 'multiple_words'}) >>> make_python_identifier('multiple spaces') ('multiple_spaces', {'multiple spaces': 'multiple_spaces'}) When the name is a python keyword, add '_1' to differentiate it >>> make_python_identifier('for') ('for_1', {'for': 'for_1'}) Remove leading and trailing whitespace >>> make_python_identifier(' whitespace ') ('whitespace', {' whitespace ': 'whitespace'}) Remove most special characters outright: >>> make_python_identifier('H@t tr!ck') ('ht_trck', {'H@t tr!ck': 'ht_trck'}) Replace special characters with their hex representations >>> make_python_identifier('H@t tr!ck', convert='hex') ('h40t_tr21ck', {'H@t tr!ck': 'h40t_tr21ck'}) remove leading digits >>> make_python_identifier('123abc') ('abc', {'123abc': 'abc'}) already in namespace >>> make_python_identifier('Variable$', namespace={'Variable$': 'variable'}) ('variable', {'Variable$': 'variable'}) namespace conflicts >>> make_python_identifier('Variable$', namespace={'Variable@': 'variable'}) ('variable_1', {'Variable@': 'variable', 'Variable$': 'variable_1'}) >>> make_python_identifier('Variable$', namespace={'Variable@': 'variable', >>> 'Variable%': 'variable_1'}) ('variable_2', {'Variable@': 'variable', 'Variable%': 'variable_1', 'Variable$': 'variable_2'}) throw exception instead >>> make_python_identifier('Variable$', namespace={'Variable@': 'variable'}, handle='throw') Traceback (most recent call last): ... NameError: variable already exists in namespace or is a reserved word References ---------- Identifiers must follow the convention outlined here: https://docs.python.org/2/reference/lexical_analysis.html#identifiers """ if namespace is None: namespace = dict() if reserved_words is None: reserved_words = list() if string in namespace: return namespace[string], namespace # create a working copy (and make it lowercase, while we're at it) s = string.lower() # remove leading and trailing whitespace s = s.strip() # Make spaces into underscores s = re.sub('[\\s\\t\\n]+', '_', s) if convert == 'hex': # Convert invalid characters to hex. Note: \p{l} designates all Unicode letter characters (any language), # \p{m} designates all mark symbols (e.g., vowel marks in Indian scrips, such as the final) # and \p{n} designates all numbers. We allow any of these to be present in the regex. s = ''.join([c.encode("hex") if re.findall('[^\p{l}\p{m}\p{n}_]', c) else c for c in s]) elif convert == 'drop': # Remove invalid characters s = re.sub('[^\p{l}\p{m}\p{n}_]', '', s) # Remove leading characters until we find a letter or underscore. Only letters can be leading characters. s = re.sub('^[^\p{l}_]+', '', s) # Check that the string is not a python identifier while (s in keyword.kwlist or s in namespace.values() or s in reserved_words): if handle == 'throw': raise NameError(s + ' already exists in namespace or is a reserved word') if handle == 'force': if re.match(".*?_\d+$", s): i = re.match(".*?_(\d+)$", s).groups()[0] s = s.strip('_' + i) + '_' + str(int(i) + 1) else: s += '_1' namespace[string] = s return s, namespace
[ "def", "make_python_identifier", "(", "string", ",", "namespace", "=", "None", ",", "reserved_words", "=", "None", ",", "convert", "=", "'drop'", ",", "handle", "=", "'force'", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "dict", "(", ")", "if", "reserved_words", "is", "None", ":", "reserved_words", "=", "list", "(", ")", "if", "string", "in", "namespace", ":", "return", "namespace", "[", "string", "]", ",", "namespace", "# create a working copy (and make it lowercase, while we're at it)", "s", "=", "string", ".", "lower", "(", ")", "# remove leading and trailing whitespace", "s", "=", "s", ".", "strip", "(", ")", "# Make spaces into underscores", "s", "=", "re", ".", "sub", "(", "'[\\\\s\\\\t\\\\n]+'", ",", "'_'", ",", "s", ")", "if", "convert", "==", "'hex'", ":", "# Convert invalid characters to hex. Note: \\p{l} designates all Unicode letter characters (any language),", "# \\p{m} designates all mark symbols (e.g., vowel marks in Indian scrips, such as the final)", "# and \\p{n} designates all numbers. We allow any of these to be present in the regex.", "s", "=", "''", ".", "join", "(", "[", "c", ".", "encode", "(", "\"hex\"", ")", "if", "re", ".", "findall", "(", "'[^\\p{l}\\p{m}\\p{n}_]'", ",", "c", ")", "else", "c", "for", "c", "in", "s", "]", ")", "elif", "convert", "==", "'drop'", ":", "# Remove invalid characters", "s", "=", "re", ".", "sub", "(", "'[^\\p{l}\\p{m}\\p{n}_]'", ",", "''", ",", "s", ")", "# Remove leading characters until we find a letter or underscore. Only letters can be leading characters.", "s", "=", "re", ".", "sub", "(", "'^[^\\p{l}_]+'", ",", "''", ",", "s", ")", "# Check that the string is not a python identifier", "while", "(", "s", "in", "keyword", ".", "kwlist", "or", "s", "in", "namespace", ".", "values", "(", ")", "or", "s", "in", "reserved_words", ")", ":", "if", "handle", "==", "'throw'", ":", "raise", "NameError", "(", "s", "+", "' already exists in namespace or is a reserved word'", ")", "if", "handle", "==", "'force'", ":", "if", "re", ".", "match", "(", "\".*?_\\d+$\"", ",", "s", ")", ":", "i", "=", "re", ".", "match", "(", "\".*?_(\\d+)$\"", ",", "s", ")", ".", "groups", "(", ")", "[", "0", "]", "s", "=", "s", ".", "strip", "(", "'_'", "+", "i", ")", "+", "'_'", "+", "str", "(", "int", "(", "i", ")", "+", "1", ")", "else", ":", "s", "+=", "'_1'", "namespace", "[", "string", "]", "=", "s", "return", "s", ",", "namespace" ]
Takes an arbitrary string and creates a valid Python identifier. If the input string is in the namespace, return its value. If the python identifier created is already in the namespace, but the input string is not (ie, two similar strings resolve to the same python identifier) or if the identifier is a reserved word in the reserved_words list, or is a python default reserved word, adds _1, or if _1 is in the namespace, _2, etc. Parameters ---------- string : <basestring> The text to be converted into a valid python identifier namespace : <dictionary> Map of existing translations into python safe identifiers. This is to ensure that two strings are not translated into the same python identifier reserved_words : <list of strings> List of words that are reserved (because they have other meanings in this particular program, such as also being the names of libraries, etc. convert : <string> Tells the function what to do with characters that are not valid in python identifiers - 'hex' implies that they will be converted to their hexidecimal representation. This is handy if you have variables that have a lot of reserved characters, or you don't want the name to be dependent on when things were added to the namespace - 'drop' implies that they will just be dropped altogether handle : <string> Tells the function how to deal with namespace conflicts - 'force' will create a representation which is not in conflict by appending _n to the resulting variable where n is the lowest number necessary to avoid a conflict - 'throw' will raise an exception Returns ------- identifier : <string> A vaild python identifier based on the input string namespace : <dictionary> An updated map of the translations of words to python identifiers, including the passed in 'string'. Examples -------- >>> make_python_identifier('Capital') ('capital', {'Capital': 'capital'}) >>> make_python_identifier('multiple words') ('multiple_words', {'multiple words': 'multiple_words'}) >>> make_python_identifier('multiple spaces') ('multiple_spaces', {'multiple spaces': 'multiple_spaces'}) When the name is a python keyword, add '_1' to differentiate it >>> make_python_identifier('for') ('for_1', {'for': 'for_1'}) Remove leading and trailing whitespace >>> make_python_identifier(' whitespace ') ('whitespace', {' whitespace ': 'whitespace'}) Remove most special characters outright: >>> make_python_identifier('H@t tr!ck') ('ht_trck', {'H@t tr!ck': 'ht_trck'}) Replace special characters with their hex representations >>> make_python_identifier('H@t tr!ck', convert='hex') ('h40t_tr21ck', {'H@t tr!ck': 'h40t_tr21ck'}) remove leading digits >>> make_python_identifier('123abc') ('abc', {'123abc': 'abc'}) already in namespace >>> make_python_identifier('Variable$', namespace={'Variable$': 'variable'}) ('variable', {'Variable$': 'variable'}) namespace conflicts >>> make_python_identifier('Variable$', namespace={'Variable@': 'variable'}) ('variable_1', {'Variable@': 'variable', 'Variable$': 'variable_1'}) >>> make_python_identifier('Variable$', namespace={'Variable@': 'variable', >>> 'Variable%': 'variable_1'}) ('variable_2', {'Variable@': 'variable', 'Variable%': 'variable_1', 'Variable$': 'variable_2'}) throw exception instead >>> make_python_identifier('Variable$', namespace={'Variable@': 'variable'}, handle='throw') Traceback (most recent call last): ... NameError: variable already exists in namespace or is a reserved word References ---------- Identifiers must follow the convention outlined here: https://docs.python.org/2/reference/lexical_analysis.html#identifiers
[ "Takes", "an", "arbitrary", "string", "and", "creates", "a", "valid", "Python", "identifier", "." ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L138-L291
15,128
JamesPHoughton/pysd
pysd/py_backend/utils.py
make_flat_df
def make_flat_df(frames, return_addresses): """ Takes a list of dictionaries, each representing what is returned from the model at a particular time, and creates a dataframe whose columns correspond to the keys of `return addresses` Parameters ---------- frames: list of dictionaries each dictionary represents the result of a prticular time in the model return_addresses: a dictionary, keys will be column names of the resulting dataframe, and are what the user passed in as 'return_columns'. Values are a tuple: (py_name, {coords dictionary}) which tells us where to look for the value to put in that specific column. Returns ------- """ # Todo: could also try a list comprehension here, or parallel apply visited = list(map(lambda x: visit_addresses(x, return_addresses), frames)) return pd.DataFrame(visited)
python
def make_flat_df(frames, return_addresses): """ Takes a list of dictionaries, each representing what is returned from the model at a particular time, and creates a dataframe whose columns correspond to the keys of `return addresses` Parameters ---------- frames: list of dictionaries each dictionary represents the result of a prticular time in the model return_addresses: a dictionary, keys will be column names of the resulting dataframe, and are what the user passed in as 'return_columns'. Values are a tuple: (py_name, {coords dictionary}) which tells us where to look for the value to put in that specific column. Returns ------- """ # Todo: could also try a list comprehension here, or parallel apply visited = list(map(lambda x: visit_addresses(x, return_addresses), frames)) return pd.DataFrame(visited)
[ "def", "make_flat_df", "(", "frames", ",", "return_addresses", ")", ":", "# Todo: could also try a list comprehension here, or parallel apply", "visited", "=", "list", "(", "map", "(", "lambda", "x", ":", "visit_addresses", "(", "x", ",", "return_addresses", ")", ",", "frames", ")", ")", "return", "pd", ".", "DataFrame", "(", "visited", ")" ]
Takes a list of dictionaries, each representing what is returned from the model at a particular time, and creates a dataframe whose columns correspond to the keys of `return addresses` Parameters ---------- frames: list of dictionaries each dictionary represents the result of a prticular time in the model return_addresses: a dictionary, keys will be column names of the resulting dataframe, and are what the user passed in as 'return_columns'. Values are a tuple: (py_name, {coords dictionary}) which tells us where to look for the value to put in that specific column. Returns -------
[ "Takes", "a", "list", "of", "dictionaries", "each", "representing", "what", "is", "returned", "from", "the", "model", "at", "a", "particular", "time", "and", "creates", "a", "dataframe", "whose", "columns", "correspond", "to", "the", "keys", "of", "return", "addresses" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L344-L367
15,129
JamesPHoughton/pysd
pysd/py_backend/utils.py
visit_addresses
def visit_addresses(frame, return_addresses): """ Visits all of the addresses, returns a new dict which contains just the addressed elements Parameters ---------- frame return_addresses: a dictionary, keys will be column names of the resulting dataframe, and are what the user passed in as 'return_columns'. Values are a tuple: (py_name, {coords dictionary}) which tells us where to look for the value to put in that specific column. Returns ------- outdict: dictionary """ outdict = dict() for real_name, (pyname, address) in return_addresses.items(): if address: xrval = frame[pyname].loc[address] if xrval.size > 1: outdict[real_name] = xrval else: outdict[real_name] = float(np.squeeze(xrval.values)) else: outdict[real_name] = frame[pyname] return outdict
python
def visit_addresses(frame, return_addresses): """ Visits all of the addresses, returns a new dict which contains just the addressed elements Parameters ---------- frame return_addresses: a dictionary, keys will be column names of the resulting dataframe, and are what the user passed in as 'return_columns'. Values are a tuple: (py_name, {coords dictionary}) which tells us where to look for the value to put in that specific column. Returns ------- outdict: dictionary """ outdict = dict() for real_name, (pyname, address) in return_addresses.items(): if address: xrval = frame[pyname].loc[address] if xrval.size > 1: outdict[real_name] = xrval else: outdict[real_name] = float(np.squeeze(xrval.values)) else: outdict[real_name] = frame[pyname] return outdict
[ "def", "visit_addresses", "(", "frame", ",", "return_addresses", ")", ":", "outdict", "=", "dict", "(", ")", "for", "real_name", ",", "(", "pyname", ",", "address", ")", "in", "return_addresses", ".", "items", "(", ")", ":", "if", "address", ":", "xrval", "=", "frame", "[", "pyname", "]", ".", "loc", "[", "address", "]", "if", "xrval", ".", "size", ">", "1", ":", "outdict", "[", "real_name", "]", "=", "xrval", "else", ":", "outdict", "[", "real_name", "]", "=", "float", "(", "np", ".", "squeeze", "(", "xrval", ".", "values", ")", ")", "else", ":", "outdict", "[", "real_name", "]", "=", "frame", "[", "pyname", "]", "return", "outdict" ]
Visits all of the addresses, returns a new dict which contains just the addressed elements Parameters ---------- frame return_addresses: a dictionary, keys will be column names of the resulting dataframe, and are what the user passed in as 'return_columns'. Values are a tuple: (py_name, {coords dictionary}) which tells us where to look for the value to put in that specific column. Returns ------- outdict: dictionary
[ "Visits", "all", "of", "the", "addresses", "returns", "a", "new", "dict", "which", "contains", "just", "the", "addressed", "elements" ]
bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda
https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L370-L401
15,130
hirokiky/django-basicauth
basicauth/basicauthutils.py
validate_request
def validate_request(request): """Check an incoming request. Returns: - True if authentication passed - Adding request['REMOTE_USER'] as authenticated username. """ if getattr(settings, 'BASICAUTH_DISABLE', False): # Not to use this env return True if 'HTTP_AUTHORIZATION' not in request.META: return False authorization_header = request.META['HTTP_AUTHORIZATION'] ret = extract_basicauth(authorization_header) if not ret: return False username, password = ret raw_pass = settings.BASICAUTH_USERS.get(username) if raw_pass is None: return False # To avoid timing atacks # https://security.stackexchange.com/questions/83660/simple-string-comparisons-not-secure-against-timing-attacks if not constant_time_compare(raw_pass, password): return False request.META['REMOTE_USER'] = username return True
python
def validate_request(request): """Check an incoming request. Returns: - True if authentication passed - Adding request['REMOTE_USER'] as authenticated username. """ if getattr(settings, 'BASICAUTH_DISABLE', False): # Not to use this env return True if 'HTTP_AUTHORIZATION' not in request.META: return False authorization_header = request.META['HTTP_AUTHORIZATION'] ret = extract_basicauth(authorization_header) if not ret: return False username, password = ret raw_pass = settings.BASICAUTH_USERS.get(username) if raw_pass is None: return False # To avoid timing atacks # https://security.stackexchange.com/questions/83660/simple-string-comparisons-not-secure-against-timing-attacks if not constant_time_compare(raw_pass, password): return False request.META['REMOTE_USER'] = username return True
[ "def", "validate_request", "(", "request", ")", ":", "if", "getattr", "(", "settings", ",", "'BASICAUTH_DISABLE'", ",", "False", ")", ":", "# Not to use this env", "return", "True", "if", "'HTTP_AUTHORIZATION'", "not", "in", "request", ".", "META", ":", "return", "False", "authorization_header", "=", "request", ".", "META", "[", "'HTTP_AUTHORIZATION'", "]", "ret", "=", "extract_basicauth", "(", "authorization_header", ")", "if", "not", "ret", ":", "return", "False", "username", ",", "password", "=", "ret", "raw_pass", "=", "settings", ".", "BASICAUTH_USERS", ".", "get", "(", "username", ")", "if", "raw_pass", "is", "None", ":", "return", "False", "# To avoid timing atacks", "# https://security.stackexchange.com/questions/83660/simple-string-comparisons-not-secure-against-timing-attacks", "if", "not", "constant_time_compare", "(", "raw_pass", ",", "password", ")", ":", "return", "False", "request", ".", "META", "[", "'REMOTE_USER'", "]", "=", "username", "return", "True" ]
Check an incoming request. Returns: - True if authentication passed - Adding request['REMOTE_USER'] as authenticated username.
[ "Check", "an", "incoming", "request", "." ]
dcc956ef1507f289bb50dce770e13c114ebd9a9b
https://github.com/hirokiky/django-basicauth/blob/dcc956ef1507f289bb50dce770e13c114ebd9a9b/basicauth/basicauthutils.py#L38-L69
15,131
google/ipaddr-py
ipaddr.py
_find_address_range
def _find_address_range(addresses): """Find a sequence of addresses. Args: addresses: a list of IPv4 or IPv6 addresses. Returns: A tuple containing the first and last IP addresses in the sequence, and the index of the last IP address in the sequence. """ first = last = addresses[0] last_index = 0 for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip last_index += 1 else: break return (first, last, last_index)
python
def _find_address_range(addresses): """Find a sequence of addresses. Args: addresses: a list of IPv4 or IPv6 addresses. Returns: A tuple containing the first and last IP addresses in the sequence, and the index of the last IP address in the sequence. """ first = last = addresses[0] last_index = 0 for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip last_index += 1 else: break return (first, last, last_index)
[ "def", "_find_address_range", "(", "addresses", ")", ":", "first", "=", "last", "=", "addresses", "[", "0", "]", "last_index", "=", "0", "for", "ip", "in", "addresses", "[", "1", ":", "]", ":", "if", "ip", ".", "_ip", "==", "last", ".", "_ip", "+", "1", ":", "last", "=", "ip", "last_index", "+=", "1", "else", ":", "break", "return", "(", "first", ",", "last", ",", "last_index", ")" ]
Find a sequence of addresses. Args: addresses: a list of IPv4 or IPv6 addresses. Returns: A tuple containing the first and last IP addresses in the sequence, and the index of the last IP address in the sequence.
[ "Find", "a", "sequence", "of", "addresses", "." ]
99e55513666db1276596d74f24863e056ca50851
https://github.com/google/ipaddr-py/blob/99e55513666db1276596d74f24863e056ca50851/ipaddr.py#L157-L176
15,132
google/ipaddr-py
ipaddr.py
_BaseNet._prefix_from_prefix_int
def _prefix_from_prefix_int(self, prefixlen): """Validate and return a prefix length integer. Args: prefixlen: An integer containing the prefix length. Returns: The input, possibly converted from long to int. Raises: NetmaskValueError: If the input is not an integer, or out of range. """ if not isinstance(prefixlen, (int, long)): raise NetmaskValueError('%r is not an integer' % prefixlen) prefixlen = int(prefixlen) if not (0 <= prefixlen <= self._max_prefixlen): raise NetmaskValueError('%d is not a valid prefix length' % prefixlen) return prefixlen
python
def _prefix_from_prefix_int(self, prefixlen): """Validate and return a prefix length integer. Args: prefixlen: An integer containing the prefix length. Returns: The input, possibly converted from long to int. Raises: NetmaskValueError: If the input is not an integer, or out of range. """ if not isinstance(prefixlen, (int, long)): raise NetmaskValueError('%r is not an integer' % prefixlen) prefixlen = int(prefixlen) if not (0 <= prefixlen <= self._max_prefixlen): raise NetmaskValueError('%d is not a valid prefix length' % prefixlen) return prefixlen
[ "def", "_prefix_from_prefix_int", "(", "self", ",", "prefixlen", ")", ":", "if", "not", "isinstance", "(", "prefixlen", ",", "(", "int", ",", "long", ")", ")", ":", "raise", "NetmaskValueError", "(", "'%r is not an integer'", "%", "prefixlen", ")", "prefixlen", "=", "int", "(", "prefixlen", ")", "if", "not", "(", "0", "<=", "prefixlen", "<=", "self", ".", "_max_prefixlen", ")", ":", "raise", "NetmaskValueError", "(", "'%d is not a valid prefix length'", "%", "prefixlen", ")", "return", "prefixlen" ]
Validate and return a prefix length integer. Args: prefixlen: An integer containing the prefix length. Returns: The input, possibly converted from long to int. Raises: NetmaskValueError: If the input is not an integer, or out of range.
[ "Validate", "and", "return", "a", "prefix", "length", "integer", "." ]
99e55513666db1276596d74f24863e056ca50851
https://github.com/google/ipaddr-py/blob/99e55513666db1276596d74f24863e056ca50851/ipaddr.py#L887-L905
15,133
raimon49/pip-licenses
piplicenses.py
output_colored
def output_colored(code, text, is_bold=False): """ Create function to output with color sequence """ if is_bold: code = '1;%s' % code return '\033[%sm%s\033[0m' % (code, text)
python
def output_colored(code, text, is_bold=False): """ Create function to output with color sequence """ if is_bold: code = '1;%s' % code return '\033[%sm%s\033[0m' % (code, text)
[ "def", "output_colored", "(", "code", ",", "text", ",", "is_bold", "=", "False", ")", ":", "if", "is_bold", ":", "code", "=", "'1;%s'", "%", "code", "return", "'\\033[%sm%s\\033[0m'", "%", "(", "code", ",", "text", ")" ]
Create function to output with color sequence
[ "Create", "function", "to", "output", "with", "color", "sequence" ]
879eddd9d75228ba7d6529bd3050d11ae6bf1712
https://github.com/raimon49/pip-licenses/blob/879eddd9d75228ba7d6529bd3050d11ae6bf1712/piplicenses.py#L504-L511
15,134
nickjj/flask-webpack
flask_webpack/__init__.py
Webpack._set_asset_paths
def _set_asset_paths(self, app): """ Read in the manifest json file which acts as a manifest for assets. This allows us to get the asset path as well as hashed names. :param app: Flask application :return: None """ webpack_stats = app.config['WEBPACK_MANIFEST_PATH'] try: with app.open_resource(webpack_stats, 'r') as stats_json: stats = json.load(stats_json) if app.config['WEBPACK_ASSETS_URL']: self.assets_url = app.config['WEBPACK_ASSETS_URL'] else: self.assets_url = stats['publicPath'] self.assets = stats['assets'] except IOError: raise RuntimeError( "Flask-Webpack requires 'WEBPACK_MANIFEST_PATH' to be set and " "it must point to a valid json file.")
python
def _set_asset_paths(self, app): """ Read in the manifest json file which acts as a manifest for assets. This allows us to get the asset path as well as hashed names. :param app: Flask application :return: None """ webpack_stats = app.config['WEBPACK_MANIFEST_PATH'] try: with app.open_resource(webpack_stats, 'r') as stats_json: stats = json.load(stats_json) if app.config['WEBPACK_ASSETS_URL']: self.assets_url = app.config['WEBPACK_ASSETS_URL'] else: self.assets_url = stats['publicPath'] self.assets = stats['assets'] except IOError: raise RuntimeError( "Flask-Webpack requires 'WEBPACK_MANIFEST_PATH' to be set and " "it must point to a valid json file.")
[ "def", "_set_asset_paths", "(", "self", ",", "app", ")", ":", "webpack_stats", "=", "app", ".", "config", "[", "'WEBPACK_MANIFEST_PATH'", "]", "try", ":", "with", "app", ".", "open_resource", "(", "webpack_stats", ",", "'r'", ")", "as", "stats_json", ":", "stats", "=", "json", ".", "load", "(", "stats_json", ")", "if", "app", ".", "config", "[", "'WEBPACK_ASSETS_URL'", "]", ":", "self", ".", "assets_url", "=", "app", ".", "config", "[", "'WEBPACK_ASSETS_URL'", "]", "else", ":", "self", ".", "assets_url", "=", "stats", "[", "'publicPath'", "]", "self", ".", "assets", "=", "stats", "[", "'assets'", "]", "except", "IOError", ":", "raise", "RuntimeError", "(", "\"Flask-Webpack requires 'WEBPACK_MANIFEST_PATH' to be set and \"", "\"it must point to a valid json file.\"", ")" ]
Read in the manifest json file which acts as a manifest for assets. This allows us to get the asset path as well as hashed names. :param app: Flask application :return: None
[ "Read", "in", "the", "manifest", "json", "file", "which", "acts", "as", "a", "manifest", "for", "assets", ".", "This", "allows", "us", "to", "get", "the", "asset", "path", "as", "well", "as", "hashed", "names", "." ]
241617c6ce0fd9ec11f507204958ddd0ec467634
https://github.com/nickjj/flask-webpack/blob/241617c6ce0fd9ec11f507204958ddd0ec467634/flask_webpack/__init__.py#L47-L70
15,135
nickjj/flask-webpack
flask_webpack/__init__.py
Webpack.javascript_tag
def javascript_tag(self, *args): """ Convenience tag to output 1 or more javascript tags. :param args: 1 or more javascript file names :return: Script tag(s) containing the asset """ tags = [] for arg in args: asset_path = self.asset_url_for('{0}.js'.format(arg)) if asset_path: tags.append('<script src="{0}"></script>'.format(asset_path)) return '\n'.join(tags)
python
def javascript_tag(self, *args): """ Convenience tag to output 1 or more javascript tags. :param args: 1 or more javascript file names :return: Script tag(s) containing the asset """ tags = [] for arg in args: asset_path = self.asset_url_for('{0}.js'.format(arg)) if asset_path: tags.append('<script src="{0}"></script>'.format(asset_path)) return '\n'.join(tags)
[ "def", "javascript_tag", "(", "self", ",", "*", "args", ")", ":", "tags", "=", "[", "]", "for", "arg", "in", "args", ":", "asset_path", "=", "self", ".", "asset_url_for", "(", "'{0}.js'", ".", "format", "(", "arg", ")", ")", "if", "asset_path", ":", "tags", ".", "append", "(", "'<script src=\"{0}\"></script>'", ".", "format", "(", "asset_path", ")", ")", "return", "'\\n'", ".", "join", "(", "tags", ")" ]
Convenience tag to output 1 or more javascript tags. :param args: 1 or more javascript file names :return: Script tag(s) containing the asset
[ "Convenience", "tag", "to", "output", "1", "or", "more", "javascript", "tags", "." ]
241617c6ce0fd9ec11f507204958ddd0ec467634
https://github.com/nickjj/flask-webpack/blob/241617c6ce0fd9ec11f507204958ddd0ec467634/flask_webpack/__init__.py#L81-L95
15,136
nickjj/flask-webpack
flask_webpack/__init__.py
Webpack.asset_url_for
def asset_url_for(self, asset): """ Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not found """ if '//' in asset: return asset if asset not in self.assets: return None return '{0}{1}'.format(self.assets_url, self.assets[asset])
python
def asset_url_for(self, asset): """ Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not found """ if '//' in asset: return asset if asset not in self.assets: return None return '{0}{1}'.format(self.assets_url, self.assets[asset])
[ "def", "asset_url_for", "(", "self", ",", "asset", ")", ":", "if", "'//'", "in", "asset", ":", "return", "asset", "if", "asset", "not", "in", "self", ".", "assets", ":", "return", "None", "return", "'{0}{1}'", ".", "format", "(", "self", ".", "assets_url", ",", "self", ".", "assets", "[", "asset", "]", ")" ]
Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not found
[ "Lookup", "the", "hashed", "asset", "path", "of", "a", "file", "name", "unless", "it", "starts", "with", "something", "that", "resembles", "a", "web", "address", "then", "take", "it", "as", "is", "." ]
241617c6ce0fd9ec11f507204958ddd0ec467634
https://github.com/nickjj/flask-webpack/blob/241617c6ce0fd9ec11f507204958ddd0ec467634/flask_webpack/__init__.py#L114-L129
15,137
hishnash/djangochannelsrestframework
djangochannelsrestframework/observer/observer.py
ModelObserver.pre_change_receiver
def pre_change_receiver(self, instance: Model, action: Action): """ Entry point for triggering the old_binding from save signals. """ if action == Action.CREATE: group_names = set() else: group_names = set(self.group_names(instance)) # use a thread local dict to be safe... if not hasattr(instance, '__instance_groups'): instance.__instance_groups = threading.local() instance.__instance_groups.observers = {} if not hasattr(instance.__instance_groups, 'observers'): instance.__instance_groups.observers = {} instance.__instance_groups.observers[self] = group_names
python
def pre_change_receiver(self, instance: Model, action: Action): """ Entry point for triggering the old_binding from save signals. """ if action == Action.CREATE: group_names = set() else: group_names = set(self.group_names(instance)) # use a thread local dict to be safe... if not hasattr(instance, '__instance_groups'): instance.__instance_groups = threading.local() instance.__instance_groups.observers = {} if not hasattr(instance.__instance_groups, 'observers'): instance.__instance_groups.observers = {} instance.__instance_groups.observers[self] = group_names
[ "def", "pre_change_receiver", "(", "self", ",", "instance", ":", "Model", ",", "action", ":", "Action", ")", ":", "if", "action", "==", "Action", ".", "CREATE", ":", "group_names", "=", "set", "(", ")", "else", ":", "group_names", "=", "set", "(", "self", ".", "group_names", "(", "instance", ")", ")", "# use a thread local dict to be safe...", "if", "not", "hasattr", "(", "instance", ",", "'__instance_groups'", ")", ":", "instance", ".", "__instance_groups", "=", "threading", ".", "local", "(", ")", "instance", ".", "__instance_groups", ".", "observers", "=", "{", "}", "if", "not", "hasattr", "(", "instance", ".", "__instance_groups", ",", "'observers'", ")", ":", "instance", ".", "__instance_groups", ".", "observers", "=", "{", "}", "instance", ".", "__instance_groups", ".", "observers", "[", "self", "]", "=", "group_names" ]
Entry point for triggering the old_binding from save signals.
[ "Entry", "point", "for", "triggering", "the", "old_binding", "from", "save", "signals", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/observer/observer.py#L171-L187
15,138
hishnash/djangochannelsrestframework
djangochannelsrestframework/observer/observer.py
ModelObserver.post_change_receiver
def post_change_receiver(self, instance: Model, action: Action, **kwargs): """ Triggers the old_binding to possibly send to its group. """ try: old_group_names = instance.__instance_groups.observers[self] except (ValueError, KeyError): old_group_names = set() if action == Action.DELETE: new_group_names = set() else: new_group_names = set(self.group_names(instance)) # if post delete, new_group_names should be [] # Django DDP had used the ordering of DELETE, UPDATE then CREATE for good reasons. self.send_messages( instance, old_group_names - new_group_names, Action.DELETE, **kwargs ) # the object has been updated so that its groups are not the same. self.send_messages( instance, old_group_names & new_group_names, Action.UPDATE, **kwargs ) # self.send_messages( instance, new_group_names - old_group_names, Action.CREATE, **kwargs )
python
def post_change_receiver(self, instance: Model, action: Action, **kwargs): """ Triggers the old_binding to possibly send to its group. """ try: old_group_names = instance.__instance_groups.observers[self] except (ValueError, KeyError): old_group_names = set() if action == Action.DELETE: new_group_names = set() else: new_group_names = set(self.group_names(instance)) # if post delete, new_group_names should be [] # Django DDP had used the ordering of DELETE, UPDATE then CREATE for good reasons. self.send_messages( instance, old_group_names - new_group_names, Action.DELETE, **kwargs ) # the object has been updated so that its groups are not the same. self.send_messages( instance, old_group_names & new_group_names, Action.UPDATE, **kwargs ) # self.send_messages( instance, new_group_names - old_group_names, Action.CREATE, **kwargs )
[ "def", "post_change_receiver", "(", "self", ",", "instance", ":", "Model", ",", "action", ":", "Action", ",", "*", "*", "kwargs", ")", ":", "try", ":", "old_group_names", "=", "instance", ".", "__instance_groups", ".", "observers", "[", "self", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "old_group_names", "=", "set", "(", ")", "if", "action", "==", "Action", ".", "DELETE", ":", "new_group_names", "=", "set", "(", ")", "else", ":", "new_group_names", "=", "set", "(", "self", ".", "group_names", "(", "instance", ")", ")", "# if post delete, new_group_names should be []", "# Django DDP had used the ordering of DELETE, UPDATE then CREATE for good reasons.", "self", ".", "send_messages", "(", "instance", ",", "old_group_names", "-", "new_group_names", ",", "Action", ".", "DELETE", ",", "*", "*", "kwargs", ")", "# the object has been updated so that its groups are not the same.", "self", ".", "send_messages", "(", "instance", ",", "old_group_names", "&", "new_group_names", ",", "Action", ".", "UPDATE", ",", "*", "*", "kwargs", ")", "#", "self", ".", "send_messages", "(", "instance", ",", "new_group_names", "-", "old_group_names", ",", "Action", ".", "CREATE", ",", "*", "*", "kwargs", ")" ]
Triggers the old_binding to possibly send to its group.
[ "Triggers", "the", "old_binding", "to", "possibly", "send", "to", "its", "group", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/observer/observer.py#L189-L226
15,139
hishnash/djangochannelsrestframework
djangochannelsrestframework/generics.py
GenericAsyncAPIConsumer.get_queryset
def get_queryset(self, **kwargs) -> QuerySet: """ Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. You may want to override this if you need to provide different querysets depending on the incoming request. (Eg. return a list of items that is specific to the user) """ assert self.queryset is not None, ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self.__class__.__name__ ) queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset
python
def get_queryset(self, **kwargs) -> QuerySet: """ Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. You may want to override this if you need to provide different querysets depending on the incoming request. (Eg. return a list of items that is specific to the user) """ assert self.queryset is not None, ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self.__class__.__name__ ) queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset
[ "def", "get_queryset", "(", "self", ",", "*", "*", "kwargs", ")", "->", "QuerySet", ":", "assert", "self", ".", "queryset", "is", "not", "None", ",", "(", "\"'%s' should either include a `queryset` attribute, \"", "\"or override the `get_queryset()` method.\"", "%", "self", ".", "__class__", ".", "__name__", ")", "queryset", "=", "self", ".", "queryset", "if", "isinstance", "(", "queryset", ",", "QuerySet", ")", ":", "# Ensure queryset is re-evaluated on each request.", "queryset", "=", "queryset", ".", "all", "(", ")", "return", "queryset" ]
Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. You may want to override this if you need to provide different querysets depending on the incoming request. (Eg. return a list of items that is specific to the user)
[ "Get", "the", "list", "of", "items", "for", "this", "view", ".", "This", "must", "be", "an", "iterable", "and", "may", "be", "a", "queryset", ".", "Defaults", "to", "using", "self", ".", "queryset", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/generics.py#L34-L59
15,140
hishnash/djangochannelsrestframework
djangochannelsrestframework/generics.py
GenericAsyncAPIConsumer.get_serializer_class
def get_serializer_class(self, **kwargs) -> Type[Serializer]: """ Return the class to use for the serializer. Defaults to using `self.serializer_class`. You may want to override this if you need to provide different serializations depending on the incoming request. (Eg. admins get full serialization, others get basic serialization) """ assert self.serializer_class is not None, ( "'%s' should either include a `serializer_class` attribute, " "or override the `get_serializer_class()` method." % self.__class__.__name__ ) return self.serializer_class
python
def get_serializer_class(self, **kwargs) -> Type[Serializer]: """ Return the class to use for the serializer. Defaults to using `self.serializer_class`. You may want to override this if you need to provide different serializations depending on the incoming request. (Eg. admins get full serialization, others get basic serialization) """ assert self.serializer_class is not None, ( "'%s' should either include a `serializer_class` attribute, " "or override the `get_serializer_class()` method." % self.__class__.__name__ ) return self.serializer_class
[ "def", "get_serializer_class", "(", "self", ",", "*", "*", "kwargs", ")", "->", "Type", "[", "Serializer", "]", ":", "assert", "self", ".", "serializer_class", "is", "not", "None", ",", "(", "\"'%s' should either include a `serializer_class` attribute, \"", "\"or override the `get_serializer_class()` method.\"", "%", "self", ".", "__class__", ".", "__name__", ")", "return", "self", ".", "serializer_class" ]
Return the class to use for the serializer. Defaults to using `self.serializer_class`. You may want to override this if you need to provide different serializations depending on the incoming request. (Eg. admins get full serialization, others get basic serialization)
[ "Return", "the", "class", "to", "use", "for", "the", "serializer", ".", "Defaults", "to", "using", "self", ".", "serializer_class", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/generics.py#L109-L125
15,141
hishnash/djangochannelsrestframework
djangochannelsrestframework/consumers.py
view_as_consumer
def view_as_consumer( wrapped_view: typing.Callable[[HttpRequest], HttpResponse], mapped_actions: typing.Optional[ typing.Dict[str, str] ]=None) -> Type[AsyncConsumer]: """ Wrap a django View so that it will be triggered by actions over this json websocket consumer. """ if mapped_actions is None: mapped_actions = { 'create': 'PUT', 'update': 'PATCH', 'list': 'GET', 'retrieve': 'GET' } class DjangoViewWrapper(DjangoViewAsConsumer): view = wrapped_view actions = mapped_actions return DjangoViewWrapper
python
def view_as_consumer( wrapped_view: typing.Callable[[HttpRequest], HttpResponse], mapped_actions: typing.Optional[ typing.Dict[str, str] ]=None) -> Type[AsyncConsumer]: """ Wrap a django View so that it will be triggered by actions over this json websocket consumer. """ if mapped_actions is None: mapped_actions = { 'create': 'PUT', 'update': 'PATCH', 'list': 'GET', 'retrieve': 'GET' } class DjangoViewWrapper(DjangoViewAsConsumer): view = wrapped_view actions = mapped_actions return DjangoViewWrapper
[ "def", "view_as_consumer", "(", "wrapped_view", ":", "typing", ".", "Callable", "[", "[", "HttpRequest", "]", ",", "HttpResponse", "]", ",", "mapped_actions", ":", "typing", ".", "Optional", "[", "typing", ".", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ")", "->", "Type", "[", "AsyncConsumer", "]", ":", "if", "mapped_actions", "is", "None", ":", "mapped_actions", "=", "{", "'create'", ":", "'PUT'", ",", "'update'", ":", "'PATCH'", ",", "'list'", ":", "'GET'", ",", "'retrieve'", ":", "'GET'", "}", "class", "DjangoViewWrapper", "(", "DjangoViewAsConsumer", ")", ":", "view", "=", "wrapped_view", "actions", "=", "mapped_actions", "return", "DjangoViewWrapper" ]
Wrap a django View so that it will be triggered by actions over this json websocket consumer.
[ "Wrap", "a", "django", "View", "so", "that", "it", "will", "be", "triggered", "by", "actions", "over", "this", "json", "websocket", "consumer", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L303-L324
15,142
hishnash/djangochannelsrestframework
djangochannelsrestframework/consumers.py
AsyncAPIConsumer.check_permissions
async def check_permissions(self, action: str, **kwargs): """ Check if the action should be permitted. Raises an appropriate exception if the request is not permitted. """ for permission in await self.get_permissions(action=action, **kwargs): if not await ensure_async(permission.has_permission)( scope=self.scope, consumer=self, action=action, **kwargs): raise PermissionDenied()
python
async def check_permissions(self, action: str, **kwargs): """ Check if the action should be permitted. Raises an appropriate exception if the request is not permitted. """ for permission in await self.get_permissions(action=action, **kwargs): if not await ensure_async(permission.has_permission)( scope=self.scope, consumer=self, action=action, **kwargs): raise PermissionDenied()
[ "async", "def", "check_permissions", "(", "self", ",", "action", ":", "str", ",", "*", "*", "kwargs", ")", ":", "for", "permission", "in", "await", "self", ".", "get_permissions", "(", "action", "=", "action", ",", "*", "*", "kwargs", ")", ":", "if", "not", "await", "ensure_async", "(", "permission", ".", "has_permission", ")", "(", "scope", "=", "self", ".", "scope", ",", "consumer", "=", "self", ",", "action", "=", "action", ",", "*", "*", "kwargs", ")", ":", "raise", "PermissionDenied", "(", ")" ]
Check if the action should be permitted. Raises an appropriate exception if the request is not permitted.
[ "Check", "if", "the", "action", "should", "be", "permitted", ".", "Raises", "an", "appropriate", "exception", "if", "the", "request", "is", "not", "permitted", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L93-L102
15,143
hishnash/djangochannelsrestframework
djangochannelsrestframework/consumers.py
AsyncAPIConsumer.handle_exception
async def handle_exception(self, exc: Exception, action: str, request_id): """ Handle any exception that occurs, by sending an appropriate message """ if isinstance(exc, APIException): await self.reply( action=action, errors=self._format_errors(exc.detail), status=exc.status_code, request_id=request_id ) elif exc == Http404 or isinstance(exc, Http404): await self.reply( action=action, errors=self._format_errors('Not found'), status=404, request_id=request_id ) else: raise exc
python
async def handle_exception(self, exc: Exception, action: str, request_id): """ Handle any exception that occurs, by sending an appropriate message """ if isinstance(exc, APIException): await self.reply( action=action, errors=self._format_errors(exc.detail), status=exc.status_code, request_id=request_id ) elif exc == Http404 or isinstance(exc, Http404): await self.reply( action=action, errors=self._format_errors('Not found'), status=404, request_id=request_id ) else: raise exc
[ "async", "def", "handle_exception", "(", "self", ",", "exc", ":", "Exception", ",", "action", ":", "str", ",", "request_id", ")", ":", "if", "isinstance", "(", "exc", ",", "APIException", ")", ":", "await", "self", ".", "reply", "(", "action", "=", "action", ",", "errors", "=", "self", ".", "_format_errors", "(", "exc", ".", "detail", ")", ",", "status", "=", "exc", ".", "status_code", ",", "request_id", "=", "request_id", ")", "elif", "exc", "==", "Http404", "or", "isinstance", "(", "exc", ",", "Http404", ")", ":", "await", "self", ".", "reply", "(", "action", "=", "action", ",", "errors", "=", "self", ".", "_format_errors", "(", "'Not found'", ")", ",", "status", "=", "404", ",", "request_id", "=", "request_id", ")", "else", ":", "raise", "exc" ]
Handle any exception that occurs, by sending an appropriate message
[ "Handle", "any", "exception", "that", "occurs", "by", "sending", "an", "appropriate", "message" ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L104-L123
15,144
hishnash/djangochannelsrestframework
djangochannelsrestframework/consumers.py
AsyncAPIConsumer.receive_json
async def receive_json(self, content: typing.Dict, **kwargs): """ Called with decoded JSON content. """ # TODO assert format, if does not match return message. request_id = content.pop('request_id') action = content.pop('action') await self.handle_action(action, request_id=request_id, **content)
python
async def receive_json(self, content: typing.Dict, **kwargs): """ Called with decoded JSON content. """ # TODO assert format, if does not match return message. request_id = content.pop('request_id') action = content.pop('action') await self.handle_action(action, request_id=request_id, **content)
[ "async", "def", "receive_json", "(", "self", ",", "content", ":", "typing", ".", "Dict", ",", "*", "*", "kwargs", ")", ":", "# TODO assert format, if does not match return message.", "request_id", "=", "content", ".", "pop", "(", "'request_id'", ")", "action", "=", "content", ".", "pop", "(", "'action'", ")", "await", "self", ".", "handle_action", "(", "action", ",", "request_id", "=", "request_id", ",", "*", "*", "content", ")" ]
Called with decoded JSON content.
[ "Called", "with", "decoded", "JSON", "content", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L170-L177
15,145
hishnash/djangochannelsrestframework
djangochannelsrestframework/decorators.py
action
def action(atomic=None, **kwargs): """ Mark a method as an action. """ def decorator(func): if atomic is None: _atomic = getattr(settings, 'ATOMIC_REQUESTS', False) else: _atomic = atomic func.action = True func.kwargs = kwargs if asyncio.iscoroutinefunction(func): if _atomic: raise ValueError('Only synchronous actions can be atomic') return func if _atomic: # wrap function in atomic wrapper func = transaction.atomic(func) @wraps(func) async def async_f(self: AsyncAPIConsumer, *args, **_kwargs): result, status = await database_sync_to_async(func)( self, *args, **_kwargs ) return result, status async_f.action = True async_f.kwargs = kwargs async_f.__name__ = func.__name__ return async_f return decorator
python
def action(atomic=None, **kwargs): """ Mark a method as an action. """ def decorator(func): if atomic is None: _atomic = getattr(settings, 'ATOMIC_REQUESTS', False) else: _atomic = atomic func.action = True func.kwargs = kwargs if asyncio.iscoroutinefunction(func): if _atomic: raise ValueError('Only synchronous actions can be atomic') return func if _atomic: # wrap function in atomic wrapper func = transaction.atomic(func) @wraps(func) async def async_f(self: AsyncAPIConsumer, *args, **_kwargs): result, status = await database_sync_to_async(func)( self, *args, **_kwargs ) return result, status async_f.action = True async_f.kwargs = kwargs async_f.__name__ = func.__name__ return async_f return decorator
[ "def", "action", "(", "atomic", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "if", "atomic", "is", "None", ":", "_atomic", "=", "getattr", "(", "settings", ",", "'ATOMIC_REQUESTS'", ",", "False", ")", "else", ":", "_atomic", "=", "atomic", "func", ".", "action", "=", "True", "func", ".", "kwargs", "=", "kwargs", "if", "asyncio", ".", "iscoroutinefunction", "(", "func", ")", ":", "if", "_atomic", ":", "raise", "ValueError", "(", "'Only synchronous actions can be atomic'", ")", "return", "func", "if", "_atomic", ":", "# wrap function in atomic wrapper", "func", "=", "transaction", ".", "atomic", "(", "func", ")", "@", "wraps", "(", "func", ")", "async", "def", "async_f", "(", "self", ":", "AsyncAPIConsumer", ",", "*", "args", ",", "*", "*", "_kwargs", ")", ":", "result", ",", "status", "=", "await", "database_sync_to_async", "(", "func", ")", "(", "self", ",", "*", "args", ",", "*", "*", "_kwargs", ")", "return", "result", ",", "status", "async_f", ".", "action", "=", "True", "async_f", ".", "kwargs", "=", "kwargs", "async_f", ".", "__name__", "=", "func", ".", "__name__", "return", "async_f", "return", "decorator" ]
Mark a method as an action.
[ "Mark", "a", "method", "as", "an", "action", "." ]
19fdec7efd785b1a94d19612a8de934e1948e344
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/decorators.py#L35-L72
15,146
blue-yonder/bonfire
bonfire/dateutils.py
datetime_parser
def datetime_parser(s): """ Parse timestamp s in local time. First the arrow parser is used, if it fails, the parsedatetime parser is used. :param s: :return: """ try: ts = arrow.get(s) # Convert UTC to local, result of get is UTC unless it specifies timezone, bonfire assumes # all time to be machine local if ts.tzinfo == arrow.get().tzinfo: ts = ts.replace(tzinfo='local') except: c = pdt.Calendar() result, what = c.parse(s) ts = None if what in (1, 2, 3): ts = datetime.datetime(*result[:6]) ts = arrow.get(ts) ts = ts.replace(tzinfo='local') return ts if ts is None: raise ValueError("Cannot parse timestamp '" + s + "'") return ts
python
def datetime_parser(s): """ Parse timestamp s in local time. First the arrow parser is used, if it fails, the parsedatetime parser is used. :param s: :return: """ try: ts = arrow.get(s) # Convert UTC to local, result of get is UTC unless it specifies timezone, bonfire assumes # all time to be machine local if ts.tzinfo == arrow.get().tzinfo: ts = ts.replace(tzinfo='local') except: c = pdt.Calendar() result, what = c.parse(s) ts = None if what in (1, 2, 3): ts = datetime.datetime(*result[:6]) ts = arrow.get(ts) ts = ts.replace(tzinfo='local') return ts if ts is None: raise ValueError("Cannot parse timestamp '" + s + "'") return ts
[ "def", "datetime_parser", "(", "s", ")", ":", "try", ":", "ts", "=", "arrow", ".", "get", "(", "s", ")", "# Convert UTC to local, result of get is UTC unless it specifies timezone, bonfire assumes", "# all time to be machine local", "if", "ts", ".", "tzinfo", "==", "arrow", ".", "get", "(", ")", ".", "tzinfo", ":", "ts", "=", "ts", ".", "replace", "(", "tzinfo", "=", "'local'", ")", "except", ":", "c", "=", "pdt", ".", "Calendar", "(", ")", "result", ",", "what", "=", "c", ".", "parse", "(", "s", ")", "ts", "=", "None", "if", "what", "in", "(", "1", ",", "2", ",", "3", ")", ":", "ts", "=", "datetime", ".", "datetime", "(", "*", "result", "[", ":", "6", "]", ")", "ts", "=", "arrow", ".", "get", "(", "ts", ")", "ts", "=", "ts", ".", "replace", "(", "tzinfo", "=", "'local'", ")", "return", "ts", "if", "ts", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot parse timestamp '\"", "+", "s", "+", "\"'\"", ")", "return", "ts" ]
Parse timestamp s in local time. First the arrow parser is used, if it fails, the parsedatetime parser is used. :param s: :return:
[ "Parse", "timestamp", "s", "in", "local", "time", ".", "First", "the", "arrow", "parser", "is", "used", "if", "it", "fails", "the", "parsedatetime", "parser", "is", "used", "." ]
d0af9ca10394f366cfa3c60f0741f1f0918011c2
https://github.com/blue-yonder/bonfire/blob/d0af9ca10394f366cfa3c60f0741f1f0918011c2/bonfire/dateutils.py#L14-L42
15,147
kyb3r/dhooks
dhooks/file.py
File.seek
def seek(self, offset: int = 0, *args, **kwargs): """ A shortcut to ``self.fp.seek``. """ return self.fp.seek(offset, *args, **kwargs)
python
def seek(self, offset: int = 0, *args, **kwargs): """ A shortcut to ``self.fp.seek``. """ return self.fp.seek(offset, *args, **kwargs)
[ "def", "seek", "(", "self", ",", "offset", ":", "int", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "fp", ".", "seek", "(", "offset", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
A shortcut to ``self.fp.seek``.
[ "A", "shortcut", "to", "self", ".", "fp", ".", "seek", "." ]
2cde52b26cc94dcbf538ebcc4e17dfc3714d2827
https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/file.py#L32-L38
15,148
kyb3r/dhooks
dhooks/embed.py
Embed.set_title
def set_title(self, title: str, url: str = None) -> None: """ Sets the title of the embed. Parameters ---------- title: str Title of the embed. url: str or None, optional URL hyperlink of the title. """ self.title = title self.url = url
python
def set_title(self, title: str, url: str = None) -> None: """ Sets the title of the embed. Parameters ---------- title: str Title of the embed. url: str or None, optional URL hyperlink of the title. """ self.title = title self.url = url
[ "def", "set_title", "(", "self", ",", "title", ":", "str", ",", "url", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "title", "=", "title", "self", ".", "url", "=", "url" ]
Sets the title of the embed. Parameters ---------- title: str Title of the embed. url: str or None, optional URL hyperlink of the title.
[ "Sets", "the", "title", "of", "the", "embed", "." ]
2cde52b26cc94dcbf538ebcc4e17dfc3714d2827
https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L82-L96
15,149
kyb3r/dhooks
dhooks/embed.py
Embed.set_timestamp
def set_timestamp(self, time: Union[str, datetime.datetime] = None, now: bool = False) -> None: """ Sets the timestamp of the embed. Parameters ---------- time: str or :class:`datetime.datetime` The ``ISO 8601`` timestamp from the embed. now: bool Defaults to :class:`False`. If set to :class:`True` the current time is used for the timestamp. """ if now: self.timestamp = str(datetime.datetime.utcnow()) else: self.timestamp = str(time)
python
def set_timestamp(self, time: Union[str, datetime.datetime] = None, now: bool = False) -> None: """ Sets the timestamp of the embed. Parameters ---------- time: str or :class:`datetime.datetime` The ``ISO 8601`` timestamp from the embed. now: bool Defaults to :class:`False`. If set to :class:`True` the current time is used for the timestamp. """ if now: self.timestamp = str(datetime.datetime.utcnow()) else: self.timestamp = str(time)
[ "def", "set_timestamp", "(", "self", ",", "time", ":", "Union", "[", "str", ",", "datetime", ".", "datetime", "]", "=", "None", ",", "now", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "now", ":", "self", ".", "timestamp", "=", "str", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ")", "else", ":", "self", ".", "timestamp", "=", "str", "(", "time", ")" ]
Sets the timestamp of the embed. Parameters ---------- time: str or :class:`datetime.datetime` The ``ISO 8601`` timestamp from the embed. now: bool Defaults to :class:`False`. If set to :class:`True` the current time is used for the timestamp.
[ "Sets", "the", "timestamp", "of", "the", "embed", "." ]
2cde52b26cc94dcbf538ebcc4e17dfc3714d2827
https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L98-L116
15,150
kyb3r/dhooks
dhooks/embed.py
Embed.add_field
def add_field(self, name: str, value: str, inline: bool = True) -> None: """ Adds an embed field. Parameters ---------- name: str Name attribute of the embed field. value: str Value attribute of the embed field. inline: bool Defaults to :class:`True`. Whether or not the embed should be inline. """ field = { 'name': name, 'value': value, 'inline': inline } self.fields.append(field)
python
def add_field(self, name: str, value: str, inline: bool = True) -> None: """ Adds an embed field. Parameters ---------- name: str Name attribute of the embed field. value: str Value attribute of the embed field. inline: bool Defaults to :class:`True`. Whether or not the embed should be inline. """ field = { 'name': name, 'value': value, 'inline': inline } self.fields.append(field)
[ "def", "add_field", "(", "self", ",", "name", ":", "str", ",", "value", ":", "str", ",", "inline", ":", "bool", "=", "True", ")", "->", "None", ":", "field", "=", "{", "'name'", ":", "name", ",", "'value'", ":", "value", ",", "'inline'", ":", "inline", "}", "self", ".", "fields", ".", "append", "(", "field", ")" ]
Adds an embed field. Parameters ---------- name: str Name attribute of the embed field. value: str Value attribute of the embed field. inline: bool Defaults to :class:`True`. Whether or not the embed should be inline.
[ "Adds", "an", "embed", "field", "." ]
2cde52b26cc94dcbf538ebcc4e17dfc3714d2827
https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L118-L140
15,151
kyb3r/dhooks
dhooks/embed.py
Embed.set_author
def set_author(self, name: str, icon_url: str = None, url: str = None) -> \ None: """ Sets the author of the embed. Parameters ---------- name: str The author's name. icon_url: str, optional URL for the author's icon. url: str, optional URL hyperlink for the author. """ self.author = { 'name': name, 'icon_url': icon_url, 'url': url }
python
def set_author(self, name: str, icon_url: str = None, url: str = None) -> \ None: """ Sets the author of the embed. Parameters ---------- name: str The author's name. icon_url: str, optional URL for the author's icon. url: str, optional URL hyperlink for the author. """ self.author = { 'name': name, 'icon_url': icon_url, 'url': url }
[ "def", "set_author", "(", "self", ",", "name", ":", "str", ",", "icon_url", ":", "str", "=", "None", ",", "url", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "author", "=", "{", "'name'", ":", "name", ",", "'icon_url'", ":", "icon_url", ",", "'url'", ":", "url", "}" ]
Sets the author of the embed. Parameters ---------- name: str The author's name. icon_url: str, optional URL for the author's icon. url: str, optional URL hyperlink for the author.
[ "Sets", "the", "author", "of", "the", "embed", "." ]
2cde52b26cc94dcbf538ebcc4e17dfc3714d2827
https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L142-L163
15,152
kyb3r/dhooks
dhooks/embed.py
Embed.set_footer
def set_footer(self, text: str, icon_url: str = None) -> None: """ Sets the footer of the embed. Parameters ---------- text: str The footer text. icon_url: str, optional URL for the icon in the footer. """ self.footer = { 'text': text, 'icon_url': icon_url }
python
def set_footer(self, text: str, icon_url: str = None) -> None: """ Sets the footer of the embed. Parameters ---------- text: str The footer text. icon_url: str, optional URL for the icon in the footer. """ self.footer = { 'text': text, 'icon_url': icon_url }
[ "def", "set_footer", "(", "self", ",", "text", ":", "str", ",", "icon_url", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "footer", "=", "{", "'text'", ":", "text", ",", "'icon_url'", ":", "icon_url", "}" ]
Sets the footer of the embed. Parameters ---------- text: str The footer text. icon_url: str, optional URL for the icon in the footer.
[ "Sets", "the", "footer", "of", "the", "embed", "." ]
2cde52b26cc94dcbf538ebcc4e17dfc3714d2827
https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L189-L205
15,153
kyb3r/dhooks
examples/async.py
init
async def init(app, loop): """Sends a message to the webhook channel when server starts.""" app.session = aiohttp.ClientSession(loop=loop) # to make web requests app.webhook = Webhook.Async(webhook_url, session=app.session) em = Embed(color=0x2ecc71) em.set_author('[INFO] Starting Worker') em.description = 'Host: {}'.format(socket.gethostname()) await app.webhook.send(embed=em)
python
async def init(app, loop): """Sends a message to the webhook channel when server starts.""" app.session = aiohttp.ClientSession(loop=loop) # to make web requests app.webhook = Webhook.Async(webhook_url, session=app.session) em = Embed(color=0x2ecc71) em.set_author('[INFO] Starting Worker') em.description = 'Host: {}'.format(socket.gethostname()) await app.webhook.send(embed=em)
[ "async", "def", "init", "(", "app", ",", "loop", ")", ":", "app", ".", "session", "=", "aiohttp", ".", "ClientSession", "(", "loop", "=", "loop", ")", "# to make web requests", "app", ".", "webhook", "=", "Webhook", ".", "Async", "(", "webhook_url", ",", "session", "=", "app", ".", "session", ")", "em", "=", "Embed", "(", "color", "=", "0x2ecc71", ")", "em", ".", "set_author", "(", "'[INFO] Starting Worker'", ")", "em", ".", "description", "=", "'Host: {}'", ".", "format", "(", "socket", ".", "gethostname", "(", ")", ")", "await", "app", ".", "webhook", ".", "send", "(", "embed", "=", "em", ")" ]
Sends a message to the webhook channel when server starts.
[ "Sends", "a", "message", "to", "the", "webhook", "channel", "when", "server", "starts", "." ]
2cde52b26cc94dcbf538ebcc4e17dfc3714d2827
https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/examples/async.py#L17-L26
15,154
kyb3r/dhooks
examples/async.py
server_stop
async def server_stop(app, loop): """Sends a message to the webhook channel when server stops.""" em = Embed(color=0xe67e22) em.set_footer('Host: {}'.format(socket.gethostname())) em.description = '[INFO] Server Stopped' await app.webhook.send(embed=em) await app.session.close()
python
async def server_stop(app, loop): """Sends a message to the webhook channel when server stops.""" em = Embed(color=0xe67e22) em.set_footer('Host: {}'.format(socket.gethostname())) em.description = '[INFO] Server Stopped' await app.webhook.send(embed=em) await app.session.close()
[ "async", "def", "server_stop", "(", "app", ",", "loop", ")", ":", "em", "=", "Embed", "(", "color", "=", "0xe67e22", ")", "em", ".", "set_footer", "(", "'Host: {}'", ".", "format", "(", "socket", ".", "gethostname", "(", ")", ")", ")", "em", ".", "description", "=", "'[INFO] Server Stopped'", "await", "app", ".", "webhook", ".", "send", "(", "embed", "=", "em", ")", "await", "app", ".", "session", ".", "close", "(", ")" ]
Sends a message to the webhook channel when server stops.
[ "Sends", "a", "message", "to", "the", "webhook", "channel", "when", "server", "stops", "." ]
2cde52b26cc94dcbf538ebcc4e17dfc3714d2827
https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/examples/async.py#L30-L37
15,155
tantale/deprecated
deprecated/classic.py
ClassicAdapter.get_deprecated_msg
def get_deprecated_msg(self, wrapped, instance): """ Get the deprecation warning message for the user. :param wrapped: Wrapped class or function. :param instance: The object to which the wrapped function was bound when it was called. :return: The warning message. """ if instance is None: if inspect.isclass(wrapped): fmt = "Call to deprecated class {name}." else: fmt = "Call to deprecated function (or staticmethod) {name}." else: if inspect.isclass(instance): fmt = "Call to deprecated class method {name}." else: fmt = "Call to deprecated method {name}." if self.reason: fmt += " ({reason})" if self.version: fmt += " -- Deprecated since version {version}." return fmt.format(name=wrapped.__name__, reason=self.reason or "", version=self.version or "")
python
def get_deprecated_msg(self, wrapped, instance): """ Get the deprecation warning message for the user. :param wrapped: Wrapped class or function. :param instance: The object to which the wrapped function was bound when it was called. :return: The warning message. """ if instance is None: if inspect.isclass(wrapped): fmt = "Call to deprecated class {name}." else: fmt = "Call to deprecated function (or staticmethod) {name}." else: if inspect.isclass(instance): fmt = "Call to deprecated class method {name}." else: fmt = "Call to deprecated method {name}." if self.reason: fmt += " ({reason})" if self.version: fmt += " -- Deprecated since version {version}." return fmt.format(name=wrapped.__name__, reason=self.reason or "", version=self.version or "")
[ "def", "get_deprecated_msg", "(", "self", ",", "wrapped", ",", "instance", ")", ":", "if", "instance", "is", "None", ":", "if", "inspect", ".", "isclass", "(", "wrapped", ")", ":", "fmt", "=", "\"Call to deprecated class {name}.\"", "else", ":", "fmt", "=", "\"Call to deprecated function (or staticmethod) {name}.\"", "else", ":", "if", "inspect", ".", "isclass", "(", "instance", ")", ":", "fmt", "=", "\"Call to deprecated class method {name}.\"", "else", ":", "fmt", "=", "\"Call to deprecated method {name}.\"", "if", "self", ".", "reason", ":", "fmt", "+=", "\" ({reason})\"", "if", "self", ".", "version", ":", "fmt", "+=", "\" -- Deprecated since version {version}.\"", "return", "fmt", ".", "format", "(", "name", "=", "wrapped", ".", "__name__", ",", "reason", "=", "self", ".", "reason", "or", "\"\"", ",", "version", "=", "self", ".", "version", "or", "\"\"", ")" ]
Get the deprecation warning message for the user. :param wrapped: Wrapped class or function. :param instance: The object to which the wrapped function was bound when it was called. :return: The warning message.
[ "Get", "the", "deprecation", "warning", "message", "for", "the", "user", "." ]
3dc742c571de7cebbbdaaf4c554f2f36fc61b3db
https://github.com/tantale/deprecated/blob/3dc742c571de7cebbbdaaf4c554f2f36fc61b3db/deprecated/classic.py#L101-L127
15,156
izdi/django-slack-oauth
django_slack_oauth/pipelines.py
slack_user
def slack_user(request, api_data): """ Pipeline for backward compatibility prior to 1.0.0 version. In case if you're willing maintain `slack_user` table. """ if request.user.is_anonymous: return request, api_data data = deepcopy(api_data) slacker, _ = SlackUser.objects.get_or_create(slacker=request.user) slacker.access_token = data.pop('access_token') slacker.extras = data slacker.save() messages.add_message(request, messages.SUCCESS, 'Your account has been successfully updated with ' 'Slack. You can share your messages within your slack ' 'domain.') return request, api_data
python
def slack_user(request, api_data): """ Pipeline for backward compatibility prior to 1.0.0 version. In case if you're willing maintain `slack_user` table. """ if request.user.is_anonymous: return request, api_data data = deepcopy(api_data) slacker, _ = SlackUser.objects.get_or_create(slacker=request.user) slacker.access_token = data.pop('access_token') slacker.extras = data slacker.save() messages.add_message(request, messages.SUCCESS, 'Your account has been successfully updated with ' 'Slack. You can share your messages within your slack ' 'domain.') return request, api_data
[ "def", "slack_user", "(", "request", ",", "api_data", ")", ":", "if", "request", ".", "user", ".", "is_anonymous", ":", "return", "request", ",", "api_data", "data", "=", "deepcopy", "(", "api_data", ")", "slacker", ",", "_", "=", "SlackUser", ".", "objects", ".", "get_or_create", "(", "slacker", "=", "request", ".", "user", ")", "slacker", ".", "access_token", "=", "data", ".", "pop", "(", "'access_token'", ")", "slacker", ".", "extras", "=", "data", "slacker", ".", "save", "(", ")", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "SUCCESS", ",", "'Your account has been successfully updated with '", "'Slack. You can share your messages within your slack '", "'domain.'", ")", "return", "request", ",", "api_data" ]
Pipeline for backward compatibility prior to 1.0.0 version. In case if you're willing maintain `slack_user` table.
[ "Pipeline", "for", "backward", "compatibility", "prior", "to", "1", ".", "0", ".", "0", "version", ".", "In", "case", "if", "you", "re", "willing", "maintain", "slack_user", "table", "." ]
46e10f7c64407a018b9585f257224fc38888fbcb
https://github.com/izdi/django-slack-oauth/blob/46e10f7c64407a018b9585f257224fc38888fbcb/django_slack_oauth/pipelines.py#L26-L46
15,157
matplotlib/cmocean
cmocean/data.py
read
def read(varin, fname='MS2_L10.mat.txt'): '''Read in dataset for variable var :param varin: Variable for which to read in data. ''' # # fname = 'MS09_L10.mat.txt' # # fname = 'MS09_L05.mat.txt' # has PAR # fname = 'MS2_L10.mat.txt' # empty PAR d = np.loadtxt(fname, comments='*') if fname == 'MS2_L10.mat.txt': var = ['lat', 'lon', 'depth', 'temp', 'density', 'sigma', 'oxygen', 'voltage 2', 'voltage 3', 'fluorescence-CDOM', 'fluorescence-ECO', 'turbidity', 'pressure', 'salinity', 'RINKO temperature', 'RINKO DO - CTD temp', 'RINKO DO - RINKO temp', 'bottom', 'PAR'] elif (fname == 'MS09_L05.mat.txt') or (fname == 'MS09_L10.mat.txt') or (fname == 'MS08_L12.mat.txt'): var = ['lat', 'lon', 'depth', 'temp', 'density', 'sigma', 'oxygen', 'voltage 2', 'voltage 3', 'voltage 4', 'fluorescence-CDOM', 'fluorescence-ECO', 'turbidity', 'pressure', 'salinity', 'RINKO temperature', 'RINKO DO - CTD temp', 'RINKO DO - RINKO temp', 'bottom', 'PAR'] # return data for variable varin return d[:, 0], d[:, 1], d[:, 2], d[:, var.index(varin)]
python
def read(varin, fname='MS2_L10.mat.txt'): '''Read in dataset for variable var :param varin: Variable for which to read in data. ''' # # fname = 'MS09_L10.mat.txt' # # fname = 'MS09_L05.mat.txt' # has PAR # fname = 'MS2_L10.mat.txt' # empty PAR d = np.loadtxt(fname, comments='*') if fname == 'MS2_L10.mat.txt': var = ['lat', 'lon', 'depth', 'temp', 'density', 'sigma', 'oxygen', 'voltage 2', 'voltage 3', 'fluorescence-CDOM', 'fluorescence-ECO', 'turbidity', 'pressure', 'salinity', 'RINKO temperature', 'RINKO DO - CTD temp', 'RINKO DO - RINKO temp', 'bottom', 'PAR'] elif (fname == 'MS09_L05.mat.txt') or (fname == 'MS09_L10.mat.txt') or (fname == 'MS08_L12.mat.txt'): var = ['lat', 'lon', 'depth', 'temp', 'density', 'sigma', 'oxygen', 'voltage 2', 'voltage 3', 'voltage 4', 'fluorescence-CDOM', 'fluorescence-ECO', 'turbidity', 'pressure', 'salinity', 'RINKO temperature', 'RINKO DO - CTD temp', 'RINKO DO - RINKO temp', 'bottom', 'PAR'] # return data for variable varin return d[:, 0], d[:, 1], d[:, 2], d[:, var.index(varin)]
[ "def", "read", "(", "varin", ",", "fname", "=", "'MS2_L10.mat.txt'", ")", ":", "# # fname = 'MS09_L10.mat.txt'", "# # fname = 'MS09_L05.mat.txt' # has PAR", "# fname = 'MS2_L10.mat.txt' # empty PAR", "d", "=", "np", ".", "loadtxt", "(", "fname", ",", "comments", "=", "'*'", ")", "if", "fname", "==", "'MS2_L10.mat.txt'", ":", "var", "=", "[", "'lat'", ",", "'lon'", ",", "'depth'", ",", "'temp'", ",", "'density'", ",", "'sigma'", ",", "'oxygen'", ",", "'voltage 2'", ",", "'voltage 3'", ",", "'fluorescence-CDOM'", ",", "'fluorescence-ECO'", ",", "'turbidity'", ",", "'pressure'", ",", "'salinity'", ",", "'RINKO temperature'", ",", "'RINKO DO - CTD temp'", ",", "'RINKO DO - RINKO temp'", ",", "'bottom'", ",", "'PAR'", "]", "elif", "(", "fname", "==", "'MS09_L05.mat.txt'", ")", "or", "(", "fname", "==", "'MS09_L10.mat.txt'", ")", "or", "(", "fname", "==", "'MS08_L12.mat.txt'", ")", ":", "var", "=", "[", "'lat'", ",", "'lon'", ",", "'depth'", ",", "'temp'", ",", "'density'", ",", "'sigma'", ",", "'oxygen'", ",", "'voltage 2'", ",", "'voltage 3'", ",", "'voltage 4'", ",", "'fluorescence-CDOM'", ",", "'fluorescence-ECO'", ",", "'turbidity'", ",", "'pressure'", ",", "'salinity'", ",", "'RINKO temperature'", ",", "'RINKO DO - CTD temp'", ",", "'RINKO DO - RINKO temp'", ",", "'bottom'", ",", "'PAR'", "]", "# return data for variable varin", "return", "d", "[", ":", ",", "0", "]", ",", "d", "[", ":", ",", "1", "]", ",", "d", "[", ":", ",", "2", "]", ",", "d", "[", ":", ",", "var", ".", "index", "(", "varin", ")", "]" ]
Read in dataset for variable var :param varin: Variable for which to read in data.
[ "Read", "in", "dataset", "for", "variable", "var" ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/data.py#L15-L40
15,158
matplotlib/cmocean
cmocean/data.py
show
def show(cmap, var, vmin=None, vmax=None): '''Show a colormap for a chosen input variable var side by side with black and white and jet colormaps. :param cmap: Colormap instance :param var: Variable to plot. :param vmin=None: Min plot value. :param vmax=None: Max plot value. ''' # get variable data lat, lon, z, data = read(var) fig = plt.figure(figsize=(16, 12)) # Plot with grayscale ax = fig.add_subplot(3, 1, 1) map1 = ax.scatter(lon, -z, c=data, cmap='gray', s=10, linewidths=0., vmin=vmin, vmax=vmax) plt.colorbar(map1, ax=ax) # Plot with jet ax = fig.add_subplot(3, 1, 2) map1 = ax.scatter(lon, -z, c=data, cmap='jet', s=10, linewidths=0., vmin=vmin, vmax=vmax) plt.colorbar(map1, ax=ax) # Plot with cmap ax = fig.add_subplot(3, 1, 3) map1 = ax.scatter(lon, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=vmin, vmax=vmax) ax.set_xlabel('Longitude [degrees]') ax.set_ylabel('Depth [m]') plt.colorbar(map1, ax=ax) plt.suptitle(var)
python
def show(cmap, var, vmin=None, vmax=None): '''Show a colormap for a chosen input variable var side by side with black and white and jet colormaps. :param cmap: Colormap instance :param var: Variable to plot. :param vmin=None: Min plot value. :param vmax=None: Max plot value. ''' # get variable data lat, lon, z, data = read(var) fig = plt.figure(figsize=(16, 12)) # Plot with grayscale ax = fig.add_subplot(3, 1, 1) map1 = ax.scatter(lon, -z, c=data, cmap='gray', s=10, linewidths=0., vmin=vmin, vmax=vmax) plt.colorbar(map1, ax=ax) # Plot with jet ax = fig.add_subplot(3, 1, 2) map1 = ax.scatter(lon, -z, c=data, cmap='jet', s=10, linewidths=0., vmin=vmin, vmax=vmax) plt.colorbar(map1, ax=ax) # Plot with cmap ax = fig.add_subplot(3, 1, 3) map1 = ax.scatter(lon, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=vmin, vmax=vmax) ax.set_xlabel('Longitude [degrees]') ax.set_ylabel('Depth [m]') plt.colorbar(map1, ax=ax) plt.suptitle(var)
[ "def", "show", "(", "cmap", ",", "var", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "# get variable data", "lat", ",", "lon", ",", "z", ",", "data", "=", "read", "(", "var", ")", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "16", ",", "12", ")", ")", "# Plot with grayscale", "ax", "=", "fig", ".", "add_subplot", "(", "3", ",", "1", ",", "1", ")", "map1", "=", "ax", ".", "scatter", "(", "lon", ",", "-", "z", ",", "c", "=", "data", ",", "cmap", "=", "'gray'", ",", "s", "=", "10", ",", "linewidths", "=", "0.", ",", "vmin", "=", "vmin", ",", "vmax", "=", "vmax", ")", "plt", ".", "colorbar", "(", "map1", ",", "ax", "=", "ax", ")", "# Plot with jet", "ax", "=", "fig", ".", "add_subplot", "(", "3", ",", "1", ",", "2", ")", "map1", "=", "ax", ".", "scatter", "(", "lon", ",", "-", "z", ",", "c", "=", "data", ",", "cmap", "=", "'jet'", ",", "s", "=", "10", ",", "linewidths", "=", "0.", ",", "vmin", "=", "vmin", ",", "vmax", "=", "vmax", ")", "plt", ".", "colorbar", "(", "map1", ",", "ax", "=", "ax", ")", "# Plot with cmap", "ax", "=", "fig", ".", "add_subplot", "(", "3", ",", "1", ",", "3", ")", "map1", "=", "ax", ".", "scatter", "(", "lon", ",", "-", "z", ",", "c", "=", "data", ",", "cmap", "=", "cmap", ",", "s", "=", "10", ",", "linewidths", "=", "0.", ",", "vmin", "=", "vmin", ",", "vmax", "=", "vmax", ")", "ax", ".", "set_xlabel", "(", "'Longitude [degrees]'", ")", "ax", ".", "set_ylabel", "(", "'Depth [m]'", ")", "plt", ".", "colorbar", "(", "map1", ",", "ax", "=", "ax", ")", "plt", ".", "suptitle", "(", "var", ")" ]
Show a colormap for a chosen input variable var side by side with black and white and jet colormaps. :param cmap: Colormap instance :param var: Variable to plot. :param vmin=None: Min plot value. :param vmax=None: Max plot value.
[ "Show", "a", "colormap", "for", "a", "chosen", "input", "variable", "var", "side", "by", "side", "with", "black", "and", "white", "and", "jet", "colormaps", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/data.py#L43-L76
15,159
matplotlib/cmocean
cmocean/data.py
plot_data
def plot_data(): '''Plot sample data up with the fancy colormaps. ''' var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM'] # colorbar limits for each property lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2], [0, 9]]) # reasonable values # lims = np.array([[20,36], [26,33], [1.5,5.6], [0,4], [0,9], [0,1.5]]) # values to show colormaps for fname in fnames: fig, axes = plt.subplots(nrows=4, ncols=2) fig.set_size_inches(20, 10) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.0, hspace=0.07) i = 0 for ax, Var, cmap in zip(axes.flat, var, cmaps): # loop through data to plot up # get variable data lat, lon, z, data = test.read(Var, fname) map1 = ax.scatter(lat, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=lims[i, 0], vmax=lims[i, 1]) # no stupid offset y_formatter = mpl.ticker.ScalarFormatter(useOffset=False) ax.xaxis.set_major_formatter(y_formatter) if i == 6: ax.set_xlabel('Latitude [degrees]') ax.set_ylabel('Depth [m]') else: ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_ylim(-z.max(), 0) ax.set_xlim(lat.min(), lat.max()) cb = plt.colorbar(map1, ax=ax, pad=0.02) cb.set_label(cmap.name + ' [' + '$' + cmap.units + '$]') i += 1 fig.savefig('figures/' + fname.split('.')[0] + '.png', bbox_inches='tight')
python
def plot_data(): '''Plot sample data up with the fancy colormaps. ''' var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM'] # colorbar limits for each property lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2], [0, 9]]) # reasonable values # lims = np.array([[20,36], [26,33], [1.5,5.6], [0,4], [0,9], [0,1.5]]) # values to show colormaps for fname in fnames: fig, axes = plt.subplots(nrows=4, ncols=2) fig.set_size_inches(20, 10) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.0, hspace=0.07) i = 0 for ax, Var, cmap in zip(axes.flat, var, cmaps): # loop through data to plot up # get variable data lat, lon, z, data = test.read(Var, fname) map1 = ax.scatter(lat, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=lims[i, 0], vmax=lims[i, 1]) # no stupid offset y_formatter = mpl.ticker.ScalarFormatter(useOffset=False) ax.xaxis.set_major_formatter(y_formatter) if i == 6: ax.set_xlabel('Latitude [degrees]') ax.set_ylabel('Depth [m]') else: ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_ylim(-z.max(), 0) ax.set_xlim(lat.min(), lat.max()) cb = plt.colorbar(map1, ax=ax, pad=0.02) cb.set_label(cmap.name + ' [' + '$' + cmap.units + '$]') i += 1 fig.savefig('figures/' + fname.split('.')[0] + '.png', bbox_inches='tight')
[ "def", "plot_data", "(", ")", ":", "var", "=", "[", "'temp'", ",", "'oxygen'", ",", "'salinity'", ",", "'fluorescence-ECO'", ",", "'density'", ",", "'PAR'", ",", "'turbidity'", ",", "'fluorescence-CDOM'", "]", "# colorbar limits for each property", "lims", "=", "np", ".", "array", "(", "[", "[", "26", ",", "33", "]", ",", "[", "0", ",", "10", "]", ",", "[", "0", ",", "36", "]", ",", "[", "0", ",", "6", "]", ",", "[", "1005", ",", "1025", "]", ",", "[", "0", ",", "0.6", "]", ",", "[", "0", ",", "2", "]", ",", "[", "0", ",", "9", "]", "]", ")", "# reasonable values", "# lims = np.array([[20,36], [26,33], [1.5,5.6], [0,4], [0,9], [0,1.5]]) # values to show colormaps", "for", "fname", "in", "fnames", ":", "fig", ",", "axes", "=", "plt", ".", "subplots", "(", "nrows", "=", "4", ",", "ncols", "=", "2", ")", "fig", ".", "set_size_inches", "(", "20", ",", "10", ")", "fig", ".", "subplots_adjust", "(", "top", "=", "0.95", ",", "bottom", "=", "0.01", ",", "left", "=", "0.2", ",", "right", "=", "0.99", ",", "wspace", "=", "0.0", ",", "hspace", "=", "0.07", ")", "i", "=", "0", "for", "ax", ",", "Var", ",", "cmap", "in", "zip", "(", "axes", ".", "flat", ",", "var", ",", "cmaps", ")", ":", "# loop through data to plot up", "# get variable data", "lat", ",", "lon", ",", "z", ",", "data", "=", "test", ".", "read", "(", "Var", ",", "fname", ")", "map1", "=", "ax", ".", "scatter", "(", "lat", ",", "-", "z", ",", "c", "=", "data", ",", "cmap", "=", "cmap", ",", "s", "=", "10", ",", "linewidths", "=", "0.", ",", "vmin", "=", "lims", "[", "i", ",", "0", "]", ",", "vmax", "=", "lims", "[", "i", ",", "1", "]", ")", "# no stupid offset", "y_formatter", "=", "mpl", ".", "ticker", ".", "ScalarFormatter", "(", "useOffset", "=", "False", ")", "ax", ".", "xaxis", ".", "set_major_formatter", "(", "y_formatter", ")", "if", "i", "==", "6", ":", "ax", ".", "set_xlabel", "(", "'Latitude [degrees]'", ")", "ax", ".", "set_ylabel", "(", "'Depth [m]'", ")", "else", ":", "ax", ".", "set_xticklabels", "(", "[", "]", ")", "ax", ".", "set_yticklabels", "(", "[", "]", ")", "ax", ".", "set_ylim", "(", "-", "z", ".", "max", "(", ")", ",", "0", ")", "ax", ".", "set_xlim", "(", "lat", ".", "min", "(", ")", ",", "lat", ".", "max", "(", ")", ")", "cb", "=", "plt", ".", "colorbar", "(", "map1", ",", "ax", "=", "ax", ",", "pad", "=", "0.02", ")", "cb", ".", "set_label", "(", "cmap", ".", "name", "+", "' ['", "+", "'$'", "+", "cmap", ".", "units", "+", "'$]'", ")", "i", "+=", "1", "fig", ".", "savefig", "(", "'figures/'", "+", "fname", ".", "split", "(", "'.'", ")", "[", "0", "]", "+", "'.png'", ",", "bbox_inches", "=", "'tight'", ")" ]
Plot sample data up with the fancy colormaps.
[ "Plot", "sample", "data", "up", "with", "the", "fancy", "colormaps", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/data.py#L79-L115
15,160
matplotlib/cmocean
cmocean/plots.py
plot_lightness
def plot_lightness(saveplot=False): '''Plot lightness of colormaps together. ''' from colorspacious import cspace_converter dc = 1. x = np.linspace(0.0, 1.0, 256) locs = [] # locations for text labels fig = plt.figure(figsize=(16, 5)) ax = fig.add_subplot(111) fig.subplots_adjust(left=0.03, right=0.97) ax.set_xlim(-0.1, len(cm.cmap_d)/2. + 0.1) ax.set_ylim(0, 100) ax.set_xlabel('Lightness for each colormap', fontsize=14) for j, cmapname in enumerate(cm.cmapnames): if '_r' in cmapname: # skip reversed versions for plot continue cmap = cm.cmap_d[cmapname] # get the colormap instance rgb = cmap(x)[np.newaxis, :, :3] lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb) L = lab[0, :, 0] if L[-1] > L[0]: ax.scatter(x+j*dc, L, c=x, cmap=cmap, s=200, linewidths=0.) else: ax.scatter(x+j*dc, L[::-1], c=x[::-1], cmap=cmap, s=200, linewidths=0.) locs.append(x[-1]+j*dc) # store locations for colormap labels # Set up labels for colormaps ax.xaxis.set_ticks_position('top') ticker = mpl.ticker.FixedLocator(locs) ax.xaxis.set_major_locator(ticker) formatter = mpl.ticker.FixedFormatter([cmapname for cmapname in cm.cmapnames]) ax.xaxis.set_major_formatter(formatter) labels = ax.get_xticklabels() for label in labels: label.set_rotation(60) if saveplot: fig.savefig('figures/lightness.png', bbox_inches='tight') fig.savefig('figures/lightness.pdf', bbox_inches='tight') plt.show()
python
def plot_lightness(saveplot=False): '''Plot lightness of colormaps together. ''' from colorspacious import cspace_converter dc = 1. x = np.linspace(0.0, 1.0, 256) locs = [] # locations for text labels fig = plt.figure(figsize=(16, 5)) ax = fig.add_subplot(111) fig.subplots_adjust(left=0.03, right=0.97) ax.set_xlim(-0.1, len(cm.cmap_d)/2. + 0.1) ax.set_ylim(0, 100) ax.set_xlabel('Lightness for each colormap', fontsize=14) for j, cmapname in enumerate(cm.cmapnames): if '_r' in cmapname: # skip reversed versions for plot continue cmap = cm.cmap_d[cmapname] # get the colormap instance rgb = cmap(x)[np.newaxis, :, :3] lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb) L = lab[0, :, 0] if L[-1] > L[0]: ax.scatter(x+j*dc, L, c=x, cmap=cmap, s=200, linewidths=0.) else: ax.scatter(x+j*dc, L[::-1], c=x[::-1], cmap=cmap, s=200, linewidths=0.) locs.append(x[-1]+j*dc) # store locations for colormap labels # Set up labels for colormaps ax.xaxis.set_ticks_position('top') ticker = mpl.ticker.FixedLocator(locs) ax.xaxis.set_major_locator(ticker) formatter = mpl.ticker.FixedFormatter([cmapname for cmapname in cm.cmapnames]) ax.xaxis.set_major_formatter(formatter) labels = ax.get_xticklabels() for label in labels: label.set_rotation(60) if saveplot: fig.savefig('figures/lightness.png', bbox_inches='tight') fig.savefig('figures/lightness.pdf', bbox_inches='tight') plt.show()
[ "def", "plot_lightness", "(", "saveplot", "=", "False", ")", ":", "from", "colorspacious", "import", "cspace_converter", "dc", "=", "1.", "x", "=", "np", ".", "linspace", "(", "0.0", ",", "1.0", ",", "256", ")", "locs", "=", "[", "]", "# locations for text labels", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "16", ",", "5", ")", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "fig", ".", "subplots_adjust", "(", "left", "=", "0.03", ",", "right", "=", "0.97", ")", "ax", ".", "set_xlim", "(", "-", "0.1", ",", "len", "(", "cm", ".", "cmap_d", ")", "/", "2.", "+", "0.1", ")", "ax", ".", "set_ylim", "(", "0", ",", "100", ")", "ax", ".", "set_xlabel", "(", "'Lightness for each colormap'", ",", "fontsize", "=", "14", ")", "for", "j", ",", "cmapname", "in", "enumerate", "(", "cm", ".", "cmapnames", ")", ":", "if", "'_r'", "in", "cmapname", ":", "# skip reversed versions for plot", "continue", "cmap", "=", "cm", ".", "cmap_d", "[", "cmapname", "]", "# get the colormap instance", "rgb", "=", "cmap", "(", "x", ")", "[", "np", ".", "newaxis", ",", ":", ",", ":", "3", "]", "lab", "=", "cspace_converter", "(", "\"sRGB1\"", ",", "\"CAM02-UCS\"", ")", "(", "rgb", ")", "L", "=", "lab", "[", "0", ",", ":", ",", "0", "]", "if", "L", "[", "-", "1", "]", ">", "L", "[", "0", "]", ":", "ax", ".", "scatter", "(", "x", "+", "j", "*", "dc", ",", "L", ",", "c", "=", "x", ",", "cmap", "=", "cmap", ",", "s", "=", "200", ",", "linewidths", "=", "0.", ")", "else", ":", "ax", ".", "scatter", "(", "x", "+", "j", "*", "dc", ",", "L", "[", ":", ":", "-", "1", "]", ",", "c", "=", "x", "[", ":", ":", "-", "1", "]", ",", "cmap", "=", "cmap", ",", "s", "=", "200", ",", "linewidths", "=", "0.", ")", "locs", ".", "append", "(", "x", "[", "-", "1", "]", "+", "j", "*", "dc", ")", "# store locations for colormap labels", "# Set up labels for colormaps", "ax", ".", "xaxis", ".", "set_ticks_position", "(", "'top'", ")", "ticker", "=", "mpl", ".", "ticker", ".", "FixedLocator", "(", "locs", ")", "ax", ".", "xaxis", ".", "set_major_locator", "(", "ticker", ")", "formatter", "=", "mpl", ".", "ticker", ".", "FixedFormatter", "(", "[", "cmapname", "for", "cmapname", "in", "cm", ".", "cmapnames", "]", ")", "ax", ".", "xaxis", ".", "set_major_formatter", "(", "formatter", ")", "labels", "=", "ax", ".", "get_xticklabels", "(", ")", "for", "label", "in", "labels", ":", "label", ".", "set_rotation", "(", "60", ")", "if", "saveplot", ":", "fig", ".", "savefig", "(", "'figures/lightness.png'", ",", "bbox_inches", "=", "'tight'", ")", "fig", ".", "savefig", "(", "'figures/lightness.pdf'", ",", "bbox_inches", "=", "'tight'", ")", "plt", ".", "show", "(", ")" ]
Plot lightness of colormaps together.
[ "Plot", "lightness", "of", "colormaps", "together", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/plots.py#L14-L61
15,161
matplotlib/cmocean
cmocean/plots.py
plot_gallery
def plot_gallery(saveplot=False): '''Make plot of colormaps and labels, like in the matplotlib gallery. :param saveplot=False: Whether to save the plot or not. ''' from colorspacious import cspace_converter gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) x = np.linspace(0.0, 1.0, 256) fig, axes = plt.subplots(nrows=int(len(cm.cmap_d)/2), ncols=1, figsize=(6, 12)) fig.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99, wspace=0.05) for ax, cmapname in zip(axes, cm.cmapnames): if '_r' in cmapname: # skip reversed versions for plot continue cmap = cm.cmap_d[cmapname] # get the colormap instance rgb = cmap(x)[np.newaxis, :, :3] # Find a good conversion to grayscale jch = cspace_converter("sRGB1", "CAM02-UCS")(rgb) # Not sure why to use JCh instead so using this. L = jch[0, :, 0] L = np.float32(np.vstack((L, L, L))) ax.imshow(gradient, aspect='auto', cmap=cmap) pos1 = ax.get_position() # get the original position pos2 = [pos1.x0, pos1.y0, pos1.width, pos1.height / 3.0] axbw = fig.add_axes(pos2) # colorbar axes axbw.set_axis_off() axbw.imshow(L, aspect='auto', cmap=cm.gray, vmin=0, vmax=100.) pos = list(ax.get_position().bounds) x_text = pos[0] - 0.01 y_text = pos[1] + pos[3]/2. fig.text(x_text, y_text, cmap.name, va='center', ha='right') # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axes: ax.set_axis_off() if saveplot: fig.savefig('figures/gallery.pdf', bbox_inches='tight') fig.savefig('figures/gallery.png', bbox_inches='tight') plt.show()
python
def plot_gallery(saveplot=False): '''Make plot of colormaps and labels, like in the matplotlib gallery. :param saveplot=False: Whether to save the plot or not. ''' from colorspacious import cspace_converter gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) x = np.linspace(0.0, 1.0, 256) fig, axes = plt.subplots(nrows=int(len(cm.cmap_d)/2), ncols=1, figsize=(6, 12)) fig.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99, wspace=0.05) for ax, cmapname in zip(axes, cm.cmapnames): if '_r' in cmapname: # skip reversed versions for plot continue cmap = cm.cmap_d[cmapname] # get the colormap instance rgb = cmap(x)[np.newaxis, :, :3] # Find a good conversion to grayscale jch = cspace_converter("sRGB1", "CAM02-UCS")(rgb) # Not sure why to use JCh instead so using this. L = jch[0, :, 0] L = np.float32(np.vstack((L, L, L))) ax.imshow(gradient, aspect='auto', cmap=cmap) pos1 = ax.get_position() # get the original position pos2 = [pos1.x0, pos1.y0, pos1.width, pos1.height / 3.0] axbw = fig.add_axes(pos2) # colorbar axes axbw.set_axis_off() axbw.imshow(L, aspect='auto', cmap=cm.gray, vmin=0, vmax=100.) pos = list(ax.get_position().bounds) x_text = pos[0] - 0.01 y_text = pos[1] + pos[3]/2. fig.text(x_text, y_text, cmap.name, va='center', ha='right') # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axes: ax.set_axis_off() if saveplot: fig.savefig('figures/gallery.pdf', bbox_inches='tight') fig.savefig('figures/gallery.png', bbox_inches='tight') plt.show()
[ "def", "plot_gallery", "(", "saveplot", "=", "False", ")", ":", "from", "colorspacious", "import", "cspace_converter", "gradient", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "256", ")", "gradient", "=", "np", ".", "vstack", "(", "(", "gradient", ",", "gradient", ")", ")", "x", "=", "np", ".", "linspace", "(", "0.0", ",", "1.0", ",", "256", ")", "fig", ",", "axes", "=", "plt", ".", "subplots", "(", "nrows", "=", "int", "(", "len", "(", "cm", ".", "cmap_d", ")", "/", "2", ")", ",", "ncols", "=", "1", ",", "figsize", "=", "(", "6", ",", "12", ")", ")", "fig", ".", "subplots_adjust", "(", "top", "=", "0.99", ",", "bottom", "=", "0.01", ",", "left", "=", "0.2", ",", "right", "=", "0.99", ",", "wspace", "=", "0.05", ")", "for", "ax", ",", "cmapname", "in", "zip", "(", "axes", ",", "cm", ".", "cmapnames", ")", ":", "if", "'_r'", "in", "cmapname", ":", "# skip reversed versions for plot", "continue", "cmap", "=", "cm", ".", "cmap_d", "[", "cmapname", "]", "# get the colormap instance", "rgb", "=", "cmap", "(", "x", ")", "[", "np", ".", "newaxis", ",", ":", ",", ":", "3", "]", "# Find a good conversion to grayscale", "jch", "=", "cspace_converter", "(", "\"sRGB1\"", ",", "\"CAM02-UCS\"", ")", "(", "rgb", ")", "# Not sure why to use JCh instead so using this.", "L", "=", "jch", "[", "0", ",", ":", ",", "0", "]", "L", "=", "np", ".", "float32", "(", "np", ".", "vstack", "(", "(", "L", ",", "L", ",", "L", ")", ")", ")", "ax", ".", "imshow", "(", "gradient", ",", "aspect", "=", "'auto'", ",", "cmap", "=", "cmap", ")", "pos1", "=", "ax", ".", "get_position", "(", ")", "# get the original position", "pos2", "=", "[", "pos1", ".", "x0", ",", "pos1", ".", "y0", ",", "pos1", ".", "width", ",", "pos1", ".", "height", "/", "3.0", "]", "axbw", "=", "fig", ".", "add_axes", "(", "pos2", ")", "# colorbar axes", "axbw", ".", "set_axis_off", "(", ")", "axbw", ".", "imshow", "(", "L", ",", "aspect", "=", "'auto'", ",", "cmap", "=", "cm", ".", "gray", ",", "vmin", "=", "0", ",", "vmax", "=", "100.", ")", "pos", "=", "list", "(", "ax", ".", "get_position", "(", ")", ".", "bounds", ")", "x_text", "=", "pos", "[", "0", "]", "-", "0.01", "y_text", "=", "pos", "[", "1", "]", "+", "pos", "[", "3", "]", "/", "2.", "fig", ".", "text", "(", "x_text", ",", "y_text", ",", "cmap", ".", "name", ",", "va", "=", "'center'", ",", "ha", "=", "'right'", ")", "# Turn off *all* ticks & spines, not just the ones with colormaps.", "for", "ax", "in", "axes", ":", "ax", ".", "set_axis_off", "(", ")", "if", "saveplot", ":", "fig", ".", "savefig", "(", "'figures/gallery.pdf'", ",", "bbox_inches", "=", "'tight'", ")", "fig", ".", "savefig", "(", "'figures/gallery.png'", ",", "bbox_inches", "=", "'tight'", ")", "plt", ".", "show", "(", ")" ]
Make plot of colormaps and labels, like in the matplotlib gallery. :param saveplot=False: Whether to save the plot or not.
[ "Make", "plot", "of", "colormaps", "and", "labels", "like", "in", "the", "matplotlib", "gallery", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/plots.py#L64-L115
15,162
matplotlib/cmocean
cmocean/plots.py
wrap_viscm
def wrap_viscm(cmap, dpi=100, saveplot=False): '''Evaluate goodness of colormap using perceptual deltas. :param cmap: Colormap instance. :param dpi=100: dpi for saved image. :param saveplot=False: Whether to save the plot or not. ''' from viscm import viscm viscm(cmap) fig = plt.gcf() fig.set_size_inches(22, 10) plt.show() if saveplot: fig.savefig('figures/eval_' + cmap.name + '.png', bbox_inches='tight', dpi=dpi) fig.savefig('figures/eval_' + cmap.name + '.pdf', bbox_inches='tight', dpi=dpi)
python
def wrap_viscm(cmap, dpi=100, saveplot=False): '''Evaluate goodness of colormap using perceptual deltas. :param cmap: Colormap instance. :param dpi=100: dpi for saved image. :param saveplot=False: Whether to save the plot or not. ''' from viscm import viscm viscm(cmap) fig = plt.gcf() fig.set_size_inches(22, 10) plt.show() if saveplot: fig.savefig('figures/eval_' + cmap.name + '.png', bbox_inches='tight', dpi=dpi) fig.savefig('figures/eval_' + cmap.name + '.pdf', bbox_inches='tight', dpi=dpi)
[ "def", "wrap_viscm", "(", "cmap", ",", "dpi", "=", "100", ",", "saveplot", "=", "False", ")", ":", "from", "viscm", "import", "viscm", "viscm", "(", "cmap", ")", "fig", "=", "plt", ".", "gcf", "(", ")", "fig", ".", "set_size_inches", "(", "22", ",", "10", ")", "plt", ".", "show", "(", ")", "if", "saveplot", ":", "fig", ".", "savefig", "(", "'figures/eval_'", "+", "cmap", ".", "name", "+", "'.png'", ",", "bbox_inches", "=", "'tight'", ",", "dpi", "=", "dpi", ")", "fig", ".", "savefig", "(", "'figures/eval_'", "+", "cmap", ".", "name", "+", "'.pdf'", ",", "bbox_inches", "=", "'tight'", ",", "dpi", "=", "dpi", ")" ]
Evaluate goodness of colormap using perceptual deltas. :param cmap: Colormap instance. :param dpi=100: dpi for saved image. :param saveplot=False: Whether to save the plot or not.
[ "Evaluate", "goodness", "of", "colormap", "using", "perceptual", "deltas", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/plots.py#L118-L136
15,163
matplotlib/cmocean
cmocean/plots.py
quick_plot
def quick_plot(cmap, fname=None, fig=None, ax=None, N=10): '''Show quick test of a colormap. ''' x = np.linspace(0, 10, N) X, _ = np.meshgrid(x, x) if ax is None: fig = plt.figure() ax = fig.add_subplot(111) mappable = ax.pcolor(X, cmap=cmap) ax.set_title(cmap.name, fontsize=14) ax.set_xticks([]) ax.set_yticks([]) plt.colorbar(mappable) plt.show() if fname is not None: plt.savefig(fname + '.png', bbox_inches='tight')
python
def quick_plot(cmap, fname=None, fig=None, ax=None, N=10): '''Show quick test of a colormap. ''' x = np.linspace(0, 10, N) X, _ = np.meshgrid(x, x) if ax is None: fig = plt.figure() ax = fig.add_subplot(111) mappable = ax.pcolor(X, cmap=cmap) ax.set_title(cmap.name, fontsize=14) ax.set_xticks([]) ax.set_yticks([]) plt.colorbar(mappable) plt.show() if fname is not None: plt.savefig(fname + '.png', bbox_inches='tight')
[ "def", "quick_plot", "(", "cmap", ",", "fname", "=", "None", ",", "fig", "=", "None", ",", "ax", "=", "None", ",", "N", "=", "10", ")", ":", "x", "=", "np", ".", "linspace", "(", "0", ",", "10", ",", "N", ")", "X", ",", "_", "=", "np", ".", "meshgrid", "(", "x", ",", "x", ")", "if", "ax", "is", "None", ":", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "mappable", "=", "ax", ".", "pcolor", "(", "X", ",", "cmap", "=", "cmap", ")", "ax", ".", "set_title", "(", "cmap", ".", "name", ",", "fontsize", "=", "14", ")", "ax", ".", "set_xticks", "(", "[", "]", ")", "ax", ".", "set_yticks", "(", "[", "]", ")", "plt", ".", "colorbar", "(", "mappable", ")", "plt", ".", "show", "(", ")", "if", "fname", "is", "not", "None", ":", "plt", ".", "savefig", "(", "fname", "+", "'.png'", ",", "bbox_inches", "=", "'tight'", ")" ]
Show quick test of a colormap.
[ "Show", "quick", "test", "of", "a", "colormap", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/plots.py#L164-L183
15,164
matplotlib/cmocean
cmocean/tools.py
print_colormaps
def print_colormaps(cmaps, N=256, returnrgb=True, savefiles=False): '''Print colormaps in 256 RGB colors to text files. :param returnrgb=False: Whether or not to return the rgb array. Only makes sense to do if print one colormaps' rgb. ''' rgb = [] for cmap in cmaps: rgbtemp = cmap(np.linspace(0, 1, N))[np.newaxis, :, :3][0] if savefiles: np.savetxt(cmap.name + '-rgb.txt', rgbtemp) rgb.append(rgbtemp) if returnrgb: return rgb
python
def print_colormaps(cmaps, N=256, returnrgb=True, savefiles=False): '''Print colormaps in 256 RGB colors to text files. :param returnrgb=False: Whether or not to return the rgb array. Only makes sense to do if print one colormaps' rgb. ''' rgb = [] for cmap in cmaps: rgbtemp = cmap(np.linspace(0, 1, N))[np.newaxis, :, :3][0] if savefiles: np.savetxt(cmap.name + '-rgb.txt', rgbtemp) rgb.append(rgbtemp) if returnrgb: return rgb
[ "def", "print_colormaps", "(", "cmaps", ",", "N", "=", "256", ",", "returnrgb", "=", "True", ",", "savefiles", "=", "False", ")", ":", "rgb", "=", "[", "]", "for", "cmap", "in", "cmaps", ":", "rgbtemp", "=", "cmap", "(", "np", ".", "linspace", "(", "0", ",", "1", ",", "N", ")", ")", "[", "np", ".", "newaxis", ",", ":", ",", ":", "3", "]", "[", "0", "]", "if", "savefiles", ":", "np", ".", "savetxt", "(", "cmap", ".", "name", "+", "'-rgb.txt'", ",", "rgbtemp", ")", "rgb", ".", "append", "(", "rgbtemp", ")", "if", "returnrgb", ":", "return", "rgb" ]
Print colormaps in 256 RGB colors to text files. :param returnrgb=False: Whether or not to return the rgb array. Only makes sense to do if print one colormaps' rgb.
[ "Print", "colormaps", "in", "256", "RGB", "colors", "to", "text", "files", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/tools.py#L17-L34
15,165
matplotlib/cmocean
cmocean/tools.py
cmap
def cmap(rgbin, N=256): '''Input an array of rgb values to generate a colormap. :param rgbin: An [mx3] array, where m is the number of input color triplets which are interpolated between to make the colormap that is returned. hex values can be input instead, as [mx1] in single quotes with a #. :param N=10: The number of levels to be interpolated to. ''' # rgb inputs here if not isinstance(rgbin[0], _string_types): # normalize to be out of 1 if out of 256 instead if rgbin.max() > 1: rgbin = rgbin/256. cmap = mpl.colors.LinearSegmentedColormap.from_list('mycmap', rgbin, N=N) return cmap
python
def cmap(rgbin, N=256): '''Input an array of rgb values to generate a colormap. :param rgbin: An [mx3] array, where m is the number of input color triplets which are interpolated between to make the colormap that is returned. hex values can be input instead, as [mx1] in single quotes with a #. :param N=10: The number of levels to be interpolated to. ''' # rgb inputs here if not isinstance(rgbin[0], _string_types): # normalize to be out of 1 if out of 256 instead if rgbin.max() > 1: rgbin = rgbin/256. cmap = mpl.colors.LinearSegmentedColormap.from_list('mycmap', rgbin, N=N) return cmap
[ "def", "cmap", "(", "rgbin", ",", "N", "=", "256", ")", ":", "# rgb inputs here", "if", "not", "isinstance", "(", "rgbin", "[", "0", "]", ",", "_string_types", ")", ":", "# normalize to be out of 1 if out of 256 instead", "if", "rgbin", ".", "max", "(", ")", ">", "1", ":", "rgbin", "=", "rgbin", "/", "256.", "cmap", "=", "mpl", ".", "colors", ".", "LinearSegmentedColormap", ".", "from_list", "(", "'mycmap'", ",", "rgbin", ",", "N", "=", "N", ")", "return", "cmap" ]
Input an array of rgb values to generate a colormap. :param rgbin: An [mx3] array, where m is the number of input color triplets which are interpolated between to make the colormap that is returned. hex values can be input instead, as [mx1] in single quotes with a #. :param N=10: The number of levels to be interpolated to.
[ "Input", "an", "array", "of", "rgb", "values", "to", "generate", "a", "colormap", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/tools.py#L73-L91
15,166
matplotlib/cmocean
cmocean/tools.py
lighten
def lighten(cmapin, alpha): '''Lighten a colormap by adding alpha < 1. :param cmap: A colormap object, like cmocean.cm.matter. :param alpha: An alpha or transparency value to assign the colormap. Alpha of 1 is opaque and of 1 is fully transparent. Outputs resultant colormap object. This will lighten the appearance of a plot you make using the output colormap object. It is also possible to lighten many plots in the plotting function itself (e.g. pcolormesh or contourf). ''' # set the alpha value while retaining the number of rows in original cmap return cmap(cmapin(np.linspace(0,1,cmapin.N), alpha))
python
def lighten(cmapin, alpha): '''Lighten a colormap by adding alpha < 1. :param cmap: A colormap object, like cmocean.cm.matter. :param alpha: An alpha or transparency value to assign the colormap. Alpha of 1 is opaque and of 1 is fully transparent. Outputs resultant colormap object. This will lighten the appearance of a plot you make using the output colormap object. It is also possible to lighten many plots in the plotting function itself (e.g. pcolormesh or contourf). ''' # set the alpha value while retaining the number of rows in original cmap return cmap(cmapin(np.linspace(0,1,cmapin.N), alpha))
[ "def", "lighten", "(", "cmapin", ",", "alpha", ")", ":", "# set the alpha value while retaining the number of rows in original cmap", "return", "cmap", "(", "cmapin", "(", "np", ".", "linspace", "(", "0", ",", "1", ",", "cmapin", ".", "N", ")", ",", "alpha", ")", ")" ]
Lighten a colormap by adding alpha < 1. :param cmap: A colormap object, like cmocean.cm.matter. :param alpha: An alpha or transparency value to assign the colormap. Alpha of 1 is opaque and of 1 is fully transparent. Outputs resultant colormap object. This will lighten the appearance of a plot you make using the output colormap object. It is also possible to lighten many plots in the plotting function itself (e.g. pcolormesh or contourf).
[ "Lighten", "a", "colormap", "by", "adding", "alpha", "<", "1", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/tools.py#L94-L109
15,167
matplotlib/cmocean
cmocean/tools.py
crop_by_percent
def crop_by_percent(cmap, per, which='both', N=None): '''Crop end or ends of a colormap by per percent. :param cmap: A colormap object, like cmocean.cm.matter. :param per: Percent of colormap to remove. If which=='both', take this percent off both ends of colormap. If which=='min' or which=='max', take percent only off the specified end of colormap. :param which='both': which end or ends of colormap to cut off. which='both' removes from both ends, which='min' from bottom end, and which='max' from top end. :param N=None: User can specify the number of rows for the outgoing colormap. If unspecified, N from incoming colormap will be used and values will be interpolated as needed to fill in rows. Outputs resultant colormap object. This is a wrapper around crop() to make it easier to use for cropping based on percent. Examples: # example with oxy map: cut off yellow part which is top 20% # compare with full colormap vmin = 0; vmax = 10; pivot = 5 A = np.random.randint(vmin, vmax, (5,5)) fig, axes = plt.subplots(1, 2) mappable = axes[0].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cmocean.cm.oxy) fig.colorbar(mappable, ax=axes[0]) vmin = 0; vmax = 8; pivot = 5 newcmap = crop_by_percent(cmocean.cm.oxy, 20, which='max', N=None) plt.figure() plt.pcolormesh(A, vmin=vmin, vmax=vmax, cmap=newcmap) plt.colorbar() # example with oxy map: cut off red part which is bottom 20% # compare with full colormap vmin = 0; vmax = 10; pivot = 5 A = np.random.randint(vmin, vmax, (5,5)) fig, axes = plt.subplots(1, 2) mappable = axes[0].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cmocean.cm.oxy) fig.colorbar(mappable, ax=axes[0]) vmin = 2; vmax = 10; pivot = 5 A = np.random.randint(vmin, vmax, (5,5)) newcmap = crop_by_percent(cmocean.cm.oxy, 20, which='min', N=None) plt.figure() plt.pcolormesh(A, vmin=vmin, vmax=vmax, cmap=newcmap) plt.colorbar() # crop both dark ends off colormap to reduce range newcmap = crop_by_percent(cmocean.cm.balance, 10, which='both', N=None) plt.figure() A = np.random.randint(-5, 5, (5,5)) plt.pcolormesh(A, vmin=vmin, vmax=vmax, cmap=newcmap) plt.colorbar() ''' if which == 'both': # take percent off both ends of cmap vmin = -100; vmax = 100; pivot = 0 dmax = per elif which == 'min': # take percent off bottom of cmap vmax = 10; pivot = 5 vmin = (0 + per/100)*2*pivot dmax = None elif which == 'max': # take percent off top of cmap vmin = 0; pivot = 5 vmax = (1 - per/100)*2*pivot dmax = None newcmap = crop(cmap, vmin, vmax, pivot, dmax=dmax, N=N) return newcmap
python
def crop_by_percent(cmap, per, which='both', N=None): '''Crop end or ends of a colormap by per percent. :param cmap: A colormap object, like cmocean.cm.matter. :param per: Percent of colormap to remove. If which=='both', take this percent off both ends of colormap. If which=='min' or which=='max', take percent only off the specified end of colormap. :param which='both': which end or ends of colormap to cut off. which='both' removes from both ends, which='min' from bottom end, and which='max' from top end. :param N=None: User can specify the number of rows for the outgoing colormap. If unspecified, N from incoming colormap will be used and values will be interpolated as needed to fill in rows. Outputs resultant colormap object. This is a wrapper around crop() to make it easier to use for cropping based on percent. Examples: # example with oxy map: cut off yellow part which is top 20% # compare with full colormap vmin = 0; vmax = 10; pivot = 5 A = np.random.randint(vmin, vmax, (5,5)) fig, axes = plt.subplots(1, 2) mappable = axes[0].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cmocean.cm.oxy) fig.colorbar(mappable, ax=axes[0]) vmin = 0; vmax = 8; pivot = 5 newcmap = crop_by_percent(cmocean.cm.oxy, 20, which='max', N=None) plt.figure() plt.pcolormesh(A, vmin=vmin, vmax=vmax, cmap=newcmap) plt.colorbar() # example with oxy map: cut off red part which is bottom 20% # compare with full colormap vmin = 0; vmax = 10; pivot = 5 A = np.random.randint(vmin, vmax, (5,5)) fig, axes = plt.subplots(1, 2) mappable = axes[0].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cmocean.cm.oxy) fig.colorbar(mappable, ax=axes[0]) vmin = 2; vmax = 10; pivot = 5 A = np.random.randint(vmin, vmax, (5,5)) newcmap = crop_by_percent(cmocean.cm.oxy, 20, which='min', N=None) plt.figure() plt.pcolormesh(A, vmin=vmin, vmax=vmax, cmap=newcmap) plt.colorbar() # crop both dark ends off colormap to reduce range newcmap = crop_by_percent(cmocean.cm.balance, 10, which='both', N=None) plt.figure() A = np.random.randint(-5, 5, (5,5)) plt.pcolormesh(A, vmin=vmin, vmax=vmax, cmap=newcmap) plt.colorbar() ''' if which == 'both': # take percent off both ends of cmap vmin = -100; vmax = 100; pivot = 0 dmax = per elif which == 'min': # take percent off bottom of cmap vmax = 10; pivot = 5 vmin = (0 + per/100)*2*pivot dmax = None elif which == 'max': # take percent off top of cmap vmin = 0; pivot = 5 vmax = (1 - per/100)*2*pivot dmax = None newcmap = crop(cmap, vmin, vmax, pivot, dmax=dmax, N=N) return newcmap
[ "def", "crop_by_percent", "(", "cmap", ",", "per", ",", "which", "=", "'both'", ",", "N", "=", "None", ")", ":", "if", "which", "==", "'both'", ":", "# take percent off both ends of cmap", "vmin", "=", "-", "100", "vmax", "=", "100", "pivot", "=", "0", "dmax", "=", "per", "elif", "which", "==", "'min'", ":", "# take percent off bottom of cmap", "vmax", "=", "10", "pivot", "=", "5", "vmin", "=", "(", "0", "+", "per", "/", "100", ")", "*", "2", "*", "pivot", "dmax", "=", "None", "elif", "which", "==", "'max'", ":", "# take percent off top of cmap", "vmin", "=", "0", "pivot", "=", "5", "vmax", "=", "(", "1", "-", "per", "/", "100", ")", "*", "2", "*", "pivot", "dmax", "=", "None", "newcmap", "=", "crop", "(", "cmap", ",", "vmin", ",", "vmax", ",", "pivot", ",", "dmax", "=", "dmax", ",", "N", "=", "N", ")", "return", "newcmap" ]
Crop end or ends of a colormap by per percent. :param cmap: A colormap object, like cmocean.cm.matter. :param per: Percent of colormap to remove. If which=='both', take this percent off both ends of colormap. If which=='min' or which=='max', take percent only off the specified end of colormap. :param which='both': which end or ends of colormap to cut off. which='both' removes from both ends, which='min' from bottom end, and which='max' from top end. :param N=None: User can specify the number of rows for the outgoing colormap. If unspecified, N from incoming colormap will be used and values will be interpolated as needed to fill in rows. Outputs resultant colormap object. This is a wrapper around crop() to make it easier to use for cropping based on percent. Examples: # example with oxy map: cut off yellow part which is top 20% # compare with full colormap vmin = 0; vmax = 10; pivot = 5 A = np.random.randint(vmin, vmax, (5,5)) fig, axes = plt.subplots(1, 2) mappable = axes[0].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cmocean.cm.oxy) fig.colorbar(mappable, ax=axes[0]) vmin = 0; vmax = 8; pivot = 5 newcmap = crop_by_percent(cmocean.cm.oxy, 20, which='max', N=None) plt.figure() plt.pcolormesh(A, vmin=vmin, vmax=vmax, cmap=newcmap) plt.colorbar() # example with oxy map: cut off red part which is bottom 20% # compare with full colormap vmin = 0; vmax = 10; pivot = 5 A = np.random.randint(vmin, vmax, (5,5)) fig, axes = plt.subplots(1, 2) mappable = axes[0].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cmocean.cm.oxy) fig.colorbar(mappable, ax=axes[0]) vmin = 2; vmax = 10; pivot = 5 A = np.random.randint(vmin, vmax, (5,5)) newcmap = crop_by_percent(cmocean.cm.oxy, 20, which='min', N=None) plt.figure() plt.pcolormesh(A, vmin=vmin, vmax=vmax, cmap=newcmap) plt.colorbar() # crop both dark ends off colormap to reduce range newcmap = crop_by_percent(cmocean.cm.balance, 10, which='both', N=None) plt.figure() A = np.random.randint(-5, 5, (5,5)) plt.pcolormesh(A, vmin=vmin, vmax=vmax, cmap=newcmap) plt.colorbar()
[ "Crop", "end", "or", "ends", "of", "a", "colormap", "by", "per", "percent", "." ]
37edd4a209a733d87dea7fed9eb22adc1d5a57c8
https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/tools.py#L198-L270
15,168
enricobacis/wos
wos/client.py
WosClient._premium
def _premium(fn): """Premium decorator for APIs that require premium access level.""" @_functools.wraps(fn) def _fn(self, *args, **kwargs): if self._lite: raise RuntimeError('Premium API not available in lite access.') return fn(self, *args, **kwargs) return _fn
python
def _premium(fn): """Premium decorator for APIs that require premium access level.""" @_functools.wraps(fn) def _fn(self, *args, **kwargs): if self._lite: raise RuntimeError('Premium API not available in lite access.') return fn(self, *args, **kwargs) return _fn
[ "def", "_premium", "(", "fn", ")", ":", "@", "_functools", ".", "wraps", "(", "fn", ")", "def", "_fn", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_lite", ":", "raise", "RuntimeError", "(", "'Premium API not available in lite access.'", ")", "return", "fn", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_fn" ]
Premium decorator for APIs that require premium access level.
[ "Premium", "decorator", "for", "APIs", "that", "require", "premium", "access", "level", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L70-L77
15,169
enricobacis/wos
wos/client.py
WosClient.make_retrieveParameters
def make_retrieveParameters(offset=1, count=100, name='RS', sort='D'): """Create retrieve parameters dictionary to be used with APIs. :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :name: Name of the field to order by. Use a two-character abbreviation to specify the field ('AU': Author, 'CF': Conference Title, 'CG': Page, 'CW': Source, 'CV': Volume, 'LC': Local Times Cited, 'LD': Load Date, 'PG': Page, 'PY': Publication Year, 'RS': Relevance, 'SO': Source, 'TC': Times Cited, 'VL': Volume) :sort: Must be A (ascending) or D (descending). The sort parameter can only be D for Relevance and TimesCited. """ return _OrderedDict([ ('firstRecord', offset), ('count', count), ('sortField', _OrderedDict([('name', name), ('sort', sort)])) ])
python
def make_retrieveParameters(offset=1, count=100, name='RS', sort='D'): """Create retrieve parameters dictionary to be used with APIs. :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :name: Name of the field to order by. Use a two-character abbreviation to specify the field ('AU': Author, 'CF': Conference Title, 'CG': Page, 'CW': Source, 'CV': Volume, 'LC': Local Times Cited, 'LD': Load Date, 'PG': Page, 'PY': Publication Year, 'RS': Relevance, 'SO': Source, 'TC': Times Cited, 'VL': Volume) :sort: Must be A (ascending) or D (descending). The sort parameter can only be D for Relevance and TimesCited. """ return _OrderedDict([ ('firstRecord', offset), ('count', count), ('sortField', _OrderedDict([('name', name), ('sort', sort)])) ])
[ "def", "make_retrieveParameters", "(", "offset", "=", "1", ",", "count", "=", "100", ",", "name", "=", "'RS'", ",", "sort", "=", "'D'", ")", ":", "return", "_OrderedDict", "(", "[", "(", "'firstRecord'", ",", "offset", ")", ",", "(", "'count'", ",", "count", ")", ",", "(", "'sortField'", ",", "_OrderedDict", "(", "[", "(", "'name'", ",", "name", ")", ",", "(", "'sort'", ",", "sort", ")", "]", ")", ")", "]", ")" ]
Create retrieve parameters dictionary to be used with APIs. :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :name: Name of the field to order by. Use a two-character abbreviation to specify the field ('AU': Author, 'CF': Conference Title, 'CG': Page, 'CW': Source, 'CV': Volume, 'LC': Local Times Cited, 'LD': Load Date, 'PG': Page, 'PY': Publication Year, 'RS': Relevance, 'SO': Source, 'TC': Times Cited, 'VL': Volume) :sort: Must be A (ascending) or D (descending). The sort parameter can only be D for Relevance and TimesCited.
[ "Create", "retrieve", "parameters", "dictionary", "to", "be", "used", "with", "APIs", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L80-L102
15,170
enricobacis/wos
wos/client.py
WosClient.connect
def connect(self): """Authenticate to WOS and set the SID cookie.""" if not self._SID: self._SID = self._auth.service.authenticate() print('Authenticated (SID: %s)' % self._SID) self._search.set_options(headers={'Cookie': 'SID="%s"' % self._SID}) self._auth.options.headers.update({'Cookie': 'SID="%s"' % self._SID}) return self._SID
python
def connect(self): """Authenticate to WOS and set the SID cookie.""" if not self._SID: self._SID = self._auth.service.authenticate() print('Authenticated (SID: %s)' % self._SID) self._search.set_options(headers={'Cookie': 'SID="%s"' % self._SID}) self._auth.options.headers.update({'Cookie': 'SID="%s"' % self._SID}) return self._SID
[ "def", "connect", "(", "self", ")", ":", "if", "not", "self", ".", "_SID", ":", "self", ".", "_SID", "=", "self", ".", "_auth", ".", "service", ".", "authenticate", "(", ")", "print", "(", "'Authenticated (SID: %s)'", "%", "self", ".", "_SID", ")", "self", ".", "_search", ".", "set_options", "(", "headers", "=", "{", "'Cookie'", ":", "'SID=\"%s\"'", "%", "self", ".", "_SID", "}", ")", "self", ".", "_auth", ".", "options", ".", "headers", ".", "update", "(", "{", "'Cookie'", ":", "'SID=\"%s\"'", "%", "self", ".", "_SID", "}", ")", "return", "self", ".", "_SID" ]
Authenticate to WOS and set the SID cookie.
[ "Authenticate", "to", "WOS", "and", "set", "the", "SID", "cookie", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L104-L112
15,171
enricobacis/wos
wos/client.py
WosClient.close
def close(self): """The close operation loads the session if it is valid and then closes it and releases the session seat. All the session data are deleted and become invalid after the request is processed. The session ID can no longer be used in subsequent requests.""" if self._SID: self._auth.service.closeSession() self._SID = None
python
def close(self): """The close operation loads the session if it is valid and then closes it and releases the session seat. All the session data are deleted and become invalid after the request is processed. The session ID can no longer be used in subsequent requests.""" if self._SID: self._auth.service.closeSession() self._SID = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_SID", ":", "self", ".", "_auth", ".", "service", ".", "closeSession", "(", ")", "self", ".", "_SID", "=", "None" ]
The close operation loads the session if it is valid and then closes it and releases the session seat. All the session data are deleted and become invalid after the request is processed. The session ID can no longer be used in subsequent requests.
[ "The", "close", "operation", "loads", "the", "session", "if", "it", "is", "valid", "and", "then", "closes", "it", "and", "releases", "the", "session", "seat", ".", "All", "the", "session", "data", "are", "deleted", "and", "become", "invalid", "after", "the", "request", "is", "processed", ".", "The", "session", "ID", "can", "no", "longer", "be", "used", "in", "subsequent", "requests", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L114-L121
15,172
enricobacis/wos
wos/client.py
WosClient.search
def search(self, query, count=5, offset=1, editions=None, symbolicTimeSpan=None, timeSpan=None, retrieveParameters=None): """The search operation submits a search query to the specified database edition and retrieves data. This operation returns a query ID that can be used in subsequent operations to retrieve more records. :query: User query for requesting data. The query parser will return errors for invalid queries :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :editions: List of editions to be searched. If None, user permissions will be substituted. Fields: collection - Name of the collection edition - Name of the edition :symbolicTimeSpan: This element defines a range of load dates. The load date is the date when a record was added to a database. If symbolicTimeSpan is specified, the timeSpan parameter must be omitted. If timeSpan and symbolicTimeSpan are both omitted, then the maximum publication date time span will be inferred from the editions data. Valid values: '1week' - Specifies to use the end date as today and the begin date as 1 week prior to today. '2week' - Specifies to use the end date as today and the begin date as 2 week prior to today. '4week' - Specifies to use the end date as today and the begin date as 4 week prior to today. :timeSpan: This element defines specifies a range of publication dates. If timeSpan is used, the symbolicTimeSpan parameter must be omitted. If timeSpan and symbolicTimeSpan are both omitted, then the maximum time span will be inferred from the editions data. Fields: begin - Beginning date for this search. Format: YYYY-MM-DD end - Ending date for this search. Format: YYYY-MM-DD :retrieveParameters: Retrieve parameters. If omitted the result of make_retrieveParameters(offset, count, 'RS', 'D') is used. """ return self._search.service.search( queryParameters=_OrderedDict([ ('databaseId', 'WOS'), ('userQuery', query), ('editions', editions), ('symbolicTimeSpan', symbolicTimeSpan), ('timeSpan', timeSpan), ('queryLanguage', 'en') ]), retrieveParameters=(retrieveParameters or self.make_retrieveParameters(offset, count)) )
python
def search(self, query, count=5, offset=1, editions=None, symbolicTimeSpan=None, timeSpan=None, retrieveParameters=None): """The search operation submits a search query to the specified database edition and retrieves data. This operation returns a query ID that can be used in subsequent operations to retrieve more records. :query: User query for requesting data. The query parser will return errors for invalid queries :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :editions: List of editions to be searched. If None, user permissions will be substituted. Fields: collection - Name of the collection edition - Name of the edition :symbolicTimeSpan: This element defines a range of load dates. The load date is the date when a record was added to a database. If symbolicTimeSpan is specified, the timeSpan parameter must be omitted. If timeSpan and symbolicTimeSpan are both omitted, then the maximum publication date time span will be inferred from the editions data. Valid values: '1week' - Specifies to use the end date as today and the begin date as 1 week prior to today. '2week' - Specifies to use the end date as today and the begin date as 2 week prior to today. '4week' - Specifies to use the end date as today and the begin date as 4 week prior to today. :timeSpan: This element defines specifies a range of publication dates. If timeSpan is used, the symbolicTimeSpan parameter must be omitted. If timeSpan and symbolicTimeSpan are both omitted, then the maximum time span will be inferred from the editions data. Fields: begin - Beginning date for this search. Format: YYYY-MM-DD end - Ending date for this search. Format: YYYY-MM-DD :retrieveParameters: Retrieve parameters. If omitted the result of make_retrieveParameters(offset, count, 'RS', 'D') is used. """ return self._search.service.search( queryParameters=_OrderedDict([ ('databaseId', 'WOS'), ('userQuery', query), ('editions', editions), ('symbolicTimeSpan', symbolicTimeSpan), ('timeSpan', timeSpan), ('queryLanguage', 'en') ]), retrieveParameters=(retrieveParameters or self.make_retrieveParameters(offset, count)) )
[ "def", "search", "(", "self", ",", "query", ",", "count", "=", "5", ",", "offset", "=", "1", ",", "editions", "=", "None", ",", "symbolicTimeSpan", "=", "None", ",", "timeSpan", "=", "None", ",", "retrieveParameters", "=", "None", ")", ":", "return", "self", ".", "_search", ".", "service", ".", "search", "(", "queryParameters", "=", "_OrderedDict", "(", "[", "(", "'databaseId'", ",", "'WOS'", ")", ",", "(", "'userQuery'", ",", "query", ")", ",", "(", "'editions'", ",", "editions", ")", ",", "(", "'symbolicTimeSpan'", ",", "symbolicTimeSpan", ")", ",", "(", "'timeSpan'", ",", "timeSpan", ")", ",", "(", "'queryLanguage'", ",", "'en'", ")", "]", ")", ",", "retrieveParameters", "=", "(", "retrieveParameters", "or", "self", ".", "make_retrieveParameters", "(", "offset", ",", "count", ")", ")", ")" ]
The search operation submits a search query to the specified database edition and retrieves data. This operation returns a query ID that can be used in subsequent operations to retrieve more records. :query: User query for requesting data. The query parser will return errors for invalid queries :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :editions: List of editions to be searched. If None, user permissions will be substituted. Fields: collection - Name of the collection edition - Name of the edition :symbolicTimeSpan: This element defines a range of load dates. The load date is the date when a record was added to a database. If symbolicTimeSpan is specified, the timeSpan parameter must be omitted. If timeSpan and symbolicTimeSpan are both omitted, then the maximum publication date time span will be inferred from the editions data. Valid values: '1week' - Specifies to use the end date as today and the begin date as 1 week prior to today. '2week' - Specifies to use the end date as today and the begin date as 2 week prior to today. '4week' - Specifies to use the end date as today and the begin date as 4 week prior to today. :timeSpan: This element defines specifies a range of publication dates. If timeSpan is used, the symbolicTimeSpan parameter must be omitted. If timeSpan and symbolicTimeSpan are both omitted, then the maximum time span will be inferred from the editions data. Fields: begin - Beginning date for this search. Format: YYYY-MM-DD end - Ending date for this search. Format: YYYY-MM-DD :retrieveParameters: Retrieve parameters. If omitted the result of make_retrieveParameters(offset, count, 'RS', 'D') is used.
[ "The", "search", "operation", "submits", "a", "search", "query", "to", "the", "specified", "database", "edition", "and", "retrieves", "data", ".", "This", "operation", "returns", "a", "query", "ID", "that", "can", "be", "used", "in", "subsequent", "operations", "to", "retrieve", "more", "records", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L124-L187
15,173
enricobacis/wos
wos/client.py
WosClient.citedReferences
def citedReferences(self, uid, count=100, offset=1, retrieveParameters=None): """The citedReferences operation returns references cited by an article identified by a unique identifier. You may specify only one identifier per request. :uid: Thomson Reuters unique record identifier :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :retrieveParameters: Retrieve parameters. If omitted the result of make_retrieveParameters(offset, count, 'RS', 'D') is used. """ return self._search.service.citedReferences( databaseId='WOS', uid=uid, queryLanguage='en', retrieveParameters=(retrieveParameters or self.make_retrieveParameters(offset, count)) )
python
def citedReferences(self, uid, count=100, offset=1, retrieveParameters=None): """The citedReferences operation returns references cited by an article identified by a unique identifier. You may specify only one identifier per request. :uid: Thomson Reuters unique record identifier :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :retrieveParameters: Retrieve parameters. If omitted the result of make_retrieveParameters(offset, count, 'RS', 'D') is used. """ return self._search.service.citedReferences( databaseId='WOS', uid=uid, queryLanguage='en', retrieveParameters=(retrieveParameters or self.make_retrieveParameters(offset, count)) )
[ "def", "citedReferences", "(", "self", ",", "uid", ",", "count", "=", "100", ",", "offset", "=", "1", ",", "retrieveParameters", "=", "None", ")", ":", "return", "self", ".", "_search", ".", "service", ".", "citedReferences", "(", "databaseId", "=", "'WOS'", ",", "uid", "=", "uid", ",", "queryLanguage", "=", "'en'", ",", "retrieveParameters", "=", "(", "retrieveParameters", "or", "self", ".", "make_retrieveParameters", "(", "offset", ",", "count", ")", ")", ")" ]
The citedReferences operation returns references cited by an article identified by a unique identifier. You may specify only one identifier per request. :uid: Thomson Reuters unique record identifier :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :retrieveParameters: Retrieve parameters. If omitted the result of make_retrieveParameters(offset, count, 'RS', 'D') is used.
[ "The", "citedReferences", "operation", "returns", "references", "cited", "by", "an", "article", "identified", "by", "a", "unique", "identifier", ".", "You", "may", "specify", "only", "one", "identifier", "per", "request", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L250-L274
15,174
enricobacis/wos
wos/client.py
WosClient.citedReferencesRetrieve
def citedReferencesRetrieve(self, queryId, count=100, offset=1, retrieveParameters=None): """The citedReferencesRetrieve operation submits a query returned by a previous citedReferences operation. This operation is useful for overcoming the retrieval limit of 100 records per query. For example, a citedReferences operation may find 106 cited references, as revealed by the content of the recordsFound element, but it returns only records 1-100. You could perform a subsequent citedReferencesretrieve operation to obtain records 101-106. :queryId: The query ID from a previous citedReferences operation :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :retrieveParameters: Retrieve parameters. If omitted the result of make_retrieveParameters(offset, count, 'RS', 'D') is used. """ return self._search.service.citedReferencesRetrieve( queryId=queryId, retrieveParameters=(retrieveParameters or self.make_retrieveParameters(offset, count)) )
python
def citedReferencesRetrieve(self, queryId, count=100, offset=1, retrieveParameters=None): """The citedReferencesRetrieve operation submits a query returned by a previous citedReferences operation. This operation is useful for overcoming the retrieval limit of 100 records per query. For example, a citedReferences operation may find 106 cited references, as revealed by the content of the recordsFound element, but it returns only records 1-100. You could perform a subsequent citedReferencesretrieve operation to obtain records 101-106. :queryId: The query ID from a previous citedReferences operation :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :retrieveParameters: Retrieve parameters. If omitted the result of make_retrieveParameters(offset, count, 'RS', 'D') is used. """ return self._search.service.citedReferencesRetrieve( queryId=queryId, retrieveParameters=(retrieveParameters or self.make_retrieveParameters(offset, count)) )
[ "def", "citedReferencesRetrieve", "(", "self", ",", "queryId", ",", "count", "=", "100", ",", "offset", "=", "1", ",", "retrieveParameters", "=", "None", ")", ":", "return", "self", ".", "_search", ".", "service", ".", "citedReferencesRetrieve", "(", "queryId", "=", "queryId", ",", "retrieveParameters", "=", "(", "retrieveParameters", "or", "self", ".", "make_retrieveParameters", "(", "offset", ",", "count", ")", ")", ")" ]
The citedReferencesRetrieve operation submits a query returned by a previous citedReferences operation. This operation is useful for overcoming the retrieval limit of 100 records per query. For example, a citedReferences operation may find 106 cited references, as revealed by the content of the recordsFound element, but it returns only records 1-100. You could perform a subsequent citedReferencesretrieve operation to obtain records 101-106. :queryId: The query ID from a previous citedReferences operation :count: Number of records to display in the result. Cannot be less than 0 and cannot be greater than 100. If count is 0 then only the summary information will be returned. :offset: First record in results to return. Must be greater than zero :retrieveParameters: Retrieve parameters. If omitted the result of make_retrieveParameters(offset, count, 'RS', 'D') is used.
[ "The", "citedReferencesRetrieve", "operation", "submits", "a", "query", "returned", "by", "a", "previous", "citedReferences", "operation", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L278-L305
15,175
enricobacis/wos
wos/utils.py
single
def single(wosclient, wos_query, xml_query=None, count=5, offset=1): """Perform a single Web of Science query and then XML query the results.""" result = wosclient.search(wos_query, count, offset) xml = _re.sub(' xmlns="[^"]+"', '', result.records, count=1).encode('utf-8') if xml_query: xml = _ET.fromstring(xml) return [el.text for el in xml.findall(xml_query)] else: return _minidom.parseString(xml).toprettyxml()
python
def single(wosclient, wos_query, xml_query=None, count=5, offset=1): """Perform a single Web of Science query and then XML query the results.""" result = wosclient.search(wos_query, count, offset) xml = _re.sub(' xmlns="[^"]+"', '', result.records, count=1).encode('utf-8') if xml_query: xml = _ET.fromstring(xml) return [el.text for el in xml.findall(xml_query)] else: return _minidom.parseString(xml).toprettyxml()
[ "def", "single", "(", "wosclient", ",", "wos_query", ",", "xml_query", "=", "None", ",", "count", "=", "5", ",", "offset", "=", "1", ")", ":", "result", "=", "wosclient", ".", "search", "(", "wos_query", ",", "count", ",", "offset", ")", "xml", "=", "_re", ".", "sub", "(", "' xmlns=\"[^\"]+\"'", ",", "''", ",", "result", ".", "records", ",", "count", "=", "1", ")", ".", "encode", "(", "'utf-8'", ")", "if", "xml_query", ":", "xml", "=", "_ET", ".", "fromstring", "(", "xml", ")", "return", "[", "el", ".", "text", "for", "el", "in", "xml", ".", "findall", "(", "xml_query", ")", "]", "else", ":", "return", "_minidom", ".", "parseString", "(", "xml", ")", ".", "toprettyxml", "(", ")" ]
Perform a single Web of Science query and then XML query the results.
[ "Perform", "a", "single", "Web", "of", "Science", "query", "and", "then", "XML", "query", "the", "results", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/utils.py#L10-L18
15,176
enricobacis/wos
wos/utils.py
query
def query(wosclient, wos_query, xml_query=None, count=5, offset=1, limit=100): """Query Web of Science and XML query results with multiple requests.""" results = [single(wosclient, wos_query, xml_query, min(limit, count-x+1), x) for x in range(offset, count+1, limit)] if xml_query: return [el for res in results for el in res] else: pattern = _re.compile(r'^<\?xml.*?\n<records>\n|\n</records>$.*') return ('<?xml version="1.0" ?>\n<records>' + '\n'.join(pattern.sub('', res) for res in results) + '</records>')
python
def query(wosclient, wos_query, xml_query=None, count=5, offset=1, limit=100): """Query Web of Science and XML query results with multiple requests.""" results = [single(wosclient, wos_query, xml_query, min(limit, count-x+1), x) for x in range(offset, count+1, limit)] if xml_query: return [el for res in results for el in res] else: pattern = _re.compile(r'^<\?xml.*?\n<records>\n|\n</records>$.*') return ('<?xml version="1.0" ?>\n<records>' + '\n'.join(pattern.sub('', res) for res in results) + '</records>')
[ "def", "query", "(", "wosclient", ",", "wos_query", ",", "xml_query", "=", "None", ",", "count", "=", "5", ",", "offset", "=", "1", ",", "limit", "=", "100", ")", ":", "results", "=", "[", "single", "(", "wosclient", ",", "wos_query", ",", "xml_query", ",", "min", "(", "limit", ",", "count", "-", "x", "+", "1", ")", ",", "x", ")", "for", "x", "in", "range", "(", "offset", ",", "count", "+", "1", ",", "limit", ")", "]", "if", "xml_query", ":", "return", "[", "el", "for", "res", "in", "results", "for", "el", "in", "res", "]", "else", ":", "pattern", "=", "_re", ".", "compile", "(", "r'^<\\?xml.*?\\n<records>\\n|\\n</records>$.*'", ")", "return", "(", "'<?xml version=\"1.0\" ?>\\n<records>'", "+", "'\\n'", ".", "join", "(", "pattern", ".", "sub", "(", "''", ",", "res", ")", "for", "res", "in", "results", ")", "+", "'</records>'", ")" ]
Query Web of Science and XML query results with multiple requests.
[ "Query", "Web", "of", "Science", "and", "XML", "query", "results", "with", "multiple", "requests", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/utils.py#L21-L31
15,177
enricobacis/wos
wos/utils.py
doi_to_wos
def doi_to_wos(wosclient, doi): """Convert DOI to WOS identifier.""" results = query(wosclient, 'DO="%s"' % doi, './REC/UID', count=1) return results[0].lstrip('WOS:') if results else None
python
def doi_to_wos(wosclient, doi): """Convert DOI to WOS identifier.""" results = query(wosclient, 'DO="%s"' % doi, './REC/UID', count=1) return results[0].lstrip('WOS:') if results else None
[ "def", "doi_to_wos", "(", "wosclient", ",", "doi", ")", ":", "results", "=", "query", "(", "wosclient", ",", "'DO=\"%s\"'", "%", "doi", ",", "'./REC/UID'", ",", "count", "=", "1", ")", "return", "results", "[", "0", "]", ".", "lstrip", "(", "'WOS:'", ")", "if", "results", "else", "None" ]
Convert DOI to WOS identifier.
[ "Convert", "DOI", "to", "WOS", "identifier", "." ]
a51f4d1a983c2c7529caac3e09606a432223630d
https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/utils.py#L34-L37
15,178
adamchainz/django-perf-rec
django_perf_rec/sql.py
sql_fingerprint
def sql_fingerprint(query, hide_columns=True): """ Simplify a query, taking away exact values and fields selected. Imperfect but better than super explicit, value-dependent queries. """ parsed_query = parse(query)[0] sql_recursively_simplify(parsed_query, hide_columns=hide_columns) return str(parsed_query)
python
def sql_fingerprint(query, hide_columns=True): """ Simplify a query, taking away exact values and fields selected. Imperfect but better than super explicit, value-dependent queries. """ parsed_query = parse(query)[0] sql_recursively_simplify(parsed_query, hide_columns=hide_columns) return str(parsed_query)
[ "def", "sql_fingerprint", "(", "query", ",", "hide_columns", "=", "True", ")", ":", "parsed_query", "=", "parse", "(", "query", ")", "[", "0", "]", "sql_recursively_simplify", "(", "parsed_query", ",", "hide_columns", "=", "hide_columns", ")", "return", "str", "(", "parsed_query", ")" ]
Simplify a query, taking away exact values and fields selected. Imperfect but better than super explicit, value-dependent queries.
[ "Simplify", "a", "query", "taking", "away", "exact", "values", "and", "fields", "selected", "." ]
76a1874820b55bcbc2f95a85bbda3cb056584e2c
https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/sql.py#L7-L15
15,179
adamchainz/django-perf-rec
django_perf_rec/sql.py
match_keyword
def match_keyword(token, keywords): """ Checks if the given token represents one of the given keywords """ if not token: return False if not token.is_keyword: return False return token.value.upper() in keywords
python
def match_keyword(token, keywords): """ Checks if the given token represents one of the given keywords """ if not token: return False if not token.is_keyword: return False return token.value.upper() in keywords
[ "def", "match_keyword", "(", "token", ",", "keywords", ")", ":", "if", "not", "token", ":", "return", "False", "if", "not", "token", ".", "is_keyword", ":", "return", "False", "return", "token", ".", "value", ".", "upper", "(", ")", "in", "keywords" ]
Checks if the given token represents one of the given keywords
[ "Checks", "if", "the", "given", "token", "represents", "one", "of", "the", "given", "keywords" ]
76a1874820b55bcbc2f95a85bbda3cb056584e2c
https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/sql.py#L84-L93
15,180
adamchainz/django-perf-rec
django_perf_rec/sql.py
_is_group
def _is_group(token): """ sqlparse 0.2.2 changed it from a callable to a bool property """ is_group = token.is_group if isinstance(is_group, bool): return is_group else: return is_group()
python
def _is_group(token): """ sqlparse 0.2.2 changed it from a callable to a bool property """ is_group = token.is_group if isinstance(is_group, bool): return is_group else: return is_group()
[ "def", "_is_group", "(", "token", ")", ":", "is_group", "=", "token", ".", "is_group", "if", "isinstance", "(", "is_group", ",", "bool", ")", ":", "return", "is_group", "else", ":", "return", "is_group", "(", ")" ]
sqlparse 0.2.2 changed it from a callable to a bool property
[ "sqlparse", "0", ".", "2", ".", "2", "changed", "it", "from", "a", "callable", "to", "a", "bool", "property" ]
76a1874820b55bcbc2f95a85bbda3cb056584e2c
https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/sql.py#L96-L104
15,181
adamchainz/django-perf-rec
django_perf_rec/utils.py
sorted_names
def sorted_names(names): """ Sort a list of names but keep the word 'default' first if it's there. """ names = list(names) have_default = False if 'default' in names: names.remove('default') have_default = True sorted_names = sorted(names) if have_default: sorted_names = ['default'] + sorted_names return sorted_names
python
def sorted_names(names): """ Sort a list of names but keep the word 'default' first if it's there. """ names = list(names) have_default = False if 'default' in names: names.remove('default') have_default = True sorted_names = sorted(names) if have_default: sorted_names = ['default'] + sorted_names return sorted_names
[ "def", "sorted_names", "(", "names", ")", ":", "names", "=", "list", "(", "names", ")", "have_default", "=", "False", "if", "'default'", "in", "names", ":", "names", ".", "remove", "(", "'default'", ")", "have_default", "=", "True", "sorted_names", "=", "sorted", "(", "names", ")", "if", "have_default", ":", "sorted_names", "=", "[", "'default'", "]", "+", "sorted_names", "return", "sorted_names" ]
Sort a list of names but keep the word 'default' first if it's there.
[ "Sort", "a", "list", "of", "names", "but", "keep", "the", "word", "default", "first", "if", "it", "s", "there", "." ]
76a1874820b55bcbc2f95a85bbda3cb056584e2c
https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/utils.py#L82-L98
15,182
adamchainz/django-perf-rec
django_perf_rec/utils.py
record_diff
def record_diff(old, new): """ Generate a human-readable diff of two performance records. """ return '\n'.join(difflib.ndiff( ['%s: %s' % (k, v) for op in old for k, v in op.items()], ['%s: %s' % (k, v) for op in new for k, v in op.items()], ))
python
def record_diff(old, new): """ Generate a human-readable diff of two performance records. """ return '\n'.join(difflib.ndiff( ['%s: %s' % (k, v) for op in old for k, v in op.items()], ['%s: %s' % (k, v) for op in new for k, v in op.items()], ))
[ "def", "record_diff", "(", "old", ",", "new", ")", ":", "return", "'\\n'", ".", "join", "(", "difflib", ".", "ndiff", "(", "[", "'%s: %s'", "%", "(", "k", ",", "v", ")", "for", "op", "in", "old", "for", "k", ",", "v", "in", "op", ".", "items", "(", ")", "]", ",", "[", "'%s: %s'", "%", "(", "k", ",", "v", ")", "for", "op", "in", "new", "for", "k", ",", "v", "in", "op", ".", "items", "(", ")", "]", ",", ")", ")" ]
Generate a human-readable diff of two performance records.
[ "Generate", "a", "human", "-", "readable", "diff", "of", "two", "performance", "records", "." ]
76a1874820b55bcbc2f95a85bbda3cb056584e2c
https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/utils.py#L101-L108
15,183
reportportal/client-Python
reportportal_client/service_async.py
QueueListener.dequeue
def dequeue(self, block=True): """Dequeue a record and return item.""" return self.queue.get(block, self.queue_get_timeout)
python
def dequeue(self, block=True): """Dequeue a record and return item.""" return self.queue.get(block, self.queue_get_timeout)
[ "def", "dequeue", "(", "self", ",", "block", "=", "True", ")", ":", "return", "self", ".", "queue", ".", "get", "(", "block", ",", "self", ".", "queue_get_timeout", ")" ]
Dequeue a record and return item.
[ "Dequeue", "a", "record", "and", "return", "item", "." ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L39-L41
15,184
reportportal/client-Python
reportportal_client/service_async.py
QueueListener.start
def start(self): """Start the listener. This starts up a background thread to monitor the queue for items to process. """ self._thread = t = threading.Thread(target=self._monitor) t.setDaemon(True) t.start()
python
def start(self): """Start the listener. This starts up a background thread to monitor the queue for items to process. """ self._thread = t = threading.Thread(target=self._monitor) t.setDaemon(True) t.start()
[ "def", "start", "(", "self", ")", ":", "self", ".", "_thread", "=", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_monitor", ")", "t", ".", "setDaemon", "(", "True", ")", "t", ".", "start", "(", ")" ]
Start the listener. This starts up a background thread to monitor the queue for items to process.
[ "Start", "the", "listener", "." ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L43-L51
15,185
reportportal/client-Python
reportportal_client/service_async.py
QueueListener.handle
def handle(self, record): """Handle an item. This just loops through the handlers offering them the record to handle. """ record = self.prepare(record) for handler in self.handlers: handler(record)
python
def handle(self, record): """Handle an item. This just loops through the handlers offering them the record to handle. """ record = self.prepare(record) for handler in self.handlers: handler(record)
[ "def", "handle", "(", "self", ",", "record", ")", ":", "record", "=", "self", ".", "prepare", "(", "record", ")", "for", "handler", "in", "self", ".", "handlers", ":", "handler", "(", "record", ")" ]
Handle an item. This just loops through the handlers offering them the record to handle.
[ "Handle", "an", "item", "." ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L62-L70
15,186
reportportal/client-Python
reportportal_client/service_async.py
QueueListener._monitor
def _monitor(self): """Monitor the queue for items, and ask the handler to deal with them. This method runs on a separate, internal thread. The thread will terminate if it sees a sentinel object in the queue. """ err_msg = ("invalid internal state:" " _stop_nowait can not be set if _stop is not set") assert self._stop.isSet() or not self._stop_nowait.isSet(), err_msg q = self.queue has_task_done = hasattr(q, 'task_done') while not self._stop.isSet(): try: record = self.dequeue(True) if record is self._sentinel_item: break self.handle(record) if has_task_done: q.task_done() except queue.Empty: pass # There might still be records in the queue, # handle then unless _stop_nowait is set. while not self._stop_nowait.isSet(): try: record = self.dequeue(False) if record is self._sentinel_item: break self.handle(record) if has_task_done: q.task_done() except queue.Empty: break
python
def _monitor(self): """Monitor the queue for items, and ask the handler to deal with them. This method runs on a separate, internal thread. The thread will terminate if it sees a sentinel object in the queue. """ err_msg = ("invalid internal state:" " _stop_nowait can not be set if _stop is not set") assert self._stop.isSet() or not self._stop_nowait.isSet(), err_msg q = self.queue has_task_done = hasattr(q, 'task_done') while not self._stop.isSet(): try: record = self.dequeue(True) if record is self._sentinel_item: break self.handle(record) if has_task_done: q.task_done() except queue.Empty: pass # There might still be records in the queue, # handle then unless _stop_nowait is set. while not self._stop_nowait.isSet(): try: record = self.dequeue(False) if record is self._sentinel_item: break self.handle(record) if has_task_done: q.task_done() except queue.Empty: break
[ "def", "_monitor", "(", "self", ")", ":", "err_msg", "=", "(", "\"invalid internal state:\"", "\" _stop_nowait can not be set if _stop is not set\"", ")", "assert", "self", ".", "_stop", ".", "isSet", "(", ")", "or", "not", "self", ".", "_stop_nowait", ".", "isSet", "(", ")", ",", "err_msg", "q", "=", "self", ".", "queue", "has_task_done", "=", "hasattr", "(", "q", ",", "'task_done'", ")", "while", "not", "self", ".", "_stop", ".", "isSet", "(", ")", ":", "try", ":", "record", "=", "self", ".", "dequeue", "(", "True", ")", "if", "record", "is", "self", ".", "_sentinel_item", ":", "break", "self", ".", "handle", "(", "record", ")", "if", "has_task_done", ":", "q", ".", "task_done", "(", ")", "except", "queue", ".", "Empty", ":", "pass", "# There might still be records in the queue,", "# handle then unless _stop_nowait is set.", "while", "not", "self", ".", "_stop_nowait", ".", "isSet", "(", ")", ":", "try", ":", "record", "=", "self", ".", "dequeue", "(", "False", ")", "if", "record", "is", "self", ".", "_sentinel_item", ":", "break", "self", ".", "handle", "(", "record", ")", "if", "has_task_done", ":", "q", ".", "task_done", "(", ")", "except", "queue", ".", "Empty", ":", "break" ]
Monitor the queue for items, and ask the handler to deal with them. This method runs on a separate, internal thread. The thread will terminate if it sees a sentinel object in the queue.
[ "Monitor", "the", "queue", "for", "items", "and", "ask", "the", "handler", "to", "deal", "with", "them", "." ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L72-L106
15,187
reportportal/client-Python
reportportal_client/service_async.py
QueueListener.stop
def stop(self, nowait=False): """Stop the listener. This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there may be some records still left on the queue, which won't be processed. If nowait is False then thread will handle remaining items in queue and stop. If nowait is True then thread will be stopped even if the queue still contains items. """ self._stop.set() if nowait: self._stop_nowait.set() self.queue.put_nowait(self._sentinel_item) if (self._thread.isAlive() and self._thread is not threading.currentThread()): self._thread.join() self._thread = None
python
def stop(self, nowait=False): """Stop the listener. This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there may be some records still left on the queue, which won't be processed. If nowait is False then thread will handle remaining items in queue and stop. If nowait is True then thread will be stopped even if the queue still contains items. """ self._stop.set() if nowait: self._stop_nowait.set() self.queue.put_nowait(self._sentinel_item) if (self._thread.isAlive() and self._thread is not threading.currentThread()): self._thread.join() self._thread = None
[ "def", "stop", "(", "self", ",", "nowait", "=", "False", ")", ":", "self", ".", "_stop", ".", "set", "(", ")", "if", "nowait", ":", "self", ".", "_stop_nowait", ".", "set", "(", ")", "self", ".", "queue", ".", "put_nowait", "(", "self", ".", "_sentinel_item", ")", "if", "(", "self", ".", "_thread", ".", "isAlive", "(", ")", "and", "self", ".", "_thread", "is", "not", "threading", ".", "currentThread", "(", ")", ")", ":", "self", ".", "_thread", ".", "join", "(", ")", "self", ".", "_thread", "=", "None" ]
Stop the listener. This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there may be some records still left on the queue, which won't be processed. If nowait is False then thread will handle remaining items in queue and stop. If nowait is True then thread will be stopped even if the queue still contains items.
[ "Stop", "the", "listener", "." ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L108-L126
15,188
reportportal/client-Python
reportportal_client/service_async.py
ReportPortalServiceAsync.terminate
def terminate(self, nowait=False): """Finalize and stop service Args: nowait: set to True to terminate immediately and skip processing messages still in the queue """ logger.debug("Acquiring lock for service termination") with self.lock: logger.debug("Terminating service") if not self.listener: logger.warning("Service already stopped.") return self.listener.stop(nowait) try: if not nowait: self._post_log_batch() except Exception: if self.error_handler: self.error_handler(sys.exc_info()) else: raise finally: self.queue = None self.listener = None
python
def terminate(self, nowait=False): """Finalize and stop service Args: nowait: set to True to terminate immediately and skip processing messages still in the queue """ logger.debug("Acquiring lock for service termination") with self.lock: logger.debug("Terminating service") if not self.listener: logger.warning("Service already stopped.") return self.listener.stop(nowait) try: if not nowait: self._post_log_batch() except Exception: if self.error_handler: self.error_handler(sys.exc_info()) else: raise finally: self.queue = None self.listener = None
[ "def", "terminate", "(", "self", ",", "nowait", "=", "False", ")", ":", "logger", ".", "debug", "(", "\"Acquiring lock for service termination\"", ")", "with", "self", ".", "lock", ":", "logger", ".", "debug", "(", "\"Terminating service\"", ")", "if", "not", "self", ".", "listener", ":", "logger", ".", "warning", "(", "\"Service already stopped.\"", ")", "return", "self", ".", "listener", ".", "stop", "(", "nowait", ")", "try", ":", "if", "not", "nowait", ":", "self", ".", "_post_log_batch", "(", ")", "except", "Exception", ":", "if", "self", ".", "error_handler", ":", "self", ".", "error_handler", "(", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "raise", "finally", ":", "self", ".", "queue", "=", "None", "self", ".", "listener", "=", "None" ]
Finalize and stop service Args: nowait: set to True to terminate immediately and skip processing messages still in the queue
[ "Finalize", "and", "stop", "service" ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L169-L196
15,189
reportportal/client-Python
reportportal_client/service_async.py
ReportPortalServiceAsync.process_log
def process_log(self, **log_item): """Special handler for log messages. Accumulate incoming log messages and post them in batch. """ logger.debug("Processing log item: %s", log_item) self.log_batch.append(log_item) if len(self.log_batch) >= self.log_batch_size: self._post_log_batch()
python
def process_log(self, **log_item): """Special handler for log messages. Accumulate incoming log messages and post them in batch. """ logger.debug("Processing log item: %s", log_item) self.log_batch.append(log_item) if len(self.log_batch) >= self.log_batch_size: self._post_log_batch()
[ "def", "process_log", "(", "self", ",", "*", "*", "log_item", ")", ":", "logger", ".", "debug", "(", "\"Processing log item: %s\"", ",", "log_item", ")", "self", ".", "log_batch", ".", "append", "(", "log_item", ")", "if", "len", "(", "self", ".", "log_batch", ")", ">=", "self", ".", "log_batch_size", ":", "self", ".", "_post_log_batch", "(", ")" ]
Special handler for log messages. Accumulate incoming log messages and post them in batch.
[ "Special", "handler", "for", "log", "messages", "." ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L206-L214
15,190
reportportal/client-Python
reportportal_client/service_async.py
ReportPortalServiceAsync.process_item
def process_item(self, item): """Main item handler. Called by queue listener. """ logger.debug("Processing item: %s (queue size: %s)", item, self.queue.qsize()) method, kwargs = item if method not in self.supported_methods: raise Error("Not expected service method: {}".format(method)) try: if method == "log": self.process_log(**kwargs) else: self._post_log_batch() getattr(self.rp_client, method)(**kwargs) except Exception: if self.error_handler: self.error_handler(sys.exc_info()) else: self.terminate(nowait=True) raise
python
def process_item(self, item): """Main item handler. Called by queue listener. """ logger.debug("Processing item: %s (queue size: %s)", item, self.queue.qsize()) method, kwargs = item if method not in self.supported_methods: raise Error("Not expected service method: {}".format(method)) try: if method == "log": self.process_log(**kwargs) else: self._post_log_batch() getattr(self.rp_client, method)(**kwargs) except Exception: if self.error_handler: self.error_handler(sys.exc_info()) else: self.terminate(nowait=True) raise
[ "def", "process_item", "(", "self", ",", "item", ")", ":", "logger", ".", "debug", "(", "\"Processing item: %s (queue size: %s)\"", ",", "item", ",", "self", ".", "queue", ".", "qsize", "(", ")", ")", "method", ",", "kwargs", "=", "item", "if", "method", "not", "in", "self", ".", "supported_methods", ":", "raise", "Error", "(", "\"Not expected service method: {}\"", ".", "format", "(", "method", ")", ")", "try", ":", "if", "method", "==", "\"log\"", ":", "self", ".", "process_log", "(", "*", "*", "kwargs", ")", "else", ":", "self", ".", "_post_log_batch", "(", ")", "getattr", "(", "self", ".", "rp_client", ",", "method", ")", "(", "*", "*", "kwargs", ")", "except", "Exception", ":", "if", "self", ".", "error_handler", ":", "self", ".", "error_handler", "(", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "self", ".", "terminate", "(", "nowait", "=", "True", ")", "raise" ]
Main item handler. Called by queue listener.
[ "Main", "item", "handler", "." ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L216-L239
15,191
reportportal/client-Python
reportportal_client/service_async.py
ReportPortalServiceAsync.log
def log(self, time, message, level=None, attachment=None): """Logs a message with attachment. The attachment is a dict of: name: name of attachment data: file content mime: content type for attachment """ logger.debug("log queued") args = { "time": time, "message": message, "level": level, "attachment": attachment, } self.queue.put_nowait(("log", args))
python
def log(self, time, message, level=None, attachment=None): """Logs a message with attachment. The attachment is a dict of: name: name of attachment data: file content mime: content type for attachment """ logger.debug("log queued") args = { "time": time, "message": message, "level": level, "attachment": attachment, } self.queue.put_nowait(("log", args))
[ "def", "log", "(", "self", ",", "time", ",", "message", ",", "level", "=", "None", ",", "attachment", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"log queued\"", ")", "args", "=", "{", "\"time\"", ":", "time", ",", "\"message\"", ":", "message", ",", "\"level\"", ":", "level", ",", "\"attachment\"", ":", "attachment", ",", "}", "self", ".", "queue", ".", "put_nowait", "(", "(", "\"log\"", ",", "args", ")", ")" ]
Logs a message with attachment. The attachment is a dict of: name: name of attachment data: file content mime: content type for attachment
[ "Logs", "a", "message", "with", "attachment", "." ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L296-L312
15,192
reportportal/client-Python
reportportal_client/service.py
ReportPortalService.log_batch
def log_batch(self, log_data): """Logs batch of messages with attachment. Args: log_data: list of log records. log record is a dict of; time, message, level, attachment attachment is a dict of: name: name of attachment data: fileobj or content mime: content type for attachment """ url = uri_join(self.base_url, "log") attachments = [] for log_item in log_data: log_item["item_id"] = self.stack[-1] attachment = log_item.get("attachment", None) if "attachment" in log_item: del log_item["attachment"] if attachment: if not isinstance(attachment, collections.Mapping): attachment = {"data": attachment} name = attachment.get("name", str(uuid.uuid4())) log_item["file"] = {"name": name} attachments.append(("file", ( name, attachment["data"], attachment.get("mime", "application/octet-stream") ))) files = [( "json_request_part", ( None, json.dumps(log_data), "application/json" ) )] files.extend(attachments) from reportportal_client import POST_LOGBATCH_RETRY_COUNT for i in range(POST_LOGBATCH_RETRY_COUNT): try: r = self.session.post( url=url, files=files, verify=self.verify_ssl ) except KeyError: if i < POST_LOGBATCH_RETRY_COUNT - 1: continue else: raise break logger.debug("log_batch - Stack: %s", self.stack) logger.debug("log_batch response: %s", r.text) return _get_data(r)
python
def log_batch(self, log_data): """Logs batch of messages with attachment. Args: log_data: list of log records. log record is a dict of; time, message, level, attachment attachment is a dict of: name: name of attachment data: fileobj or content mime: content type for attachment """ url = uri_join(self.base_url, "log") attachments = [] for log_item in log_data: log_item["item_id"] = self.stack[-1] attachment = log_item.get("attachment", None) if "attachment" in log_item: del log_item["attachment"] if attachment: if not isinstance(attachment, collections.Mapping): attachment = {"data": attachment} name = attachment.get("name", str(uuid.uuid4())) log_item["file"] = {"name": name} attachments.append(("file", ( name, attachment["data"], attachment.get("mime", "application/octet-stream") ))) files = [( "json_request_part", ( None, json.dumps(log_data), "application/json" ) )] files.extend(attachments) from reportportal_client import POST_LOGBATCH_RETRY_COUNT for i in range(POST_LOGBATCH_RETRY_COUNT): try: r = self.session.post( url=url, files=files, verify=self.verify_ssl ) except KeyError: if i < POST_LOGBATCH_RETRY_COUNT - 1: continue else: raise break logger.debug("log_batch - Stack: %s", self.stack) logger.debug("log_batch response: %s", r.text) return _get_data(r)
[ "def", "log_batch", "(", "self", ",", "log_data", ")", ":", "url", "=", "uri_join", "(", "self", ".", "base_url", ",", "\"log\"", ")", "attachments", "=", "[", "]", "for", "log_item", "in", "log_data", ":", "log_item", "[", "\"item_id\"", "]", "=", "self", ".", "stack", "[", "-", "1", "]", "attachment", "=", "log_item", ".", "get", "(", "\"attachment\"", ",", "None", ")", "if", "\"attachment\"", "in", "log_item", ":", "del", "log_item", "[", "\"attachment\"", "]", "if", "attachment", ":", "if", "not", "isinstance", "(", "attachment", ",", "collections", ".", "Mapping", ")", ":", "attachment", "=", "{", "\"data\"", ":", "attachment", "}", "name", "=", "attachment", ".", "get", "(", "\"name\"", ",", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ")", "log_item", "[", "\"file\"", "]", "=", "{", "\"name\"", ":", "name", "}", "attachments", ".", "append", "(", "(", "\"file\"", ",", "(", "name", ",", "attachment", "[", "\"data\"", "]", ",", "attachment", ".", "get", "(", "\"mime\"", ",", "\"application/octet-stream\"", ")", ")", ")", ")", "files", "=", "[", "(", "\"json_request_part\"", ",", "(", "None", ",", "json", ".", "dumps", "(", "log_data", ")", ",", "\"application/json\"", ")", ")", "]", "files", ".", "extend", "(", "attachments", ")", "from", "reportportal_client", "import", "POST_LOGBATCH_RETRY_COUNT", "for", "i", "in", "range", "(", "POST_LOGBATCH_RETRY_COUNT", ")", ":", "try", ":", "r", "=", "self", ".", "session", ".", "post", "(", "url", "=", "url", ",", "files", "=", "files", ",", "verify", "=", "self", ".", "verify_ssl", ")", "except", "KeyError", ":", "if", "i", "<", "POST_LOGBATCH_RETRY_COUNT", "-", "1", ":", "continue", "else", ":", "raise", "break", "logger", ".", "debug", "(", "\"log_batch - Stack: %s\"", ",", "self", ".", "stack", ")", "logger", ".", "debug", "(", "\"log_batch response: %s\"", ",", "r", ".", "text", ")", "return", "_get_data", "(", "r", ")" ]
Logs batch of messages with attachment. Args: log_data: list of log records. log record is a dict of; time, message, level, attachment attachment is a dict of: name: name of attachment data: fileobj or content mime: content type for attachment
[ "Logs", "batch", "of", "messages", "with", "attachment", "." ]
8d22445d0de73f46fb23d0c0e49ac309335173ce
https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service.py#L250-L312
15,193
saltstack/pytest-salt
versioneer.py
git_versions_from_keywords
def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date, "branch": None} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None, "branch": None}
python
def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date, "branch": None} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None, "branch": None}
[ "def", "git_versions_from_keywords", "(", "keywords", ",", "tag_prefix", ",", "verbose", ")", ":", "if", "not", "keywords", ":", "raise", "NotThisMethod", "(", "\"no keywords at all, weird\"", ")", "date", "=", "keywords", ".", "get", "(", "\"date\"", ")", "if", "date", "is", "not", "None", ":", "# git-2.2.0 added \"%cI\", which expands to an ISO-8601 -compliant", "# datestamp. However we prefer \"%ci\" (which expands to an \"ISO-8601", "# -like\" string, which we must then edit to make compliant), because", "# it's been around since git-1.5.3, and it's too difficult to", "# discover which version we're using, or to work around using an", "# older one.", "date", "=", "date", ".", "strip", "(", ")", ".", "replace", "(", "\" \"", ",", "\"T\"", ",", "1", ")", ".", "replace", "(", "\" \"", ",", "\"\"", ",", "1", ")", "refnames", "=", "keywords", "[", "\"refnames\"", "]", ".", "strip", "(", ")", "if", "refnames", ".", "startswith", "(", "\"$Format\"", ")", ":", "if", "verbose", ":", "print", "(", "\"keywords are unexpanded, not using\"", ")", "raise", "NotThisMethod", "(", "\"unexpanded keywords, not a git-archive tarball\"", ")", "refs", "=", "set", "(", "[", "r", ".", "strip", "(", ")", "for", "r", "in", "refnames", ".", "strip", "(", "\"()\"", ")", ".", "split", "(", "\",\"", ")", "]", ")", "# starting in git-1.8.3, tags are listed as \"tag: foo-1.0\" instead of", "# just \"foo-1.0\". If we see a \"tag: \" prefix, prefer those.", "TAG", "=", "\"tag: \"", "tags", "=", "set", "(", "[", "r", "[", "len", "(", "TAG", ")", ":", "]", "for", "r", "in", "refs", "if", "r", ".", "startswith", "(", "TAG", ")", "]", ")", "if", "not", "tags", ":", "# Either we're using git < 1.8.3, or there really are no tags. We use", "# a heuristic: assume all version tags have a digit. The old git %d", "# expansion behaves like git log --decorate=short and strips out the", "# refs/heads/ and refs/tags/ prefixes that would let us distinguish", "# between branches and tags. By ignoring refnames without digits, we", "# filter out many common branch names like \"release\" and", "# \"stabilization\", as well as \"HEAD\" and \"master\".", "tags", "=", "set", "(", "[", "r", "for", "r", "in", "refs", "if", "re", ".", "search", "(", "r'\\d'", ",", "r", ")", "]", ")", "if", "verbose", ":", "print", "(", "\"discarding '%s', no digits\"", "%", "\",\"", ".", "join", "(", "refs", "-", "tags", ")", ")", "if", "verbose", ":", "print", "(", "\"likely tags: %s\"", "%", "\",\"", ".", "join", "(", "sorted", "(", "tags", ")", ")", ")", "for", "ref", "in", "sorted", "(", "tags", ")", ":", "# sorting will prefer e.g. \"2.0\" over \"2.0rc1\"", "if", "ref", ".", "startswith", "(", "tag_prefix", ")", ":", "r", "=", "ref", "[", "len", "(", "tag_prefix", ")", ":", "]", "if", "verbose", ":", "print", "(", "\"picking %s\"", "%", "r", ")", "return", "{", "\"version\"", ":", "r", ",", "\"full-revisionid\"", ":", "keywords", "[", "\"full\"", "]", ".", "strip", "(", ")", ",", "\"dirty\"", ":", "False", ",", "\"error\"", ":", "None", ",", "\"date\"", ":", "date", ",", "\"branch\"", ":", "None", "}", "# no suitable tags, so version is \"0+unknown\", but full hex is still there", "if", "verbose", ":", "print", "(", "\"no suitable tags, using unknown + full revision id\"", ")", "return", "{", "\"version\"", ":", "\"0+unknown\"", ",", "\"full-revisionid\"", ":", "keywords", "[", "\"full\"", "]", ".", "strip", "(", ")", ",", "\"dirty\"", ":", "False", ",", "\"error\"", ":", "\"no suitable tags\"", ",", "\"date\"", ":", "None", ",", "\"branch\"", ":", "None", "}" ]
Get version information from git keywords.
[ "Get", "version", "information", "from", "git", "keywords", "." ]
3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d
https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1042-L1094
15,194
saltstack/pytest-salt
versioneer.py
render_pep440_branch_based
def render_pep440_branch_based(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.BRANCH_gHEX[.dirty] """ replacements = ([' ', '.'], ['(', ''], [')', ''], ['\\', '.'], ['/', '.']) branch_name = pieces.get('branch') or '' if branch_name: for old, new in replacements: branch_name = branch_name.replace(old, new) else: branch_name = 'unknown_branch' if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += '.dev0' + plus_or_dot(pieces) rendered += "%d.%s.g%s" % ( pieces["distance"], branch_name, pieces['short'] ) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.%s.g%s" % ( pieces["distance"], branch_name, pieces['short'] ) if pieces["dirty"]: rendered += ".dirty" return rendered
python
def render_pep440_branch_based(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.BRANCH_gHEX[.dirty] """ replacements = ([' ', '.'], ['(', ''], [')', ''], ['\\', '.'], ['/', '.']) branch_name = pieces.get('branch') or '' if branch_name: for old, new in replacements: branch_name = branch_name.replace(old, new) else: branch_name = 'unknown_branch' if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += '.dev0' + plus_or_dot(pieces) rendered += "%d.%s.g%s" % ( pieces["distance"], branch_name, pieces['short'] ) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.%s.g%s" % ( pieces["distance"], branch_name, pieces['short'] ) if pieces["dirty"]: rendered += ".dirty" return rendered
[ "def", "render_pep440_branch_based", "(", "pieces", ")", ":", "replacements", "=", "(", "[", "' '", ",", "'.'", "]", ",", "[", "'('", ",", "''", "]", ",", "[", "')'", ",", "''", "]", ",", "[", "'\\\\'", ",", "'.'", "]", ",", "[", "'/'", ",", "'.'", "]", ")", "branch_name", "=", "pieces", ".", "get", "(", "'branch'", ")", "or", "''", "if", "branch_name", ":", "for", "old", ",", "new", "in", "replacements", ":", "branch_name", "=", "branch_name", ".", "replace", "(", "old", ",", "new", ")", "else", ":", "branch_name", "=", "'unknown_branch'", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", "+=", "'.dev0'", "+", "plus_or_dot", "(", "pieces", ")", "rendered", "+=", "\"%d.%s.g%s\"", "%", "(", "pieces", "[", "\"distance\"", "]", ",", "branch_name", ",", "pieces", "[", "'short'", "]", ")", "if", "pieces", "[", "\"dirty\"", "]", ":", "rendered", "+=", "\".dirty\"", "else", ":", "# exception #1", "rendered", "=", "\"0+untagged.%d.%s.g%s\"", "%", "(", "pieces", "[", "\"distance\"", "]", ",", "branch_name", ",", "pieces", "[", "'short'", "]", ")", "if", "pieces", "[", "\"dirty\"", "]", ":", "rendered", "+=", "\".dirty\"", "return", "rendered" ]
Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.BRANCH_gHEX[.dirty]
[ "Build", "up", "version", "string", "with", "post", "-", "release", "local", "version", "identifier", "." ]
3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d
https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1458-L1495
15,195
saltstack/pytest-salt
versioneer.py
render
def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "pep440-branch-based": rendered = render_pep440_branch_based(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")}
python
def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "pep440-branch-based": rendered = render_pep440_branch_based(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")}
[ "def", "render", "(", "pieces", ",", "style", ")", ":", "if", "pieces", "[", "\"error\"", "]", ":", "return", "{", "\"version\"", ":", "\"unknown\"", ",", "\"full-revisionid\"", ":", "pieces", ".", "get", "(", "\"long\"", ")", ",", "\"dirty\"", ":", "None", ",", "\"error\"", ":", "pieces", "[", "\"error\"", "]", ",", "\"date\"", ":", "None", "}", "if", "not", "style", "or", "style", "==", "\"default\"", ":", "style", "=", "\"pep440\"", "# the default", "if", "style", "==", "\"pep440\"", ":", "rendered", "=", "render_pep440", "(", "pieces", ")", "elif", "style", "==", "\"pep440-pre\"", ":", "rendered", "=", "render_pep440_pre", "(", "pieces", ")", "elif", "style", "==", "\"pep440-post\"", ":", "rendered", "=", "render_pep440_post", "(", "pieces", ")", "elif", "style", "==", "\"pep440-old\"", ":", "rendered", "=", "render_pep440_old", "(", "pieces", ")", "elif", "style", "==", "\"pep440-branch-based\"", ":", "rendered", "=", "render_pep440_branch_based", "(", "pieces", ")", "elif", "style", "==", "\"git-describe\"", ":", "rendered", "=", "render_git_describe", "(", "pieces", ")", "elif", "style", "==", "\"git-describe-long\"", ":", "rendered", "=", "render_git_describe_long", "(", "pieces", ")", "else", ":", "raise", "ValueError", "(", "\"unknown style '%s'\"", "%", "style", ")", "return", "{", "\"version\"", ":", "rendered", ",", "\"full-revisionid\"", ":", "pieces", "[", "\"long\"", "]", ",", "\"dirty\"", ":", "pieces", "[", "\"dirty\"", "]", ",", "\"error\"", ":", "None", ",", "\"date\"", ":", "pieces", ".", "get", "(", "\"date\"", ")", "}" ]
Render the given version pieces into the requested style.
[ "Render", "the", "given", "version", "pieces", "into", "the", "requested", "style", "." ]
3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d
https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1498-L1529
15,196
saltstack/pytest-salt
versioneer.py
do_setup
def do_setup(): """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET_RE.search(old) is None: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0
python
def do_setup(): """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET_RE.search(old) is None: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0
[ "def", "do_setup", "(", ")", ":", "root", "=", "get_root", "(", ")", "try", ":", "cfg", "=", "get_config_from_root", "(", "root", ")", "except", "(", "EnvironmentError", ",", "configparser", ".", "NoSectionError", ",", "configparser", ".", "NoOptionError", ")", "as", "e", ":", "if", "isinstance", "(", "e", ",", "(", "EnvironmentError", ",", "configparser", ".", "NoSectionError", ")", ")", ":", "print", "(", "\"Adding sample versioneer config to setup.cfg\"", ",", "file", "=", "sys", ".", "stderr", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "root", ",", "\"setup.cfg\"", ")", ",", "\"a\"", ")", "as", "f", ":", "f", ".", "write", "(", "SAMPLE_CONFIG", ")", "print", "(", "CONFIG_ERROR", ",", "file", "=", "sys", ".", "stderr", ")", "return", "1", "print", "(", "\" creating %s\"", "%", "cfg", ".", "versionfile_source", ")", "with", "open", "(", "cfg", ".", "versionfile_source", ",", "\"w\"", ")", "as", "f", ":", "LONG", "=", "LONG_VERSION_PY", "[", "cfg", ".", "VCS", "]", "f", ".", "write", "(", "LONG", "%", "{", "\"DOLLAR\"", ":", "\"$\"", ",", "\"STYLE\"", ":", "cfg", ".", "style", ",", "\"TAG_PREFIX\"", ":", "cfg", ".", "tag_prefix", ",", "\"PARENTDIR_PREFIX\"", ":", "cfg", ".", "parentdir_prefix", ",", "\"VERSIONFILE_SOURCE\"", ":", "cfg", ".", "versionfile_source", ",", "}", ")", "ipy", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "cfg", ".", "versionfile_source", ")", ",", "\"__init__.py\"", ")", "if", "os", ".", "path", ".", "exists", "(", "ipy", ")", ":", "try", ":", "with", "open", "(", "ipy", ",", "\"r\"", ")", "as", "f", ":", "old", "=", "f", ".", "read", "(", ")", "except", "EnvironmentError", ":", "old", "=", "\"\"", "if", "INIT_PY_SNIPPET_RE", ".", "search", "(", "old", ")", "is", "None", ":", "print", "(", "\" appending to %s\"", "%", "ipy", ")", "with", "open", "(", "ipy", ",", "\"a\"", ")", "as", "f", ":", "f", ".", "write", "(", "INIT_PY_SNIPPET", ")", "else", ":", "print", "(", "\" %s unmodified\"", "%", "ipy", ")", "else", ":", "print", "(", "\" %s doesn't exist, ok\"", "%", "ipy", ")", "ipy", "=", "None", "# Make sure both the top-level \"versioneer.py\" and versionfile_source", "# (PKG/_version.py, used by runtime code) are in MANIFEST.in, so", "# they'll be copied into source distributions. Pip won't be able to", "# install the package without this.", "manifest_in", "=", "os", ".", "path", ".", "join", "(", "root", ",", "\"MANIFEST.in\"", ")", "simple_includes", "=", "set", "(", ")", "try", ":", "with", "open", "(", "manifest_in", ",", "\"r\"", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "line", ".", "startswith", "(", "\"include \"", ")", ":", "for", "include", "in", "line", ".", "split", "(", ")", "[", "1", ":", "]", ":", "simple_includes", ".", "add", "(", "include", ")", "except", "EnvironmentError", ":", "pass", "# That doesn't cover everything MANIFEST.in can do", "# (http://docs.python.org/2/distutils/sourcedist.html#commands), so", "# it might give some false negatives. Appending redundant 'include'", "# lines is safe, though.", "if", "\"versioneer.py\"", "not", "in", "simple_includes", ":", "print", "(", "\" appending 'versioneer.py' to MANIFEST.in\"", ")", "with", "open", "(", "manifest_in", ",", "\"a\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"include versioneer.py\\n\"", ")", "else", ":", "print", "(", "\" 'versioneer.py' already in MANIFEST.in\"", ")", "if", "cfg", ".", "versionfile_source", "not", "in", "simple_includes", ":", "print", "(", "\" appending versionfile_source ('%s') to MANIFEST.in\"", "%", "cfg", ".", "versionfile_source", ")", "with", "open", "(", "manifest_in", ",", "\"a\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"include %s\\n\"", "%", "cfg", ".", "versionfile_source", ")", "else", ":", "print", "(", "\" versionfile_source already in MANIFEST.in\"", ")", "# Make VCS-specific changes. For git, this means creating/changing", "# .gitattributes to mark _version.py for export-subst keyword", "# substitution.", "do_vcs_install", "(", "manifest_in", ",", "cfg", ".", "versionfile_source", ",", "ipy", ")", "return", "0" ]
Do main VCS-independent setup function for installing Versioneer.
[ "Do", "main", "VCS", "-", "independent", "setup", "function", "for", "installing", "Versioneer", "." ]
3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d
https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1846-L1925
15,197
saltstack/pytest-salt
versioneer.py
scan_setup_py
def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass(" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors
python
def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass(" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors
[ "def", "scan_setup_py", "(", ")", ":", "found", "=", "set", "(", ")", "setters", "=", "False", "errors", "=", "0", "with", "open", "(", "\"setup.py\"", ",", "\"r\"", ")", "as", "f", ":", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "if", "\"import versioneer\"", "in", "line", ":", "found", ".", "add", "(", "\"import\"", ")", "if", "\"versioneer.get_cmdclass(\"", "in", "line", ":", "found", ".", "add", "(", "\"cmdclass\"", ")", "if", "\"versioneer.get_version()\"", "in", "line", ":", "found", ".", "add", "(", "\"get_version\"", ")", "if", "\"versioneer.VCS\"", "in", "line", ":", "setters", "=", "True", "if", "\"versioneer.versionfile_source\"", "in", "line", ":", "setters", "=", "True", "if", "len", "(", "found", ")", "!=", "3", ":", "print", "(", "\"\"", ")", "print", "(", "\"Your setup.py appears to be missing some important items\"", ")", "print", "(", "\"(but I might be wrong). Please make sure it has something\"", ")", "print", "(", "\"roughly like the following:\"", ")", "print", "(", "\"\"", ")", "print", "(", "\" import versioneer\"", ")", "print", "(", "\" setup( version=versioneer.get_version(),\"", ")", "print", "(", "\" cmdclass=versioneer.get_cmdclass(), ...)\"", ")", "print", "(", "\"\"", ")", "errors", "+=", "1", "if", "setters", ":", "print", "(", "\"You should remove lines like 'versioneer.VCS = ' and\"", ")", "print", "(", "\"'versioneer.versionfile_source = ' . This configuration\"", ")", "print", "(", "\"now lives in setup.cfg, and should be removed from setup.py\"", ")", "print", "(", "\"\"", ")", "errors", "+=", "1", "return", "errors" ]
Validate the contents of setup.py against Versioneer's expectations.
[ "Validate", "the", "contents", "of", "setup", ".", "py", "against", "Versioneer", "s", "expectations", "." ]
3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d
https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1928-L1962
15,198
saltstack/pytest-salt
setup.py
read
def read(fname): ''' Read a file from the directory where setup.py resides ''' file_path = os.path.join(SETUP_DIRNAME, fname) with codecs.open(file_path, encoding='utf-8') as rfh: return rfh.read()
python
def read(fname): ''' Read a file from the directory where setup.py resides ''' file_path = os.path.join(SETUP_DIRNAME, fname) with codecs.open(file_path, encoding='utf-8') as rfh: return rfh.read()
[ "def", "read", "(", "fname", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "SETUP_DIRNAME", ",", "fname", ")", "with", "codecs", ".", "open", "(", "file_path", ",", "encoding", "=", "'utf-8'", ")", "as", "rfh", ":", "return", "rfh", ".", "read", "(", ")" ]
Read a file from the directory where setup.py resides
[ "Read", "a", "file", "from", "the", "directory", "where", "setup", ".", "py", "resides" ]
3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d
https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/setup.py#L23-L29
15,199
jeongyoonlee/Kaggler
kaggler/model/nn.py
NN.func
def func(self, w, *args): """Return the costs of the neural network for predictions. Args: w (array of float): weight vectors such that: w[:-h1] -- weights between the input and h layers w[-h1:] -- weights between the h and output layers args: features (args[0]) and target (args[1]) Returns: combined cost of RMSE, L1, and L2 regularization """ x0 = args[0] x1 = args[1] n0 = x0.shape[0] n1 = x1.shape[0] # n -- number of pairs to evaluate n = max(n0, n1) * 10 idx0 = np.random.choice(range(n0), size=n) idx1 = np.random.choice(range(n1), size=n) # b -- bias for the input and h layers b0 = np.ones((n0, 1)) b1 = np.ones((n1, 1)) i1 = self.i + 1 h = self.h h1 = h + 1 # Predict for features -- cannot use predict_raw() because here # different weights can be used. if sparse.issparse(x0): p0 = np.hstack((sigm(sparse.hstack((x0, b0)).dot(w[:-h1].reshape( i1, h))), b0)).dot(w[-h1:].reshape(h1, 1)) p1 = np.hstack((sigm(sparse.hstack((x1, b1)).dot(w[:-h1].reshape( i1, h))), b1)).dot(w[-h1:].reshape(h1, 1)) else: p0 = np.hstack((sigm(np.hstack((x0, b0)).dot(w[:-h1].reshape( i1, h))), b0)).dot(w[-h1:].reshape(h1, 1)) p1 = np.hstack((sigm(np.hstack((x1, b1)).dot(w[:-h1].reshape( i1, h))), b1)).dot(w[-h1:].reshape(h1, 1)) p0 = p0[idx0] p1 = p1[idx1] # Return the cost that consists of the sum of squared error + # L2-regularization for weights between the input and h layers + # L2-regularization for weights between the h and output layers. #return .5 * (sum((1 - sigm(p1 - p0)) ** 2) + self.l1 * sum(w[:-h1] ** 2) + return .5 * (sum((1 - p1 + p0) ** 2) / n + self.l1 * sum(w[:-h1] ** 2) / (i1 * h) + self.l2 * sum(w[-h1:] ** 2) / h1)
python
def func(self, w, *args): """Return the costs of the neural network for predictions. Args: w (array of float): weight vectors such that: w[:-h1] -- weights between the input and h layers w[-h1:] -- weights between the h and output layers args: features (args[0]) and target (args[1]) Returns: combined cost of RMSE, L1, and L2 regularization """ x0 = args[0] x1 = args[1] n0 = x0.shape[0] n1 = x1.shape[0] # n -- number of pairs to evaluate n = max(n0, n1) * 10 idx0 = np.random.choice(range(n0), size=n) idx1 = np.random.choice(range(n1), size=n) # b -- bias for the input and h layers b0 = np.ones((n0, 1)) b1 = np.ones((n1, 1)) i1 = self.i + 1 h = self.h h1 = h + 1 # Predict for features -- cannot use predict_raw() because here # different weights can be used. if sparse.issparse(x0): p0 = np.hstack((sigm(sparse.hstack((x0, b0)).dot(w[:-h1].reshape( i1, h))), b0)).dot(w[-h1:].reshape(h1, 1)) p1 = np.hstack((sigm(sparse.hstack((x1, b1)).dot(w[:-h1].reshape( i1, h))), b1)).dot(w[-h1:].reshape(h1, 1)) else: p0 = np.hstack((sigm(np.hstack((x0, b0)).dot(w[:-h1].reshape( i1, h))), b0)).dot(w[-h1:].reshape(h1, 1)) p1 = np.hstack((sigm(np.hstack((x1, b1)).dot(w[:-h1].reshape( i1, h))), b1)).dot(w[-h1:].reshape(h1, 1)) p0 = p0[idx0] p1 = p1[idx1] # Return the cost that consists of the sum of squared error + # L2-regularization for weights between the input and h layers + # L2-regularization for weights between the h and output layers. #return .5 * (sum((1 - sigm(p1 - p0)) ** 2) + self.l1 * sum(w[:-h1] ** 2) + return .5 * (sum((1 - p1 + p0) ** 2) / n + self.l1 * sum(w[:-h1] ** 2) / (i1 * h) + self.l2 * sum(w[-h1:] ** 2) / h1)
[ "def", "func", "(", "self", ",", "w", ",", "*", "args", ")", ":", "x0", "=", "args", "[", "0", "]", "x1", "=", "args", "[", "1", "]", "n0", "=", "x0", ".", "shape", "[", "0", "]", "n1", "=", "x1", ".", "shape", "[", "0", "]", "# n -- number of pairs to evaluate", "n", "=", "max", "(", "n0", ",", "n1", ")", "*", "10", "idx0", "=", "np", ".", "random", ".", "choice", "(", "range", "(", "n0", ")", ",", "size", "=", "n", ")", "idx1", "=", "np", ".", "random", ".", "choice", "(", "range", "(", "n1", ")", ",", "size", "=", "n", ")", "# b -- bias for the input and h layers", "b0", "=", "np", ".", "ones", "(", "(", "n0", ",", "1", ")", ")", "b1", "=", "np", ".", "ones", "(", "(", "n1", ",", "1", ")", ")", "i1", "=", "self", ".", "i", "+", "1", "h", "=", "self", ".", "h", "h1", "=", "h", "+", "1", "# Predict for features -- cannot use predict_raw() because here", "# different weights can be used.", "if", "sparse", ".", "issparse", "(", "x0", ")", ":", "p0", "=", "np", ".", "hstack", "(", "(", "sigm", "(", "sparse", ".", "hstack", "(", "(", "x0", ",", "b0", ")", ")", ".", "dot", "(", "w", "[", ":", "-", "h1", "]", ".", "reshape", "(", "i1", ",", "h", ")", ")", ")", ",", "b0", ")", ")", ".", "dot", "(", "w", "[", "-", "h1", ":", "]", ".", "reshape", "(", "h1", ",", "1", ")", ")", "p1", "=", "np", ".", "hstack", "(", "(", "sigm", "(", "sparse", ".", "hstack", "(", "(", "x1", ",", "b1", ")", ")", ".", "dot", "(", "w", "[", ":", "-", "h1", "]", ".", "reshape", "(", "i1", ",", "h", ")", ")", ")", ",", "b1", ")", ")", ".", "dot", "(", "w", "[", "-", "h1", ":", "]", ".", "reshape", "(", "h1", ",", "1", ")", ")", "else", ":", "p0", "=", "np", ".", "hstack", "(", "(", "sigm", "(", "np", ".", "hstack", "(", "(", "x0", ",", "b0", ")", ")", ".", "dot", "(", "w", "[", ":", "-", "h1", "]", ".", "reshape", "(", "i1", ",", "h", ")", ")", ")", ",", "b0", ")", ")", ".", "dot", "(", "w", "[", "-", "h1", ":", "]", ".", "reshape", "(", "h1", ",", "1", ")", ")", "p1", "=", "np", ".", "hstack", "(", "(", "sigm", "(", "np", ".", "hstack", "(", "(", "x1", ",", "b1", ")", ")", ".", "dot", "(", "w", "[", ":", "-", "h1", "]", ".", "reshape", "(", "i1", ",", "h", ")", ")", ")", ",", "b1", ")", ")", ".", "dot", "(", "w", "[", "-", "h1", ":", "]", ".", "reshape", "(", "h1", ",", "1", ")", ")", "p0", "=", "p0", "[", "idx0", "]", "p1", "=", "p1", "[", "idx1", "]", "# Return the cost that consists of the sum of squared error +", "# L2-regularization for weights between the input and h layers +", "# L2-regularization for weights between the h and output layers.", "#return .5 * (sum((1 - sigm(p1 - p0)) ** 2) + self.l1 * sum(w[:-h1] ** 2) +", "return", ".5", "*", "(", "sum", "(", "(", "1", "-", "p1", "+", "p0", ")", "**", "2", ")", "/", "n", "+", "self", ".", "l1", "*", "sum", "(", "w", "[", ":", "-", "h1", "]", "**", "2", ")", "/", "(", "i1", "*", "h", ")", "+", "self", ".", "l2", "*", "sum", "(", "w", "[", "-", "h1", ":", "]", "**", "2", ")", "/", "h1", ")" ]
Return the costs of the neural network for predictions. Args: w (array of float): weight vectors such that: w[:-h1] -- weights between the input and h layers w[-h1:] -- weights between the h and output layers args: features (args[0]) and target (args[1]) Returns: combined cost of RMSE, L1, and L2 regularization
[ "Return", "the", "costs", "of", "the", "neural", "network", "for", "predictions", "." ]
20661105b61958dc9a3c529c1d3b2313ab23ae32
https://github.com/jeongyoonlee/Kaggler/blob/20661105b61958dc9a3c529c1d3b2313ab23ae32/kaggler/model/nn.py#L204-L256