repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
deathbeds/importnb
src/importnb/ipython_extension.py
IPYTHON_MAIN
def IPYTHON_MAIN(): """Decide if the Ipython command line is running code.""" import pkg_resources runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython").__name__ )
python
def IPYTHON_MAIN(): """Decide if the Ipython command line is running code.""" import pkg_resources runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython").__name__ )
[ "def", "IPYTHON_MAIN", "(", ")", ":", "import", "pkg_resources", "runner_frame", "=", "inspect", ".", "getouterframes", "(", "inspect", ".", "currentframe", "(", ")", ")", "[", "-", "2", "]", "return", "(", "getattr", "(", "runner_frame", ",", "\"function\"", ",", "None", ")", "==", "pkg_resources", ".", "load_entry_point", "(", "\"ipython\"", ",", "\"console_scripts\"", ",", "\"ipython\"", ")", ".", "__name__", ")" ]
Decide if the Ipython command line is running code.
[ "Decide", "if", "the", "Ipython", "command", "line", "is", "running", "code", "." ]
train
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/ipython_extension.py#L85-L93
nuagenetworks/bambou
bambou/nurest_modelcontroller.py
NURESTModelController.register_model
def register_model(cls, model): """ Register a model class according to its remote name Args: model: the model to register """ rest_name = model.rest_name resource_name = model.resource_name if rest_name not in cls._model_rest_name_registry: cls._model_rest_name_registry[rest_name] = [model] cls._model_resource_name_registry[resource_name] = [model] elif model not in cls._model_rest_name_registry[rest_name]: cls._model_rest_name_registry[rest_name].append(model) cls._model_resource_name_registry[resource_name].append(model)
python
def register_model(cls, model): """ Register a model class according to its remote name Args: model: the model to register """ rest_name = model.rest_name resource_name = model.resource_name if rest_name not in cls._model_rest_name_registry: cls._model_rest_name_registry[rest_name] = [model] cls._model_resource_name_registry[resource_name] = [model] elif model not in cls._model_rest_name_registry[rest_name]: cls._model_rest_name_registry[rest_name].append(model) cls._model_resource_name_registry[resource_name].append(model)
[ "def", "register_model", "(", "cls", ",", "model", ")", ":", "rest_name", "=", "model", ".", "rest_name", "resource_name", "=", "model", ".", "resource_name", "if", "rest_name", "not", "in", "cls", ".", "_model_rest_name_registry", ":", "cls", ".", "_model_rest_name_registry", "[", "rest_name", "]", "=", "[", "model", "]", "cls", ".", "_model_resource_name_registry", "[", "resource_name", "]", "=", "[", "model", "]", "elif", "model", "not", "in", "cls", ".", "_model_rest_name_registry", "[", "rest_name", "]", ":", "cls", ".", "_model_rest_name_registry", "[", "rest_name", "]", ".", "append", "(", "model", ")", "cls", ".", "_model_resource_name_registry", "[", "resource_name", "]", ".", "append", "(", "model", ")" ]
Register a model class according to its remote name Args: model: the model to register
[ "Register", "a", "model", "class", "according", "to", "its", "remote", "name" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_modelcontroller.py#L37-L54
nuagenetworks/bambou
bambou/nurest_modelcontroller.py
NURESTModelController.get_first_model_with_rest_name
def get_first_model_with_rest_name(cls, rest_name): """ Get the first model corresponding to a rest_name Args: rest_name: the rest name """ models = cls.get_models_with_rest_name(rest_name) if len(models) > 0: return models[0] return None
python
def get_first_model_with_rest_name(cls, rest_name): """ Get the first model corresponding to a rest_name Args: rest_name: the rest name """ models = cls.get_models_with_rest_name(rest_name) if len(models) > 0: return models[0] return None
[ "def", "get_first_model_with_rest_name", "(", "cls", ",", "rest_name", ")", ":", "models", "=", "cls", ".", "get_models_with_rest_name", "(", "rest_name", ")", "if", "len", "(", "models", ")", ">", "0", ":", "return", "models", "[", "0", "]", "return", "None" ]
Get the first model corresponding to a rest_name Args: rest_name: the rest name
[ "Get", "the", "first", "model", "corresponding", "to", "a", "rest_name" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_modelcontroller.py#L87-L99
nuagenetworks/bambou
bambou/nurest_modelcontroller.py
NURESTModelController.get_first_model_with_resource_name
def get_first_model_with_resource_name(cls, resource_name): """ Get the first model corresponding to a resource_name Args: resource_name: the resource name """ models = cls.get_models_with_resource_name(resource_name) if len(models) > 0: return models[0] return None
python
def get_first_model_with_resource_name(cls, resource_name): """ Get the first model corresponding to a resource_name Args: resource_name: the resource name """ models = cls.get_models_with_resource_name(resource_name) if len(models) > 0: return models[0] return None
[ "def", "get_first_model_with_resource_name", "(", "cls", ",", "resource_name", ")", ":", "models", "=", "cls", ".", "get_models_with_resource_name", "(", "resource_name", ")", "if", "len", "(", "models", ")", ">", "0", ":", "return", "models", "[", "0", "]", "return", "None" ]
Get the first model corresponding to a resource_name Args: resource_name: the resource name
[ "Get", "the", "first", "model", "corresponding", "to", "a", "resource_name" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_modelcontroller.py#L121-L133
zeromake/aiosqlite3
aiosqlite3/sqlite_thread.py
SqliteThread.run
def run(self): """ 执行任务 """ while not self._stoped: self._tx_event.wait() self._tx_event.clear() try: func = self._tx_queue.get_nowait() if isinstance(func, str): self._stoped = True self._rx_queue.put('closed') self.notice() break except Empty: # pragma: no cover continue try: result = func() self._rx_queue.put(result) except Exception as e: self._rx_queue.put(e) self.notice() else: # pragma: no cover pass
python
def run(self): """ 执行任务 """ while not self._stoped: self._tx_event.wait() self._tx_event.clear() try: func = self._tx_queue.get_nowait() if isinstance(func, str): self._stoped = True self._rx_queue.put('closed') self.notice() break except Empty: # pragma: no cover continue try: result = func() self._rx_queue.put(result) except Exception as e: self._rx_queue.put(e) self.notice() else: # pragma: no cover pass
[ "def", "run", "(", "self", ")", ":", "while", "not", "self", ".", "_stoped", ":", "self", ".", "_tx_event", ".", "wait", "(", ")", "self", ".", "_tx_event", ".", "clear", "(", ")", "try", ":", "func", "=", "self", ".", "_tx_queue", ".", "get_nowait", "(", ")", "if", "isinstance", "(", "func", ",", "str", ")", ":", "self", ".", "_stoped", "=", "True", "self", ".", "_rx_queue", ".", "put", "(", "'closed'", ")", "self", ".", "notice", "(", ")", "break", "except", "Empty", ":", "# pragma: no cover", "continue", "try", ":", "result", "=", "func", "(", ")", "self", ".", "_rx_queue", ".", "put", "(", "result", ")", "except", "Exception", "as", "e", ":", "self", ".", "_rx_queue", ".", "put", "(", "e", ")", "self", ".", "notice", "(", ")", "else", ":", "# pragma: no cover", "pass" ]
执行任务
[ "执行任务" ]
train
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sqlite_thread.py#L22-L47
OpenDataScienceLab/skdata
skdata/widgets.py
SkDataWidget.build_layout
def build_layout(self, dset_id: str): """ :param dset_id: :return: """ all_fields = list(self.get_data(dset_id=dset_id).keys()) try: field_reference = self.skd[dset_id].attrs('target') except: field_reference = all_fields[0] fields_comparison = [all_fields[1]] # chart type widget self.register_widget( chart_type=widgets.RadioButtons( options=['individual', 'grouped'], value='individual', description='Chart Type:' ) ) # bins widget self.register_widget( bins=IntSlider( description='Bins:', min=2, max=10, value=2, continuous_update=False ) ) # fields comparison widget self.register_widget( xs=widgets.SelectMultiple( description='Xs:', options=[f for f in all_fields if not f == field_reference], value=fields_comparison ) ) # field reference widget self.register_widget( y=widgets.Dropdown( description='Y:', options=all_fields, value=field_reference ) ) # used to internal flow control y_changed = [False] self.register_widget( box_filter_panel=widgets.VBox([ self._('y'), self._('xs'), self._('bins') ]) ) # layout widgets self.register_widget( table=widgets.HTML(), chart=widgets.HTML() ) self.register_widget(vbox_chart=widgets.VBox([ self._('chart_type'), self._('chart') ])) self.register_widget( tab=widgets.Tab( children=[ self._('box_filter_panel'), self._('table'), self._('vbox_chart') ] ) ) self.register_widget(dashboard=widgets.HBox([self._('tab')])) # observe hooks def w_y_change(change: dict): """ When y field was changed xs field should be updated and data table and chart should be displayed/updated. :param change: :return: """ # remove reference field from the comparison field list _xs = [ f for f in all_fields if not f == change['new'] ] y_changed[0] = True # flow control variable _xs_value = list(self._('xs').value) if change['new'] in self._('xs').value: _xs_value.pop(_xs_value.index(change['new'])) if not _xs_value: _xs_value = [_xs[0]] self._('xs').options = _xs self._('xs').value = _xs_value self._display_result(y=change['new'], dset_id=dset_id) y_changed[0] = False # flow control variable # widgets registration # change tab settings self._('tab').set_title(0, 'Filter') self._('tab').set_title(1, 'Data') self._('tab').set_title(2, 'Chart') # data panel self._('table').value = '...' # chart panel self._('chart').value = '...' # create observe callbacks self._('bins').observe( lambda change: ( self._display_result(bins=change['new'], dset_id=dset_id) ), 'value' ) self._('y').observe(w_y_change, 'value') # execute display result if 'y' was not changing. self._('xs').observe( lambda change: ( self._display_result(xs=change['new'], dset_id=dset_id) if not y_changed[0] else None ), 'value' ) self._('chart_type').observe( lambda change: ( self._display_result(chart_type=change['new'], dset_id=dset_id) ), 'value' )
python
def build_layout(self, dset_id: str): """ :param dset_id: :return: """ all_fields = list(self.get_data(dset_id=dset_id).keys()) try: field_reference = self.skd[dset_id].attrs('target') except: field_reference = all_fields[0] fields_comparison = [all_fields[1]] # chart type widget self.register_widget( chart_type=widgets.RadioButtons( options=['individual', 'grouped'], value='individual', description='Chart Type:' ) ) # bins widget self.register_widget( bins=IntSlider( description='Bins:', min=2, max=10, value=2, continuous_update=False ) ) # fields comparison widget self.register_widget( xs=widgets.SelectMultiple( description='Xs:', options=[f for f in all_fields if not f == field_reference], value=fields_comparison ) ) # field reference widget self.register_widget( y=widgets.Dropdown( description='Y:', options=all_fields, value=field_reference ) ) # used to internal flow control y_changed = [False] self.register_widget( box_filter_panel=widgets.VBox([ self._('y'), self._('xs'), self._('bins') ]) ) # layout widgets self.register_widget( table=widgets.HTML(), chart=widgets.HTML() ) self.register_widget(vbox_chart=widgets.VBox([ self._('chart_type'), self._('chart') ])) self.register_widget( tab=widgets.Tab( children=[ self._('box_filter_panel'), self._('table'), self._('vbox_chart') ] ) ) self.register_widget(dashboard=widgets.HBox([self._('tab')])) # observe hooks def w_y_change(change: dict): """ When y field was changed xs field should be updated and data table and chart should be displayed/updated. :param change: :return: """ # remove reference field from the comparison field list _xs = [ f for f in all_fields if not f == change['new'] ] y_changed[0] = True # flow control variable _xs_value = list(self._('xs').value) if change['new'] in self._('xs').value: _xs_value.pop(_xs_value.index(change['new'])) if not _xs_value: _xs_value = [_xs[0]] self._('xs').options = _xs self._('xs').value = _xs_value self._display_result(y=change['new'], dset_id=dset_id) y_changed[0] = False # flow control variable # widgets registration # change tab settings self._('tab').set_title(0, 'Filter') self._('tab').set_title(1, 'Data') self._('tab').set_title(2, 'Chart') # data panel self._('table').value = '...' # chart panel self._('chart').value = '...' # create observe callbacks self._('bins').observe( lambda change: ( self._display_result(bins=change['new'], dset_id=dset_id) ), 'value' ) self._('y').observe(w_y_change, 'value') # execute display result if 'y' was not changing. self._('xs').observe( lambda change: ( self._display_result(xs=change['new'], dset_id=dset_id) if not y_changed[0] else None ), 'value' ) self._('chart_type').observe( lambda change: ( self._display_result(chart_type=change['new'], dset_id=dset_id) ), 'value' )
[ "def", "build_layout", "(", "self", ",", "dset_id", ":", "str", ")", ":", "all_fields", "=", "list", "(", "self", ".", "get_data", "(", "dset_id", "=", "dset_id", ")", ".", "keys", "(", ")", ")", "try", ":", "field_reference", "=", "self", ".", "skd", "[", "dset_id", "]", ".", "attrs", "(", "'target'", ")", "except", ":", "field_reference", "=", "all_fields", "[", "0", "]", "fields_comparison", "=", "[", "all_fields", "[", "1", "]", "]", "# chart type widget", "self", ".", "register_widget", "(", "chart_type", "=", "widgets", ".", "RadioButtons", "(", "options", "=", "[", "'individual'", ",", "'grouped'", "]", ",", "value", "=", "'individual'", ",", "description", "=", "'Chart Type:'", ")", ")", "# bins widget", "self", ".", "register_widget", "(", "bins", "=", "IntSlider", "(", "description", "=", "'Bins:'", ",", "min", "=", "2", ",", "max", "=", "10", ",", "value", "=", "2", ",", "continuous_update", "=", "False", ")", ")", "# fields comparison widget", "self", ".", "register_widget", "(", "xs", "=", "widgets", ".", "SelectMultiple", "(", "description", "=", "'Xs:'", ",", "options", "=", "[", "f", "for", "f", "in", "all_fields", "if", "not", "f", "==", "field_reference", "]", ",", "value", "=", "fields_comparison", ")", ")", "# field reference widget", "self", ".", "register_widget", "(", "y", "=", "widgets", ".", "Dropdown", "(", "description", "=", "'Y:'", ",", "options", "=", "all_fields", ",", "value", "=", "field_reference", ")", ")", "# used to internal flow control", "y_changed", "=", "[", "False", "]", "self", ".", "register_widget", "(", "box_filter_panel", "=", "widgets", ".", "VBox", "(", "[", "self", ".", "_", "(", "'y'", ")", ",", "self", ".", "_", "(", "'xs'", ")", ",", "self", ".", "_", "(", "'bins'", ")", "]", ")", ")", "# layout widgets", "self", ".", "register_widget", "(", "table", "=", "widgets", ".", "HTML", "(", ")", ",", "chart", "=", "widgets", ".", "HTML", "(", ")", ")", "self", ".", "register_widget", "(", "vbox_chart", "=", "widgets", ".", "VBox", "(", "[", "self", ".", "_", "(", "'chart_type'", ")", ",", "self", ".", "_", "(", "'chart'", ")", "]", ")", ")", "self", ".", "register_widget", "(", "tab", "=", "widgets", ".", "Tab", "(", "children", "=", "[", "self", ".", "_", "(", "'box_filter_panel'", ")", ",", "self", ".", "_", "(", "'table'", ")", ",", "self", ".", "_", "(", "'vbox_chart'", ")", "]", ")", ")", "self", ".", "register_widget", "(", "dashboard", "=", "widgets", ".", "HBox", "(", "[", "self", ".", "_", "(", "'tab'", ")", "]", ")", ")", "# observe hooks", "def", "w_y_change", "(", "change", ":", "dict", ")", ":", "\"\"\"\n When y field was changed xs field should be updated and data table\n and chart should be displayed/updated.\n\n :param change:\n :return:\n \"\"\"", "# remove reference field from the comparison field list", "_xs", "=", "[", "f", "for", "f", "in", "all_fields", "if", "not", "f", "==", "change", "[", "'new'", "]", "]", "y_changed", "[", "0", "]", "=", "True", "# flow control variable", "_xs_value", "=", "list", "(", "self", ".", "_", "(", "'xs'", ")", ".", "value", ")", "if", "change", "[", "'new'", "]", "in", "self", ".", "_", "(", "'xs'", ")", ".", "value", ":", "_xs_value", ".", "pop", "(", "_xs_value", ".", "index", "(", "change", "[", "'new'", "]", ")", ")", "if", "not", "_xs_value", ":", "_xs_value", "=", "[", "_xs", "[", "0", "]", "]", "self", ".", "_", "(", "'xs'", ")", ".", "options", "=", "_xs", "self", ".", "_", "(", "'xs'", ")", ".", "value", "=", "_xs_value", "self", ".", "_display_result", "(", "y", "=", "change", "[", "'new'", "]", ",", "dset_id", "=", "dset_id", ")", "y_changed", "[", "0", "]", "=", "False", "# flow control variable", "# widgets registration", "# change tab settings", "self", ".", "_", "(", "'tab'", ")", ".", "set_title", "(", "0", ",", "'Filter'", ")", "self", ".", "_", "(", "'tab'", ")", ".", "set_title", "(", "1", ",", "'Data'", ")", "self", ".", "_", "(", "'tab'", ")", ".", "set_title", "(", "2", ",", "'Chart'", ")", "# data panel", "self", ".", "_", "(", "'table'", ")", ".", "value", "=", "'...'", "# chart panel", "self", ".", "_", "(", "'chart'", ")", ".", "value", "=", "'...'", "# create observe callbacks", "self", ".", "_", "(", "'bins'", ")", ".", "observe", "(", "lambda", "change", ":", "(", "self", ".", "_display_result", "(", "bins", "=", "change", "[", "'new'", "]", ",", "dset_id", "=", "dset_id", ")", ")", ",", "'value'", ")", "self", ".", "_", "(", "'y'", ")", ".", "observe", "(", "w_y_change", ",", "'value'", ")", "# execute display result if 'y' was not changing.", "self", ".", "_", "(", "'xs'", ")", ".", "observe", "(", "lambda", "change", ":", "(", "self", ".", "_display_result", "(", "xs", "=", "change", "[", "'new'", "]", ",", "dset_id", "=", "dset_id", ")", "if", "not", "y_changed", "[", "0", "]", "else", "None", ")", ",", "'value'", ")", "self", ".", "_", "(", "'chart_type'", ")", ".", "observe", "(", "lambda", "change", ":", "(", "self", ".", "_display_result", "(", "chart_type", "=", "change", "[", "'new'", "]", ",", "dset_id", "=", "dset_id", ")", ")", ",", "'value'", ")" ]
:param dset_id: :return:
[ ":", "param", "dset_id", ":", ":", "return", ":" ]
train
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/widgets.py#L108-L249
OpenDataScienceLab/skdata
skdata/widgets.py
SkDataWidget.display
def display(self, dset_id: str): """ :param dset_id: :return: """ # update result self.skd[dset_id].compute() # build layout self.build_layout(dset_id=dset_id) # display widgets display(self._('dashboard')) # display data table and chart self._display_result(dset_id=dset_id)
python
def display(self, dset_id: str): """ :param dset_id: :return: """ # update result self.skd[dset_id].compute() # build layout self.build_layout(dset_id=dset_id) # display widgets display(self._('dashboard')) # display data table and chart self._display_result(dset_id=dset_id)
[ "def", "display", "(", "self", ",", "dset_id", ":", "str", ")", ":", "# update result", "self", ".", "skd", "[", "dset_id", "]", ".", "compute", "(", ")", "# build layout", "self", ".", "build_layout", "(", "dset_id", "=", "dset_id", ")", "# display widgets", "display", "(", "self", ".", "_", "(", "'dashboard'", ")", ")", "# display data table and chart", "self", ".", "_display_result", "(", "dset_id", "=", "dset_id", ")" ]
:param dset_id: :return:
[ ":", "param", "dset_id", ":", ":", "return", ":" ]
train
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/widgets.py#L251-L264
deathbeds/importnb
src/importnb/finder.py
FuzzyFinder.find_spec
def find_spec(self, fullname, target=None): """Try to finder the spec and if it cannot be found, use the underscore starring syntax to identify potential matches. """ spec = super().find_spec(fullname, target=target) if spec is None: original = fullname if "." in fullname: original, fullname = fullname.rsplit(".", 1) else: original, fullname = "", original if "_" in fullname: files = fuzzy_file_search(self.path, fullname) if files: file = Path(sorted(files)[0]) spec = super().find_spec( (original + "." + file.stem.split(".", 1)[0]).lstrip("."), target=target ) fullname = (original + "." + fullname).lstrip(".") if spec and fullname != spec.name: spec = FuzzySpec( spec.name, spec.loader, origin=spec.origin, loader_state=spec.loader_state, alias=fullname, is_package=bool(spec.submodule_search_locations), ) return spec
python
def find_spec(self, fullname, target=None): """Try to finder the spec and if it cannot be found, use the underscore starring syntax to identify potential matches. """ spec = super().find_spec(fullname, target=target) if spec is None: original = fullname if "." in fullname: original, fullname = fullname.rsplit(".", 1) else: original, fullname = "", original if "_" in fullname: files = fuzzy_file_search(self.path, fullname) if files: file = Path(sorted(files)[0]) spec = super().find_spec( (original + "." + file.stem.split(".", 1)[0]).lstrip("."), target=target ) fullname = (original + "." + fullname).lstrip(".") if spec and fullname != spec.name: spec = FuzzySpec( spec.name, spec.loader, origin=spec.origin, loader_state=spec.loader_state, alias=fullname, is_package=bool(spec.submodule_search_locations), ) return spec
[ "def", "find_spec", "(", "self", ",", "fullname", ",", "target", "=", "None", ")", ":", "spec", "=", "super", "(", ")", ".", "find_spec", "(", "fullname", ",", "target", "=", "target", ")", "if", "spec", "is", "None", ":", "original", "=", "fullname", "if", "\".\"", "in", "fullname", ":", "original", ",", "fullname", "=", "fullname", ".", "rsplit", "(", "\".\"", ",", "1", ")", "else", ":", "original", ",", "fullname", "=", "\"\"", ",", "original", "if", "\"_\"", "in", "fullname", ":", "files", "=", "fuzzy_file_search", "(", "self", ".", "path", ",", "fullname", ")", "if", "files", ":", "file", "=", "Path", "(", "sorted", "(", "files", ")", "[", "0", "]", ")", "spec", "=", "super", "(", ")", ".", "find_spec", "(", "(", "original", "+", "\".\"", "+", "file", ".", "stem", ".", "split", "(", "\".\"", ",", "1", ")", "[", "0", "]", ")", ".", "lstrip", "(", "\".\"", ")", ",", "target", "=", "target", ")", "fullname", "=", "(", "original", "+", "\".\"", "+", "fullname", ")", ".", "lstrip", "(", "\".\"", ")", "if", "spec", "and", "fullname", "!=", "spec", ".", "name", ":", "spec", "=", "FuzzySpec", "(", "spec", ".", "name", ",", "spec", ".", "loader", ",", "origin", "=", "spec", ".", "origin", ",", "loader_state", "=", "spec", ".", "loader_state", ",", "alias", "=", "fullname", ",", "is_package", "=", "bool", "(", "spec", ".", "submodule_search_locations", ")", ",", ")", "return", "spec" ]
Try to finder the spec and if it cannot be found, use the underscore starring syntax to identify potential matches.
[ "Try", "to", "finder", "the", "spec", "and", "if", "it", "cannot", "be", "found", "use", "the", "underscore", "starring", "syntax", "to", "identify", "potential", "matches", "." ]
train
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/finder.py#L58-L89
nuagenetworks/bambou
bambou/nurest_root_object.py
NURESTRootObject.get_resource_url
def get_resource_url(self): """ Get resource complete url """ name = self.__class__.resource_name url = self.__class__.rest_base_url() return "%s/%s" % (url, name)
python
def get_resource_url(self): """ Get resource complete url """ name = self.__class__.resource_name url = self.__class__.rest_base_url() return "%s/%s" % (url, name)
[ "def", "get_resource_url", "(", "self", ")", ":", "name", "=", "self", ".", "__class__", ".", "resource_name", "url", "=", "self", ".", "__class__", ".", "rest_base_url", "(", ")", "return", "\"%s/%s\"", "%", "(", "url", ",", "name", ")" ]
Get resource complete url
[ "Get", "resource", "complete", "url" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_root_object.py#L118-L124
nuagenetworks/bambou
bambou/nurest_root_object.py
NURESTRootObject.save
def save(self, async=False, callback=None, encrypted=True): """ Updates the user and perform the callback method """ if self._new_password and encrypted: self.password = Sha1.encrypt(self._new_password) controller = NURESTSession.get_current_session().login_controller controller.password = self._new_password controller.api_key = None data = json.dumps(self.to_dict()) request = NURESTRequest(method=HTTP_METHOD_PUT, url=self.get_resource_url(), data=data) if async: return self.send_request(request=request, async=async, local_callback=self._did_save, remote_callback=callback) else: connection = self.send_request(request=request) return self._did_save(connection)
python
def save(self, async=False, callback=None, encrypted=True): """ Updates the user and perform the callback method """ if self._new_password and encrypted: self.password = Sha1.encrypt(self._new_password) controller = NURESTSession.get_current_session().login_controller controller.password = self._new_password controller.api_key = None data = json.dumps(self.to_dict()) request = NURESTRequest(method=HTTP_METHOD_PUT, url=self.get_resource_url(), data=data) if async: return self.send_request(request=request, async=async, local_callback=self._did_save, remote_callback=callback) else: connection = self.send_request(request=request) return self._did_save(connection)
[ "def", "save", "(", "self", ",", "async", "=", "False", ",", "callback", "=", "None", ",", "encrypted", "=", "True", ")", ":", "if", "self", ".", "_new_password", "and", "encrypted", ":", "self", ".", "password", "=", "Sha1", ".", "encrypt", "(", "self", ".", "_new_password", ")", "controller", "=", "NURESTSession", ".", "get_current_session", "(", ")", ".", "login_controller", "controller", ".", "password", "=", "self", ".", "_new_password", "controller", ".", "api_key", "=", "None", "data", "=", "json", ".", "dumps", "(", "self", ".", "to_dict", "(", ")", ")", "request", "=", "NURESTRequest", "(", "method", "=", "HTTP_METHOD_PUT", ",", "url", "=", "self", ".", "get_resource_url", "(", ")", ",", "data", "=", "data", ")", "if", "async", ":", "return", "self", ".", "send_request", "(", "request", "=", "request", ",", "async", "=", "async", ",", "local_callback", "=", "self", ".", "_did_save", ",", "remote_callback", "=", "callback", ")", "else", ":", "connection", "=", "self", ".", "send_request", "(", "request", "=", "request", ")", "return", "self", ".", "_did_save", "(", "connection", ")" ]
Updates the user and perform the callback method
[ "Updates", "the", "user", "and", "perform", "the", "callback", "method" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_root_object.py#L131-L148
nuagenetworks/bambou
bambou/nurest_root_object.py
NURESTRootObject._did_save
def _did_save(self, connection): """ Launched when save has been successfully executed """ self._new_password = None controller = NURESTSession.get_current_session().login_controller controller.password = None controller.api_key = self.api_key if connection.async: callback = connection.callbacks['remote'] if connection.user_info: callback(connection.user_info, connection) else: callback(self, connection) else: return (self, connection)
python
def _did_save(self, connection): """ Launched when save has been successfully executed """ self._new_password = None controller = NURESTSession.get_current_session().login_controller controller.password = None controller.api_key = self.api_key if connection.async: callback = connection.callbacks['remote'] if connection.user_info: callback(connection.user_info, connection) else: callback(self, connection) else: return (self, connection)
[ "def", "_did_save", "(", "self", ",", "connection", ")", ":", "self", ".", "_new_password", "=", "None", "controller", "=", "NURESTSession", ".", "get_current_session", "(", ")", ".", "login_controller", "controller", ".", "password", "=", "None", "controller", ".", "api_key", "=", "self", ".", "api_key", "if", "connection", ".", "async", ":", "callback", "=", "connection", ".", "callbacks", "[", "'remote'", "]", "if", "connection", ".", "user_info", ":", "callback", "(", "connection", ".", "user_info", ",", "connection", ")", "else", ":", "callback", "(", "self", ",", "connection", ")", "else", ":", "return", "(", "self", ",", "connection", ")" ]
Launched when save has been successfully executed
[ "Launched", "when", "save", "has", "been", "successfully", "executed" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_root_object.py#L150-L167
nuagenetworks/bambou
bambou/nurest_root_object.py
NURESTRootObject.fetch
def fetch(self, async=False, callback=None): """ Fetch all information about the current object Args: async (bool): Boolean to make an asynchronous call. Default is False callback (function): Callback method that will be triggered in case of asynchronous call Returns: tuple: (current_fetcher, callee_parent, fetched_bjects, connection) Example: >>> entity = NUEntity(id="xxx-xxx-xxx-xxx") >>> entity.fetch() # will get the entity with id "xxx-xxx-xxx-xxx" >>> print entity.name "My Entity" """ request = NURESTRequest(method=HTTP_METHOD_GET, url=self.get_resource_url()) if async: return self.send_request(request=request, async=async, local_callback=self._did_fetch, remote_callback=callback) else: connection = self.send_request(request=request) return self._did_retrieve(connection)
python
def fetch(self, async=False, callback=None): """ Fetch all information about the current object Args: async (bool): Boolean to make an asynchronous call. Default is False callback (function): Callback method that will be triggered in case of asynchronous call Returns: tuple: (current_fetcher, callee_parent, fetched_bjects, connection) Example: >>> entity = NUEntity(id="xxx-xxx-xxx-xxx") >>> entity.fetch() # will get the entity with id "xxx-xxx-xxx-xxx" >>> print entity.name "My Entity" """ request = NURESTRequest(method=HTTP_METHOD_GET, url=self.get_resource_url()) if async: return self.send_request(request=request, async=async, local_callback=self._did_fetch, remote_callback=callback) else: connection = self.send_request(request=request) return self._did_retrieve(connection)
[ "def", "fetch", "(", "self", ",", "async", "=", "False", ",", "callback", "=", "None", ")", ":", "request", "=", "NURESTRequest", "(", "method", "=", "HTTP_METHOD_GET", ",", "url", "=", "self", ".", "get_resource_url", "(", ")", ")", "if", "async", ":", "return", "self", ".", "send_request", "(", "request", "=", "request", ",", "async", "=", "async", ",", "local_callback", "=", "self", ".", "_did_fetch", ",", "remote_callback", "=", "callback", ")", "else", ":", "connection", "=", "self", ".", "send_request", "(", "request", "=", "request", ")", "return", "self", ".", "_did_retrieve", "(", "connection", ")" ]
Fetch all information about the current object Args: async (bool): Boolean to make an asynchronous call. Default is False callback (function): Callback method that will be triggered in case of asynchronous call Returns: tuple: (current_fetcher, callee_parent, fetched_bjects, connection) Example: >>> entity = NUEntity(id="xxx-xxx-xxx-xxx") >>> entity.fetch() # will get the entity with id "xxx-xxx-xxx-xxx" >>> print entity.name "My Entity"
[ "Fetch", "all", "information", "about", "the", "current", "object" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_root_object.py#L169-L191
noumar/iso639
iso639/iso639.py
_fabtabular
def _fabtabular(): """ This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists. """ import csv import sys from pkg_resources import resource_filename data = resource_filename(__package__, 'iso-639-3.tab') inverted = resource_filename(__package__, 'iso-639-3_Name_Index.tab') macro = resource_filename(__package__, 'iso-639-3-macrolanguages.tab') part5 = resource_filename(__package__, 'iso639-5.tsv') part2 = resource_filename(__package__, 'iso639-2.tsv') part1 = resource_filename(__package__, 'iso639-1.tsv') # if sys.version_info[0] == 2: # from urllib2 import urlopen # from contextlib import closing # data_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab')) # inverted_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab')) # else: # from urllib.request import urlopen # import io # data_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab').read().decode()) # inverted_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab').read().decode()) if sys.version_info[0] == 3: from functools import partial global open open = partial(open, encoding='utf-8') data_fo = open(data) inverted_fo = open(inverted) macro_fo = open(macro) part5_fo = open(part5) part2_fo = open(part2) part1_fo = open(part1) with data_fo as u: with inverted_fo as i: with macro_fo as m: with part5_fo as p5: with part2_fo as p2: with part1_fo as p1: return (list(csv.reader(u, delimiter='\t'))[1:], list(csv.reader(i, delimiter='\t'))[1:], list(csv.reader(m, delimiter='\t'))[1:], list(csv.reader(p5, delimiter='\t'))[1:], list(csv.reader(p2, delimiter='\t'))[1:], list(csv.reader(p1, delimiter='\t'))[1:])
python
def _fabtabular(): """ This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists. """ import csv import sys from pkg_resources import resource_filename data = resource_filename(__package__, 'iso-639-3.tab') inverted = resource_filename(__package__, 'iso-639-3_Name_Index.tab') macro = resource_filename(__package__, 'iso-639-3-macrolanguages.tab') part5 = resource_filename(__package__, 'iso639-5.tsv') part2 = resource_filename(__package__, 'iso639-2.tsv') part1 = resource_filename(__package__, 'iso639-1.tsv') # if sys.version_info[0] == 2: # from urllib2 import urlopen # from contextlib import closing # data_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab')) # inverted_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab')) # else: # from urllib.request import urlopen # import io # data_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab').read().decode()) # inverted_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab').read().decode()) if sys.version_info[0] == 3: from functools import partial global open open = partial(open, encoding='utf-8') data_fo = open(data) inverted_fo = open(inverted) macro_fo = open(macro) part5_fo = open(part5) part2_fo = open(part2) part1_fo = open(part1) with data_fo as u: with inverted_fo as i: with macro_fo as m: with part5_fo as p5: with part2_fo as p2: with part1_fo as p1: return (list(csv.reader(u, delimiter='\t'))[1:], list(csv.reader(i, delimiter='\t'))[1:], list(csv.reader(m, delimiter='\t'))[1:], list(csv.reader(p5, delimiter='\t'))[1:], list(csv.reader(p2, delimiter='\t'))[1:], list(csv.reader(p1, delimiter='\t'))[1:])
[ "def", "_fabtabular", "(", ")", ":", "import", "csv", "import", "sys", "from", "pkg_resources", "import", "resource_filename", "data", "=", "resource_filename", "(", "__package__", ",", "'iso-639-3.tab'", ")", "inverted", "=", "resource_filename", "(", "__package__", ",", "'iso-639-3_Name_Index.tab'", ")", "macro", "=", "resource_filename", "(", "__package__", ",", "'iso-639-3-macrolanguages.tab'", ")", "part5", "=", "resource_filename", "(", "__package__", ",", "'iso639-5.tsv'", ")", "part2", "=", "resource_filename", "(", "__package__", ",", "'iso639-2.tsv'", ")", "part1", "=", "resource_filename", "(", "__package__", ",", "'iso639-1.tsv'", ")", "# if sys.version_info[0] == 2:", "# from urllib2 import urlopen", "# from contextlib import closing", "# data_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab'))", "# inverted_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab'))", "# else:", "# from urllib.request import urlopen", "# import io", "# data_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab').read().decode())", "# inverted_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab').read().decode())", "if", "sys", ".", "version_info", "[", "0", "]", "==", "3", ":", "from", "functools", "import", "partial", "global", "open", "open", "=", "partial", "(", "open", ",", "encoding", "=", "'utf-8'", ")", "data_fo", "=", "open", "(", "data", ")", "inverted_fo", "=", "open", "(", "inverted", ")", "macro_fo", "=", "open", "(", "macro", ")", "part5_fo", "=", "open", "(", "part5", ")", "part2_fo", "=", "open", "(", "part2", ")", "part1_fo", "=", "open", "(", "part1", ")", "with", "data_fo", "as", "u", ":", "with", "inverted_fo", "as", "i", ":", "with", "macro_fo", "as", "m", ":", "with", "part5_fo", "as", "p5", ":", "with", "part2_fo", "as", "p2", ":", "with", "part1_fo", "as", "p1", ":", "return", "(", "list", "(", "csv", ".", "reader", "(", "u", ",", "delimiter", "=", "'\\t'", ")", ")", "[", "1", ":", "]", ",", "list", "(", "csv", ".", "reader", "(", "i", ",", "delimiter", "=", "'\\t'", ")", ")", "[", "1", ":", "]", ",", "list", "(", "csv", ".", "reader", "(", "m", ",", "delimiter", "=", "'\\t'", ")", ")", "[", "1", ":", "]", ",", "list", "(", "csv", ".", "reader", "(", "p5", ",", "delimiter", "=", "'\\t'", ")", ")", "[", "1", ":", "]", ",", "list", "(", "csv", ".", "reader", "(", "p2", ",", "delimiter", "=", "'\\t'", ")", ")", "[", "1", ":", "]", ",", "list", "(", "csv", ".", "reader", "(", "p1", ",", "delimiter", "=", "'\\t'", ")", ")", "[", "1", ":", "]", ")" ]
This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists.
[ "This", "function", "retrieves", "the", "ISO", "639", "and", "inverted", "names", "datasets", "as", "tsv", "files", "and", "returns", "them", "as", "lists", "." ]
train
https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/iso639/iso639.py#L14-L63
noumar/iso639
iso639/iso639.py
Iso639.retired
def retired(self): """ Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')). """ def gen(): import csv import re from datetime import datetime from pkg_resources import resource_filename with open(resource_filename(__package__, 'iso-639-3_Retirements.tab')) as rf: rtd = list(csv.reader(rf, delimiter='\t'))[1:] rc = [r[0] for r in rtd] for i, _, _, m, s, d in rtd: d = datetime.strptime(d, '%Y-%m-%d') if not m: m = re.findall('\[([a-z]{3})\]', s) if m: m = [m] if isinstance(m, str) else m yield i, (d, [self.get(part3=x) for x in m if x not in rc], s) else: yield i, (d, [], s) yield 'sh', self.get(part3='hbs') # Add 'sh' as deprecated return dict(gen())
python
def retired(self): """ Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')). """ def gen(): import csv import re from datetime import datetime from pkg_resources import resource_filename with open(resource_filename(__package__, 'iso-639-3_Retirements.tab')) as rf: rtd = list(csv.reader(rf, delimiter='\t'))[1:] rc = [r[0] for r in rtd] for i, _, _, m, s, d in rtd: d = datetime.strptime(d, '%Y-%m-%d') if not m: m = re.findall('\[([a-z]{3})\]', s) if m: m = [m] if isinstance(m, str) else m yield i, (d, [self.get(part3=x) for x in m if x not in rc], s) else: yield i, (d, [], s) yield 'sh', self.get(part3='hbs') # Add 'sh' as deprecated return dict(gen())
[ "def", "retired", "(", "self", ")", ":", "def", "gen", "(", ")", ":", "import", "csv", "import", "re", "from", "datetime", "import", "datetime", "from", "pkg_resources", "import", "resource_filename", "with", "open", "(", "resource_filename", "(", "__package__", ",", "'iso-639-3_Retirements.tab'", ")", ")", "as", "rf", ":", "rtd", "=", "list", "(", "csv", ".", "reader", "(", "rf", ",", "delimiter", "=", "'\\t'", ")", ")", "[", "1", ":", "]", "rc", "=", "[", "r", "[", "0", "]", "for", "r", "in", "rtd", "]", "for", "i", ",", "_", ",", "_", ",", "m", ",", "s", ",", "d", "in", "rtd", ":", "d", "=", "datetime", ".", "strptime", "(", "d", ",", "'%Y-%m-%d'", ")", "if", "not", "m", ":", "m", "=", "re", ".", "findall", "(", "'\\[([a-z]{3})\\]'", ",", "s", ")", "if", "m", ":", "m", "=", "[", "m", "]", "if", "isinstance", "(", "m", ",", "str", ")", "else", "m", "yield", "i", ",", "(", "d", ",", "[", "self", ".", "get", "(", "part3", "=", "x", ")", "for", "x", "in", "m", "if", "x", "not", "in", "rc", "]", ",", "s", ")", "else", ":", "yield", "i", ",", "(", "d", ",", "[", "]", ",", "s", ")", "yield", "'sh'", ",", "self", ".", "get", "(", "part3", "=", "'hbs'", ")", "# Add 'sh' as deprecated", "return", "dict", "(", "gen", "(", ")", ")" ]
Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')).
[ "Function", "for", "generating", "retired", "languages", ".", "Returns", "a", "dict", "(", "code", "(", "datetime", "[", "language", "...", "]", "description", "))", "." ]
train
https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/iso639/iso639.py#L230-L256
noumar/iso639
iso639/iso639.py
Iso639.get
def get(self, **kwargs): """ Simple getter function for languages. Takes 1 keyword/value and returns 1 language object. """ if not len(kwargs) == 1: raise AttributeError('Only one keyword expected') key, value = kwargs.popitem() return getattr(self, key)[value]
python
def get(self, **kwargs): """ Simple getter function for languages. Takes 1 keyword/value and returns 1 language object. """ if not len(kwargs) == 1: raise AttributeError('Only one keyword expected') key, value = kwargs.popitem() return getattr(self, key)[value]
[ "def", "get", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "len", "(", "kwargs", ")", "==", "1", ":", "raise", "AttributeError", "(", "'Only one keyword expected'", ")", "key", ",", "value", "=", "kwargs", ".", "popitem", "(", ")", "return", "getattr", "(", "self", ",", "key", ")", "[", "value", "]" ]
Simple getter function for languages. Takes 1 keyword/value and returns 1 language object.
[ "Simple", "getter", "function", "for", "languages", ".", "Takes", "1", "keyword", "/", "value", "and", "returns", "1", "language", "object", "." ]
train
https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/iso639/iso639.py#L258-L265
opennode/waldur-core
waldur_core/structure/views.py
CustomerViewSet.list
def list(self, request, *args, **kwargs): """ To get a list of customers, run GET against */api/customers/* as authenticated user. Note that a user can only see connected customers: - customers that the user owns - customers that have a project where user has a role Staff also can filter customers by user UUID, for example /api/customers/?user_uuid=<UUID> Staff also can filter customers by exists accounting_start_date, for example: The first category: /api/customers/?accounting_is_running=True has accounting_start_date empty (i.e. accounting starts at once) has accounting_start_date in the past (i.e. has already started). Those that are not in the first: /api/customers/?accounting_is_running=False # exists accounting_start_date """ return super(CustomerViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ To get a list of customers, run GET against */api/customers/* as authenticated user. Note that a user can only see connected customers: - customers that the user owns - customers that have a project where user has a role Staff also can filter customers by user UUID, for example /api/customers/?user_uuid=<UUID> Staff also can filter customers by exists accounting_start_date, for example: The first category: /api/customers/?accounting_is_running=True has accounting_start_date empty (i.e. accounting starts at once) has accounting_start_date in the past (i.e. has already started). Those that are not in the first: /api/customers/?accounting_is_running=False # exists accounting_start_date """ return super(CustomerViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "CustomerViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To get a list of customers, run GET against */api/customers/* as authenticated user. Note that a user can only see connected customers: - customers that the user owns - customers that have a project where user has a role Staff also can filter customers by user UUID, for example /api/customers/?user_uuid=<UUID> Staff also can filter customers by exists accounting_start_date, for example: The first category: /api/customers/?accounting_is_running=True has accounting_start_date empty (i.e. accounting starts at once) has accounting_start_date in the past (i.e. has already started). Those that are not in the first: /api/customers/?accounting_is_running=False # exists accounting_start_date
[ "To", "get", "a", "list", "of", "customers", "run", "GET", "against", "*", "/", "api", "/", "customers", "/", "*", "as", "authenticated", "user", ".", "Note", "that", "a", "user", "can", "only", "see", "connected", "customers", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L71-L92
opennode/waldur-core
waldur_core/structure/views.py
CustomerViewSet.retrieve
def retrieve(self, request, *args, **kwargs): """ Optional `field` query parameter (can be list) allows to limit what fields are returned. For example, given request /api/customers/<uuid>/?field=uuid&field=name you get response like this: .. code-block:: javascript { "uuid": "90bcfe38b0124c9bbdadd617b5d739f5", "name": "Ministry of Bells" } """ return super(CustomerViewSet, self).retrieve(request, *args, **kwargs)
python
def retrieve(self, request, *args, **kwargs): """ Optional `field` query parameter (can be list) allows to limit what fields are returned. For example, given request /api/customers/<uuid>/?field=uuid&field=name you get response like this: .. code-block:: javascript { "uuid": "90bcfe38b0124c9bbdadd617b5d739f5", "name": "Ministry of Bells" } """ return super(CustomerViewSet, self).retrieve(request, *args, **kwargs)
[ "def", "retrieve", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "CustomerViewSet", ",", "self", ")", ".", "retrieve", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Optional `field` query parameter (can be list) allows to limit what fields are returned. For example, given request /api/customers/<uuid>/?field=uuid&field=name you get response like this: .. code-block:: javascript { "uuid": "90bcfe38b0124c9bbdadd617b5d739f5", "name": "Ministry of Bells" }
[ "Optional", "field", "query", "parameter", "(", "can", "be", "list", ")", "allows", "to", "limit", "what", "fields", "are", "returned", ".", "For", "example", "given", "request", "/", "api", "/", "customers", "/", "<uuid", ">", "/", "?field", "=", "uuid&field", "=", "name", "you", "get", "response", "like", "this", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L94-L106
opennode/waldur-core
waldur_core/structure/views.py
CustomerViewSet.create
def create(self, request, *args, **kwargs): """ A new customer can only be created: - by users with staff privilege (is_staff=True); - by organization owners if OWNER_CAN_MANAGE_CUSTOMER is set to True; Example of a valid request: .. code-block:: http POST /api/customers/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "Customer A", "native_name": "Customer A", "abbreviation": "CA", "contact_details": "Luhamaa 28, 10128 Tallinn", } """ return super(CustomerViewSet, self).create(request, *args, **kwargs)
python
def create(self, request, *args, **kwargs): """ A new customer can only be created: - by users with staff privilege (is_staff=True); - by organization owners if OWNER_CAN_MANAGE_CUSTOMER is set to True; Example of a valid request: .. code-block:: http POST /api/customers/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "Customer A", "native_name": "Customer A", "abbreviation": "CA", "contact_details": "Luhamaa 28, 10128 Tallinn", } """ return super(CustomerViewSet, self).create(request, *args, **kwargs)
[ "def", "create", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "CustomerViewSet", ",", "self", ")", ".", "create", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
A new customer can only be created: - by users with staff privilege (is_staff=True); - by organization owners if OWNER_CAN_MANAGE_CUSTOMER is set to True; Example of a valid request: .. code-block:: http POST /api/customers/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "Customer A", "native_name": "Customer A", "abbreviation": "CA", "contact_details": "Luhamaa 28, 10128 Tallinn", }
[ "A", "new", "customer", "can", "only", "be", "created", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L108-L132
opennode/waldur-core
waldur_core/structure/views.py
CustomerViewSet.destroy
def destroy(self, request, *args, **kwargs): """ Deletion of a customer is done through sending a **DELETE** request to the customer instance URI. Please note, that if a customer has connected projects, deletion request will fail with 409 response code. Valid request example (token is user specific): .. code-block:: http DELETE /api/customers/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1 Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com """ return super(CustomerViewSet, self).destroy(request, *args, **kwargs)
python
def destroy(self, request, *args, **kwargs): """ Deletion of a customer is done through sending a **DELETE** request to the customer instance URI. Please note, that if a customer has connected projects, deletion request will fail with 409 response code. Valid request example (token is user specific): .. code-block:: http DELETE /api/customers/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1 Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com """ return super(CustomerViewSet, self).destroy(request, *args, **kwargs)
[ "def", "destroy", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "CustomerViewSet", ",", "self", ")", ".", "destroy", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Deletion of a customer is done through sending a **DELETE** request to the customer instance URI. Please note, that if a customer has connected projects, deletion request will fail with 409 response code. Valid request example (token is user specific): .. code-block:: http DELETE /api/customers/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1 Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com
[ "Deletion", "of", "a", "customer", "is", "done", "through", "sending", "a", "**", "DELETE", "**", "request", "to", "the", "customer", "instance", "URI", ".", "Please", "note", "that", "if", "a", "customer", "has", "connected", "projects", "deletion", "request", "will", "fail", "with", "409", "response", "code", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L134-L147
opennode/waldur-core
waldur_core/structure/views.py
ProjectViewSet.list
def list(self, request, *args, **kwargs): """ To get a list of projects, run **GET** against */api/projects/* as authenticated user. Here you can also check actual value for project quotas and project usage Note that a user can only see connected projects: - projects that the user owns as a customer - projects where user has any role Supported logic filters: - ?can_manage - return a list of projects where current user is manager or a customer owner; - ?can_admin - return a list of projects where current user is admin; """ return super(ProjectViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ To get a list of projects, run **GET** against */api/projects/* as authenticated user. Here you can also check actual value for project quotas and project usage Note that a user can only see connected projects: - projects that the user owns as a customer - projects where user has any role Supported logic filters: - ?can_manage - return a list of projects where current user is manager or a customer owner; - ?can_admin - return a list of projects where current user is admin; """ return super(ProjectViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ProjectViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To get a list of projects, run **GET** against */api/projects/* as authenticated user. Here you can also check actual value for project quotas and project usage Note that a user can only see connected projects: - projects that the user owns as a customer - projects where user has any role Supported logic filters: - ?can_manage - return a list of projects where current user is manager or a customer owner; - ?can_admin - return a list of projects where current user is admin;
[ "To", "get", "a", "list", "of", "projects", "run", "**", "GET", "**", "against", "*", "/", "api", "/", "projects", "/", "*", "as", "authenticated", "user", ".", "Here", "you", "can", "also", "check", "actual", "value", "for", "project", "quotas", "and", "project", "usage" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L260-L275
opennode/waldur-core
waldur_core/structure/views.py
ProjectViewSet.retrieve
def retrieve(self, request, *args, **kwargs): """ Optional `field` query parameter (can be list) allows to limit what fields are returned. For example, given request /api/projects/<uuid>/?field=uuid&field=name you get response like this: .. code-block:: javascript { "uuid": "90bcfe38b0124c9bbdadd617b5d739f5", "name": "Default" } """ return super(ProjectViewSet, self).retrieve(request, *args, **kwargs)
python
def retrieve(self, request, *args, **kwargs): """ Optional `field` query parameter (can be list) allows to limit what fields are returned. For example, given request /api/projects/<uuid>/?field=uuid&field=name you get response like this: .. code-block:: javascript { "uuid": "90bcfe38b0124c9bbdadd617b5d739f5", "name": "Default" } """ return super(ProjectViewSet, self).retrieve(request, *args, **kwargs)
[ "def", "retrieve", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ProjectViewSet", ",", "self", ")", ".", "retrieve", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Optional `field` query parameter (can be list) allows to limit what fields are returned. For example, given request /api/projects/<uuid>/?field=uuid&field=name you get response like this: .. code-block:: javascript { "uuid": "90bcfe38b0124c9bbdadd617b5d739f5", "name": "Default" }
[ "Optional", "field", "query", "parameter", "(", "can", "be", "list", ")", "allows", "to", "limit", "what", "fields", "are", "returned", ".", "For", "example", "given", "request", "/", "api", "/", "projects", "/", "<uuid", ">", "/", "?field", "=", "uuid&field", "=", "name", "you", "get", "response", "like", "this", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L277-L289
opennode/waldur-core
waldur_core/structure/views.py
ProjectViewSet.create
def create(self, request, *args, **kwargs): """ A new project can be created by users with staff privilege (is_staff=True) or customer owners. Project resource quota is optional. Example of a valid request: .. code-block:: http POST /api/projects/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "Project A", "customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/", } """ return super(ProjectViewSet, self).create(request, *args, **kwargs)
python
def create(self, request, *args, **kwargs): """ A new project can be created by users with staff privilege (is_staff=True) or customer owners. Project resource quota is optional. Example of a valid request: .. code-block:: http POST /api/projects/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "Project A", "customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/", } """ return super(ProjectViewSet, self).create(request, *args, **kwargs)
[ "def", "create", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ProjectViewSet", ",", "self", ")", ".", "create", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
A new project can be created by users with staff privilege (is_staff=True) or customer owners. Project resource quota is optional. Example of a valid request: .. code-block:: http POST /api/projects/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "Project A", "customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/", }
[ "A", "new", "project", "can", "be", "created", "by", "users", "with", "staff", "privilege", "(", "is_staff", "=", "True", ")", "or", "customer", "owners", ".", "Project", "resource", "quota", "is", "optional", ".", "Example", "of", "a", "valid", "request", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L291-L309
opennode/waldur-core
waldur_core/structure/views.py
ProjectViewSet.destroy
def destroy(self, request, *args, **kwargs): """ Deletion of a project is done through sending a **DELETE** request to the project instance URI. Please note, that if a project has connected instances, deletion request will fail with 409 response code. Valid request example (token is user specific): .. code-block:: http DELETE /api/projects/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1 Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com """ return super(ProjectViewSet, self).destroy(request, *args, **kwargs)
python
def destroy(self, request, *args, **kwargs): """ Deletion of a project is done through sending a **DELETE** request to the project instance URI. Please note, that if a project has connected instances, deletion request will fail with 409 response code. Valid request example (token is user specific): .. code-block:: http DELETE /api/projects/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1 Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com """ return super(ProjectViewSet, self).destroy(request, *args, **kwargs)
[ "def", "destroy", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ProjectViewSet", ",", "self", ")", ".", "destroy", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Deletion of a project is done through sending a **DELETE** request to the project instance URI. Please note, that if a project has connected instances, deletion request will fail with 409 response code. Valid request example (token is user specific): .. code-block:: http DELETE /api/projects/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1 Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com
[ "Deletion", "of", "a", "project", "is", "done", "through", "sending", "a", "**", "DELETE", "**", "request", "to", "the", "project", "instance", "URI", ".", "Please", "note", "that", "if", "a", "project", "has", "connected", "instances", "deletion", "request", "will", "fail", "with", "409", "response", "code", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L311-L324
opennode/waldur-core
waldur_core/structure/views.py
ProjectViewSet.users
def users(self, request, uuid=None): """ A list of users connected to the project """ project = self.get_object() queryset = project.get_users() # we need to handle filtration manually because we want to filter only project users, not projects. filter_backend = filters.UserConcatenatedNameOrderingBackend() queryset = filter_backend.filter_queryset(request, queryset, self) queryset = self.paginate_queryset(queryset) serializer = self.get_serializer(queryset, many=True) return self.get_paginated_response(serializer.data)
python
def users(self, request, uuid=None): """ A list of users connected to the project """ project = self.get_object() queryset = project.get_users() # we need to handle filtration manually because we want to filter only project users, not projects. filter_backend = filters.UserConcatenatedNameOrderingBackend() queryset = filter_backend.filter_queryset(request, queryset, self) queryset = self.paginate_queryset(queryset) serializer = self.get_serializer(queryset, many=True) return self.get_paginated_response(serializer.data)
[ "def", "users", "(", "self", ",", "request", ",", "uuid", "=", "None", ")", ":", "project", "=", "self", ".", "get_object", "(", ")", "queryset", "=", "project", ".", "get_users", "(", ")", "# we need to handle filtration manually because we want to filter only project users, not projects.", "filter_backend", "=", "filters", ".", "UserConcatenatedNameOrderingBackend", "(", ")", "queryset", "=", "filter_backend", ".", "filter_queryset", "(", "request", ",", "queryset", ",", "self", ")", "queryset", "=", "self", ".", "paginate_queryset", "(", "queryset", ")", "serializer", "=", "self", ".", "get_serializer", "(", "queryset", ",", "many", "=", "True", ")", "return", "self", ".", "get_paginated_response", "(", "serializer", ".", "data", ")" ]
A list of users connected to the project
[ "A", "list", "of", "users", "connected", "to", "the", "project" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L374-L383
opennode/waldur-core
waldur_core/structure/views.py
UserViewSet.list
def list(self, request, *args, **kwargs): """ User list is available to all authenticated users. To get a list, issue authenticated **GET** request against */api/users/*. User list supports several filters. All filters are set in HTTP query section. Field filters are listed below. All of the filters apart from ?organization are using case insensitive partial matching. Several custom filters are supported: - ?current - filters out user making a request. Useful for getting information about a currently logged in user. - ?civil_number=XXX - filters out users with a specified civil number - ?is_active=True|False - show only active (non-active) users The user can be created either through automated process on login with SAML token, or through a REST call by a user with staff privilege. Example of a creation request is below. .. code-block:: http POST /api/users/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "username": "sample-user", "full_name": "full name", "native_name": "taisnimi", "job_title": "senior cleaning manager", "email": "example@example.com", "civil_number": "12121212", "phone_number": "", "description": "", "organization": "", } NB! Username field is case-insensitive. So "John" and "john" will be treated as the same user. """ return super(UserViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ User list is available to all authenticated users. To get a list, issue authenticated **GET** request against */api/users/*. User list supports several filters. All filters are set in HTTP query section. Field filters are listed below. All of the filters apart from ?organization are using case insensitive partial matching. Several custom filters are supported: - ?current - filters out user making a request. Useful for getting information about a currently logged in user. - ?civil_number=XXX - filters out users with a specified civil number - ?is_active=True|False - show only active (non-active) users The user can be created either through automated process on login with SAML token, or through a REST call by a user with staff privilege. Example of a creation request is below. .. code-block:: http POST /api/users/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "username": "sample-user", "full_name": "full name", "native_name": "taisnimi", "job_title": "senior cleaning manager", "email": "example@example.com", "civil_number": "12121212", "phone_number": "", "description": "", "organization": "", } NB! Username field is case-insensitive. So "John" and "john" will be treated as the same user. """ return super(UserViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "UserViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
User list is available to all authenticated users. To get a list, issue authenticated **GET** request against */api/users/*. User list supports several filters. All filters are set in HTTP query section. Field filters are listed below. All of the filters apart from ?organization are using case insensitive partial matching. Several custom filters are supported: - ?current - filters out user making a request. Useful for getting information about a currently logged in user. - ?civil_number=XXX - filters out users with a specified civil number - ?is_active=True|False - show only active (non-active) users The user can be created either through automated process on login with SAML token, or through a REST call by a user with staff privilege. Example of a creation request is below. .. code-block:: http POST /api/users/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "username": "sample-user", "full_name": "full name", "native_name": "taisnimi", "job_title": "senior cleaning manager", "email": "example@example.com", "civil_number": "12121212", "phone_number": "", "description": "", "organization": "", } NB! Username field is case-insensitive. So "John" and "john" will be treated as the same user.
[ "User", "list", "is", "available", "to", "all", "authenticated", "users", ".", "To", "get", "a", "list", "issue", "authenticated", "**", "GET", "**", "request", "against", "*", "/", "api", "/", "users", "/", "*", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L417-L459
opennode/waldur-core
waldur_core/structure/views.py
UserViewSet.retrieve
def retrieve(self, request, *args, **kwargs): """ User fields can be updated by account owner or user with staff privilege (is_staff=True). Following user fields can be updated: - organization (deprecated, use `organization plugin <http://waldur_core-organization.readthedocs.org/en/stable/>`_ instead) - full_name - native_name - job_title - phone_number - email Can be done by **PUT**ing a new data to the user URI, i.e. */api/users/<UUID>/* by staff user or account owner. Valid request example (token is user specific): .. code-block:: http PUT /api/users/e0c058d06864441fb4f1c40dee5dd4fd/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "email": "example@example.com", "organization": "Bells organization", } """ return super(UserViewSet, self).retrieve(request, *args, **kwargs)
python
def retrieve(self, request, *args, **kwargs): """ User fields can be updated by account owner or user with staff privilege (is_staff=True). Following user fields can be updated: - organization (deprecated, use `organization plugin <http://waldur_core-organization.readthedocs.org/en/stable/>`_ instead) - full_name - native_name - job_title - phone_number - email Can be done by **PUT**ing a new data to the user URI, i.e. */api/users/<UUID>/* by staff user or account owner. Valid request example (token is user specific): .. code-block:: http PUT /api/users/e0c058d06864441fb4f1c40dee5dd4fd/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "email": "example@example.com", "organization": "Bells organization", } """ return super(UserViewSet, self).retrieve(request, *args, **kwargs)
[ "def", "retrieve", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "UserViewSet", ",", "self", ")", ".", "retrieve", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
User fields can be updated by account owner or user with staff privilege (is_staff=True). Following user fields can be updated: - organization (deprecated, use `organization plugin <http://waldur_core-organization.readthedocs.org/en/stable/>`_ instead) - full_name - native_name - job_title - phone_number - email Can be done by **PUT**ing a new data to the user URI, i.e. */api/users/<UUID>/* by staff user or account owner. Valid request example (token is user specific): .. code-block:: http PUT /api/users/e0c058d06864441fb4f1c40dee5dd4fd/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "email": "example@example.com", "organization": "Bells organization", }
[ "User", "fields", "can", "be", "updated", "by", "account", "owner", "or", "user", "with", "staff", "privilege", "(", "is_staff", "=", "True", ")", ".", "Following", "user", "fields", "can", "be", "updated", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L461-L490
opennode/waldur-core
waldur_core/structure/views.py
UserViewSet.password
def password(self, request, uuid=None): """ To change a user password, submit a **POST** request to the user's RPC URL, specifying new password by staff user or account owner. Password is expected to be at least 7 symbols long and contain at least one number and at least one lower or upper case. Example of a valid request: .. code-block:: http POST /api/users/e0c058d06864441fb4f1c40dee5dd4fd/password/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "password": "nQvqHzeP123", } """ user = self.get_object() serializer = serializers.PasswordSerializer(data=request.data) serializer.is_valid(raise_exception=True) new_password = serializer.validated_data['password'] user.set_password(new_password) user.save() return Response({'detail': _('Password has been successfully updated.')}, status=status.HTTP_200_OK)
python
def password(self, request, uuid=None): """ To change a user password, submit a **POST** request to the user's RPC URL, specifying new password by staff user or account owner. Password is expected to be at least 7 symbols long and contain at least one number and at least one lower or upper case. Example of a valid request: .. code-block:: http POST /api/users/e0c058d06864441fb4f1c40dee5dd4fd/password/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "password": "nQvqHzeP123", } """ user = self.get_object() serializer = serializers.PasswordSerializer(data=request.data) serializer.is_valid(raise_exception=True) new_password = serializer.validated_data['password'] user.set_password(new_password) user.save() return Response({'detail': _('Password has been successfully updated.')}, status=status.HTTP_200_OK)
[ "def", "password", "(", "self", ",", "request", ",", "uuid", "=", "None", ")", ":", "user", "=", "self", ".", "get_object", "(", ")", "serializer", "=", "serializers", ".", "PasswordSerializer", "(", "data", "=", "request", ".", "data", ")", "serializer", ".", "is_valid", "(", "raise_exception", "=", "True", ")", "new_password", "=", "serializer", ".", "validated_data", "[", "'password'", "]", "user", ".", "set_password", "(", "new_password", ")", "user", ".", "save", "(", ")", "return", "Response", "(", "{", "'detail'", ":", "_", "(", "'Password has been successfully updated.'", ")", "}", ",", "status", "=", "status", ".", "HTTP_200_OK", ")" ]
To change a user password, submit a **POST** request to the user's RPC URL, specifying new password by staff user or account owner. Password is expected to be at least 7 symbols long and contain at least one number and at least one lower or upper case. Example of a valid request: .. code-block:: http POST /api/users/e0c058d06864441fb4f1c40dee5dd4fd/password/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "password": "nQvqHzeP123", }
[ "To", "change", "a", "user", "password", "submit", "a", "**", "POST", "**", "request", "to", "the", "user", "s", "RPC", "URL", "specifying", "new", "password", "by", "staff", "user", "or", "account", "owner", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L493-L525
opennode/waldur-core
waldur_core/structure/views.py
ProjectPermissionViewSet.list
def list(self, request, *args, **kwargs): """ Project permissions expresses connection of user to a project. User may have either project manager or system administrator permission in the project. Use */api/project-permissions/* endpoint to maintain project permissions. Note that project permissions can be viewed and modified only by customer owners and staff users. To list all visible permissions, run a **GET** query against a list. Response will contain a list of project users and their brief data. To add a new user to the project, **POST** a new relationship to */api/project-permissions/* endpoint specifying project, user and the role of the user ('admin' or 'manager'): .. code-block:: http POST /api/project-permissions/ HTTP/1.1 Accept: application/json Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com { "project": "http://example.com/api/projects/6c9b01c251c24174a6691a1f894fae31/", "role": "manager", "user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/" } """ return super(ProjectPermissionViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ Project permissions expresses connection of user to a project. User may have either project manager or system administrator permission in the project. Use */api/project-permissions/* endpoint to maintain project permissions. Note that project permissions can be viewed and modified only by customer owners and staff users. To list all visible permissions, run a **GET** query against a list. Response will contain a list of project users and their brief data. To add a new user to the project, **POST** a new relationship to */api/project-permissions/* endpoint specifying project, user and the role of the user ('admin' or 'manager'): .. code-block:: http POST /api/project-permissions/ HTTP/1.1 Accept: application/json Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com { "project": "http://example.com/api/projects/6c9b01c251c24174a6691a1f894fae31/", "role": "manager", "user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/" } """ return super(ProjectPermissionViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ProjectPermissionViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Project permissions expresses connection of user to a project. User may have either project manager or system administrator permission in the project. Use */api/project-permissions/* endpoint to maintain project permissions. Note that project permissions can be viewed and modified only by customer owners and staff users. To list all visible permissions, run a **GET** query against a list. Response will contain a list of project users and their brief data. To add a new user to the project, **POST** a new relationship to */api/project-permissions/* endpoint specifying project, user and the role of the user ('admin' or 'manager'): .. code-block:: http POST /api/project-permissions/ HTTP/1.1 Accept: application/json Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com { "project": "http://example.com/api/projects/6c9b01c251c24174a6691a1f894fae31/", "role": "manager", "user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/" }
[ "Project", "permissions", "expresses", "connection", "of", "user", "to", "a", "project", ".", "User", "may", "have", "either", "project", "manager", "or", "system", "administrator", "permission", "in", "the", "project", ".", "Use", "*", "/", "api", "/", "project", "-", "permissions", "/", "*", "endpoint", "to", "maintain", "project", "permissions", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L611-L638
opennode/waldur-core
waldur_core/structure/views.py
ProjectPermissionViewSet.destroy
def destroy(self, request, *args, **kwargs): """ To remove a user from a project, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/project-permissions/42/ HTTP/1.1 Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com """ return super(ProjectPermissionViewSet, self).destroy(request, *args, **kwargs)
python
def destroy(self, request, *args, **kwargs): """ To remove a user from a project, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/project-permissions/42/ HTTP/1.1 Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com """ return super(ProjectPermissionViewSet, self).destroy(request, *args, **kwargs)
[ "def", "destroy", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ProjectPermissionViewSet", ",", "self", ")", ".", "destroy", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To remove a user from a project, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/project-permissions/42/ HTTP/1.1 Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com
[ "To", "remove", "a", "user", "from", "a", "project", "delete", "corresponding", "connection", "(", "**", "url", "**", "field", ")", ".", "Successful", "deletion", "will", "return", "status", "code", "204", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L640-L651
opennode/waldur-core
waldur_core/structure/views.py
CustomerPermissionViewSet.list
def list(self, request, *args, **kwargs): """ Each customer is associated with a group of users that represent customer owners. The link is maintained through **api/customer-permissions/** endpoint. To list all visible links, run a **GET** query against a list. Response will contain a list of customer owners and their brief data. To add a new user to the customer, **POST** a new relationship to **customer-permissions** endpoint: .. code-block:: http POST /api/customer-permissions/ HTTP/1.1 Accept: application/json Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com { "customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/", "role": "owner", "user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/" } """ return super(CustomerPermissionViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ Each customer is associated with a group of users that represent customer owners. The link is maintained through **api/customer-permissions/** endpoint. To list all visible links, run a **GET** query against a list. Response will contain a list of customer owners and their brief data. To add a new user to the customer, **POST** a new relationship to **customer-permissions** endpoint: .. code-block:: http POST /api/customer-permissions/ HTTP/1.1 Accept: application/json Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com { "customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/", "role": "owner", "user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/" } """ return super(CustomerPermissionViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "CustomerPermissionViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Each customer is associated with a group of users that represent customer owners. The link is maintained through **api/customer-permissions/** endpoint. To list all visible links, run a **GET** query against a list. Response will contain a list of customer owners and their brief data. To add a new user to the customer, **POST** a new relationship to **customer-permissions** endpoint: .. code-block:: http POST /api/customer-permissions/ HTTP/1.1 Accept: application/json Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com { "customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/", "role": "owner", "user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/" }
[ "Each", "customer", "is", "associated", "with", "a", "group", "of", "users", "that", "represent", "customer", "owners", ".", "The", "link", "is", "maintained", "through", "**", "api", "/", "customer", "-", "permissions", "/", "**", "endpoint", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L689-L712
opennode/waldur-core
waldur_core/structure/views.py
CustomerPermissionViewSet.retrieve
def retrieve(self, request, *args, **kwargs): """ To remove a user from a customer owner group, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/customer-permissions/71/ HTTP/1.1 Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com """ return super(CustomerPermissionViewSet, self).retrieve(request, *args, **kwargs)
python
def retrieve(self, request, *args, **kwargs): """ To remove a user from a customer owner group, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/customer-permissions/71/ HTTP/1.1 Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com """ return super(CustomerPermissionViewSet, self).retrieve(request, *args, **kwargs)
[ "def", "retrieve", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "CustomerPermissionViewSet", ",", "self", ")", ".", "retrieve", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To remove a user from a customer owner group, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/customer-permissions/71/ HTTP/1.1 Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: example.com
[ "To", "remove", "a", "user", "from", "a", "customer", "owner", "group", "delete", "corresponding", "connection", "(", "**", "url", "**", "field", ")", ".", "Successful", "deletion", "will", "return", "status", "code", "204", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L714-L725
opennode/waldur-core
waldur_core/structure/views.py
CreationTimeStatsView.list
def list(self, request, *args, **kwargs): """ Available request parameters: - ?type=type_of_statistics_objects (required. Have to be from the list: 'customer', 'project') - ?from=timestamp (default: now - 30 days, for example: 1415910025) - ?to=timestamp (default: now, for example: 1415912625) - ?datapoints=how many data points have to be in answer (default: 6) Answer will be list of datapoints(dictionaries). Each datapoint will contain fields: 'to', 'from', 'value'. 'Value' - count of objects, that were created between 'from' and 'to' dates. Example: .. code-block:: javascript [ {"to": 471970877, "from": 1, "value": 5}, {"to": 943941753, "from": 471970877, "value": 0}, {"to": 1415912629, "from": 943941753, "value": 3} ] """ return super(CreationTimeStatsView, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ Available request parameters: - ?type=type_of_statistics_objects (required. Have to be from the list: 'customer', 'project') - ?from=timestamp (default: now - 30 days, for example: 1415910025) - ?to=timestamp (default: now, for example: 1415912625) - ?datapoints=how many data points have to be in answer (default: 6) Answer will be list of datapoints(dictionaries). Each datapoint will contain fields: 'to', 'from', 'value'. 'Value' - count of objects, that were created between 'from' and 'to' dates. Example: .. code-block:: javascript [ {"to": 471970877, "from": 1, "value": 5}, {"to": 943941753, "from": 471970877, "value": 0}, {"to": 1415912629, "from": 943941753, "value": 3} ] """ return super(CreationTimeStatsView, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "CreationTimeStatsView", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Available request parameters: - ?type=type_of_statistics_objects (required. Have to be from the list: 'customer', 'project') - ?from=timestamp (default: now - 30 days, for example: 1415910025) - ?to=timestamp (default: now, for example: 1415912625) - ?datapoints=how many data points have to be in answer (default: 6) Answer will be list of datapoints(dictionaries). Each datapoint will contain fields: 'to', 'from', 'value'. 'Value' - count of objects, that were created between 'from' and 'to' dates. Example: .. code-block:: javascript [ {"to": 471970877, "from": 1, "value": 5}, {"to": 943941753, "from": 471970877, "value": 0}, {"to": 1415912629, "from": 943941753, "value": 3} ]
[ "Available", "request", "parameters", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L757-L780
opennode/waldur-core
waldur_core/structure/views.py
SshKeyViewSet.list
def list(self, request, *args, **kwargs): """ To get a list of SSH keys, run **GET** against */api/keys/* as authenticated user. A new SSH key can be created by any active users. Example of a valid request: .. code-block:: http POST /api/keys/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "ssh_public_key1", "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDURXDP5YhOQUYoDuTxJ84DuzqMJYJqJ8+SZT28 TtLm5yBDRLKAERqtlbH2gkrQ3US58gd2r8H9jAmQOydfvgwauxuJUE4eDpaMWupqquMYsYLB5f+vVGhdZbbzfc6DTQ2rY dknWoMoArlG7MvRMA/xQ0ye1muTv+mYMipnd7Z+WH0uVArYI9QBpqC/gpZRRIouQ4VIQIVWGoT6M4Kat5ZBXEa9yP+9du D2C05GX3gumoSAVyAcDHn/xgej9pYRXGha4l+LKkFdGwAoXdV1z79EG1+9ns7wXuqMJFHM2KDpxAizV0GkZcojISvDwuh vEAFdOJcqjyyH4FOGYa8usP1 jhon@example.com", } """ return super(SshKeyViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ To get a list of SSH keys, run **GET** against */api/keys/* as authenticated user. A new SSH key can be created by any active users. Example of a valid request: .. code-block:: http POST /api/keys/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "ssh_public_key1", "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDURXDP5YhOQUYoDuTxJ84DuzqMJYJqJ8+SZT28 TtLm5yBDRLKAERqtlbH2gkrQ3US58gd2r8H9jAmQOydfvgwauxuJUE4eDpaMWupqquMYsYLB5f+vVGhdZbbzfc6DTQ2rY dknWoMoArlG7MvRMA/xQ0ye1muTv+mYMipnd7Z+WH0uVArYI9QBpqC/gpZRRIouQ4VIQIVWGoT6M4Kat5ZBXEa9yP+9du D2C05GX3gumoSAVyAcDHn/xgej9pYRXGha4l+LKkFdGwAoXdV1z79EG1+9ns7wXuqMJFHM2KDpxAizV0GkZcojISvDwuh vEAFdOJcqjyyH4FOGYa8usP1 jhon@example.com", } """ return super(SshKeyViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "SshKeyViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To get a list of SSH keys, run **GET** against */api/keys/* as authenticated user. A new SSH key can be created by any active users. Example of a valid request: .. code-block:: http POST /api/keys/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "ssh_public_key1", "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDURXDP5YhOQUYoDuTxJ84DuzqMJYJqJ8+SZT28 TtLm5yBDRLKAERqtlbH2gkrQ3US58gd2r8H9jAmQOydfvgwauxuJUE4eDpaMWupqquMYsYLB5f+vVGhdZbbzfc6DTQ2rY dknWoMoArlG7MvRMA/xQ0ye1muTv+mYMipnd7Z+WH0uVArYI9QBpqC/gpZRRIouQ4VIQIVWGoT6M4Kat5ZBXEa9yP+9du D2C05GX3gumoSAVyAcDHn/xgej9pYRXGha4l+LKkFdGwAoXdV1z79EG1+9ns7wXuqMJFHM2KDpxAizV0GkZcojISvDwuh vEAFdOJcqjyyH4FOGYa8usP1 jhon@example.com", }
[ "To", "get", "a", "list", "of", "SSH", "keys", "run", "**", "GET", "**", "against", "*", "/", "api", "/", "keys", "/", "*", "as", "authenticated", "user", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L816-L839
opennode/waldur-core
waldur_core/structure/views.py
ServiceSettingsViewSet.list
def list(self, request, *args, **kwargs): """ To get a list of service settings, run **GET** against */api/service-settings/* as an authenticated user. Only settings owned by this user or shared settings will be listed. Supported filters are: - ?name=<text> - partial matching used for searching - ?type=<type> - choices: OpenStack, DigitalOcean, Amazon, JIRA, GitLab, Oracle - ?state=<state> - choices: New, Creation Scheduled, Creating, Sync Scheduled, Syncing, In Sync, Erred - ?shared=<bool> - allows to filter shared service settings """ return super(ServiceSettingsViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ To get a list of service settings, run **GET** against */api/service-settings/* as an authenticated user. Only settings owned by this user or shared settings will be listed. Supported filters are: - ?name=<text> - partial matching used for searching - ?type=<type> - choices: OpenStack, DigitalOcean, Amazon, JIRA, GitLab, Oracle - ?state=<state> - choices: New, Creation Scheduled, Creating, Sync Scheduled, Syncing, In Sync, Erred - ?shared=<bool> - allows to filter shared service settings """ return super(ServiceSettingsViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ServiceSettingsViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To get a list of service settings, run **GET** against */api/service-settings/* as an authenticated user. Only settings owned by this user or shared settings will be listed. Supported filters are: - ?name=<text> - partial matching used for searching - ?type=<type> - choices: OpenStack, DigitalOcean, Amazon, JIRA, GitLab, Oracle - ?state=<state> - choices: New, Creation Scheduled, Creating, Sync Scheduled, Syncing, In Sync, Erred - ?shared=<bool> - allows to filter shared service settings
[ "To", "get", "a", "list", "of", "service", "settings", "run", "**", "GET", "**", "against", "*", "/", "api", "/", "service", "-", "settings", "/", "*", "as", "an", "authenticated", "user", ".", "Only", "settings", "owned", "by", "this", "user", "or", "shared", "settings", "will", "be", "listed", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L863-L875
opennode/waldur-core
waldur_core/structure/views.py
ServiceSettingsViewSet.can_user_update_settings
def can_user_update_settings(request, view, obj=None): """ Only staff can update shared settings, otherwise user has to be an owner of the settings.""" if obj is None: return # TODO [TM:3/21/17] clean it up after WAL-634. Clean up service settings update tests as well. if obj.customer and not obj.shared: return permissions.is_owner(request, view, obj) else: return permissions.is_staff(request, view, obj)
python
def can_user_update_settings(request, view, obj=None): """ Only staff can update shared settings, otherwise user has to be an owner of the settings.""" if obj is None: return # TODO [TM:3/21/17] clean it up after WAL-634. Clean up service settings update tests as well. if obj.customer and not obj.shared: return permissions.is_owner(request, view, obj) else: return permissions.is_staff(request, view, obj)
[ "def", "can_user_update_settings", "(", "request", ",", "view", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "return", "# TODO [TM:3/21/17] clean it up after WAL-634. Clean up service settings update tests as well.", "if", "obj", ".", "customer", "and", "not", "obj", ".", "shared", ":", "return", "permissions", ".", "is_owner", "(", "request", ",", "view", ",", "obj", ")", "else", ":", "return", "permissions", ".", "is_staff", "(", "request", ",", "view", ",", "obj", ")" ]
Only staff can update shared settings, otherwise user has to be an owner of the settings.
[ "Only", "staff", "can", "update", "shared", "settings", "otherwise", "user", "has", "to", "be", "an", "owner", "of", "the", "settings", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L877-L886
opennode/waldur-core
waldur_core/structure/views.py
ServiceSettingsViewSet.update
def update(self, request, *args, **kwargs): """ To update service settings, issue a **PUT** or **PATCH** to */api/service-settings/<uuid>/* as a customer owner. You are allowed to change name and credentials only. Example of a request: .. code-block:: http PATCH /api/service-settings/9079705c17d64e6aa0af2e619b0e0702/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "username": "admin", "password": "new_secret" } """ return super(ServiceSettingsViewSet, self).update(request, *args, **kwargs)
python
def update(self, request, *args, **kwargs): """ To update service settings, issue a **PUT** or **PATCH** to */api/service-settings/<uuid>/* as a customer owner. You are allowed to change name and credentials only. Example of a request: .. code-block:: http PATCH /api/service-settings/9079705c17d64e6aa0af2e619b0e0702/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "username": "admin", "password": "new_secret" } """ return super(ServiceSettingsViewSet, self).update(request, *args, **kwargs)
[ "def", "update", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ServiceSettingsViewSet", ",", "self", ")", ".", "update", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To update service settings, issue a **PUT** or **PATCH** to */api/service-settings/<uuid>/* as a customer owner. You are allowed to change name and credentials only. Example of a request: .. code-block:: http PATCH /api/service-settings/9079705c17d64e6aa0af2e619b0e0702/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "username": "admin", "password": "new_secret" }
[ "To", "update", "service", "settings", "issue", "a", "**", "PUT", "**", "or", "**", "PATCH", "**", "to", "*", "/", "api", "/", "service", "-", "settings", "/", "<uuid", ">", "/", "*", "as", "a", "customer", "owner", ".", "You", "are", "allowed", "to", "change", "name", "and", "credentials", "only", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L888-L908
opennode/waldur-core
waldur_core/structure/views.py
ServiceSettingsViewSet.stats
def stats(self, request, uuid=None): """ This endpoint returns allocation of resources for current service setting. Answer is service-specific dictionary. Example output for OpenStack: * vcpu - maximum number of vCPUs (from hypervisors) * vcpu_quota - maximum number of vCPUs(from quotas) * vcpu_usage - current number of used vCPUs * ram - total size of memory for allocation (from hypervisors) * ram_quota - maximum number of memory (from quotas) * ram_usage - currently used memory size on all physical hosts * storage - total available disk space on all physical hosts (from hypervisors) * storage_quota - maximum number of storage (from quotas) * storage_usage - currently used storage on all physical hosts { 'vcpu': 10, 'vcpu_quota': 7, 'vcpu_usage': 5, 'ram': 1000, 'ram_quota': 700, 'ram_usage': 500, 'storage': 10000, 'storage_quota': 7000, 'storage_usage': 5000 } """ service_settings = self.get_object() backend = service_settings.get_backend() try: stats = backend.get_stats() except ServiceBackendNotImplemented: stats = {} return Response(stats, status=status.HTTP_200_OK)
python
def stats(self, request, uuid=None): """ This endpoint returns allocation of resources for current service setting. Answer is service-specific dictionary. Example output for OpenStack: * vcpu - maximum number of vCPUs (from hypervisors) * vcpu_quota - maximum number of vCPUs(from quotas) * vcpu_usage - current number of used vCPUs * ram - total size of memory for allocation (from hypervisors) * ram_quota - maximum number of memory (from quotas) * ram_usage - currently used memory size on all physical hosts * storage - total available disk space on all physical hosts (from hypervisors) * storage_quota - maximum number of storage (from quotas) * storage_usage - currently used storage on all physical hosts { 'vcpu': 10, 'vcpu_quota': 7, 'vcpu_usage': 5, 'ram': 1000, 'ram_quota': 700, 'ram_usage': 500, 'storage': 10000, 'storage_quota': 7000, 'storage_usage': 5000 } """ service_settings = self.get_object() backend = service_settings.get_backend() try: stats = backend.get_stats() except ServiceBackendNotImplemented: stats = {} return Response(stats, status=status.HTTP_200_OK)
[ "def", "stats", "(", "self", ",", "request", ",", "uuid", "=", "None", ")", ":", "service_settings", "=", "self", ".", "get_object", "(", ")", "backend", "=", "service_settings", ".", "get_backend", "(", ")", "try", ":", "stats", "=", "backend", ".", "get_stats", "(", ")", "except", "ServiceBackendNotImplemented", ":", "stats", "=", "{", "}", "return", "Response", "(", "stats", ",", "status", "=", "status", ".", "HTTP_200_OK", ")" ]
This endpoint returns allocation of resources for current service setting. Answer is service-specific dictionary. Example output for OpenStack: * vcpu - maximum number of vCPUs (from hypervisors) * vcpu_quota - maximum number of vCPUs(from quotas) * vcpu_usage - current number of used vCPUs * ram - total size of memory for allocation (from hypervisors) * ram_quota - maximum number of memory (from quotas) * ram_usage - currently used memory size on all physical hosts * storage - total available disk space on all physical hosts (from hypervisors) * storage_quota - maximum number of storage (from quotas) * storage_usage - currently used storage on all physical hosts { 'vcpu': 10, 'vcpu_quota': 7, 'vcpu_usage': 5, 'ram': 1000, 'ram_quota': 700, 'ram_usage': 500, 'storage': 10000, 'storage_quota': 7000, 'storage_usage': 5000 }
[ "This", "endpoint", "returns", "allocation", "of", "resources", "for", "current", "service", "setting", ".", "Answer", "is", "service", "-", "specific", "dictionary", ".", "Example", "output", "for", "OpenStack", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L914-L952
opennode/waldur-core
waldur_core/structure/views.py
ResourceSummaryViewSet.list
def list(self, request, *args, **kwargs): """ To get a list of supported resources' actions, run **OPTIONS** against */api/<resource_url>/* as an authenticated user. It is possible to filter and order by resource-specific fields, but this filters will be applied only to resources that support such filtering. For example it is possible to sort resource by ?o=ram, but SugarCRM crms will ignore this ordering, because they do not support such option. Filter resources by type or category ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ There are two query argument to select resources by their type. - Specify explicitly list of resource types, for example: /api/<resource_endpoint>/?resource_type=DigitalOcean.Droplet&resource_type=OpenStack.Instance - Specify category, one of vms, apps, private_clouds or storages for example: /api/<resource_endpoint>/?category=vms Filtering by monitoring fields ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Resources may have SLA attached to it. Example rendering of SLA: .. code-block:: javascript "sla": { "value": 95.0 "agreed_value": 99.0, "period": "2016-03" } You may filter or order resources by SLA. Default period is current year and month. - Example query for filtering list of resources by actual SLA: /api/<resource_endpoint>/?actual_sla=90&period=2016-02 - Warning! If resource does not have SLA attached to it, it is not included in ordered response. Example query for ordering list of resources by actual SLA: /api/<resource_endpoint>/?o=actual_sla&period=2016-02 Service list is displaying current SLAs for each of the items. By default, SLA period is set to the current month. To change the period pass it as a query argument: - ?period=YYYY-MM - return a list with SLAs for a given month - ?period=YYYY - return a list with SLAs for a given year In all cases all currently running resources are returned, if SLA for the given period is not known or not present, it will be shown as **null** in the response. Resources may have monitoring items attached to it. Example rendering of monitoring items: .. code-block:: javascript "monitoring_items": { "application_state": 1 } You may filter or order resources by monitoring item. - Example query for filtering list of resources by installation state: /api/<resource_endpoint>/?monitoring__installation_state=1 - Warning! If resource does not have monitoring item attached to it, it is not included in ordered response. Example query for ordering list of resources by installation state: /api/<resource_endpoint>/?o=monitoring__installation_state Filtering by tags ^^^^^^^^^^^^^^^^^ Resource may have tags attached to it. Example of tags rendering: .. code-block:: javascript "tags": [ "license-os:centos7", "os-family:linux", "license-application:postgresql", "support:premium" ] Tags filtering: - ?tag=IaaS - filter by full tag name, using method OR. Can be list. - ?rtag=os-family:linux - filter by full tag name, using AND method. Can be list. - ?tag__license-os=centos7 - filter by tags with particular prefix. Tags ordering: - ?o=tag__license-os - order by tag with particular prefix. Instances without given tag will not be returned. """ return super(ResourceSummaryViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ To get a list of supported resources' actions, run **OPTIONS** against */api/<resource_url>/* as an authenticated user. It is possible to filter and order by resource-specific fields, but this filters will be applied only to resources that support such filtering. For example it is possible to sort resource by ?o=ram, but SugarCRM crms will ignore this ordering, because they do not support such option. Filter resources by type or category ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ There are two query argument to select resources by their type. - Specify explicitly list of resource types, for example: /api/<resource_endpoint>/?resource_type=DigitalOcean.Droplet&resource_type=OpenStack.Instance - Specify category, one of vms, apps, private_clouds or storages for example: /api/<resource_endpoint>/?category=vms Filtering by monitoring fields ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Resources may have SLA attached to it. Example rendering of SLA: .. code-block:: javascript "sla": { "value": 95.0 "agreed_value": 99.0, "period": "2016-03" } You may filter or order resources by SLA. Default period is current year and month. - Example query for filtering list of resources by actual SLA: /api/<resource_endpoint>/?actual_sla=90&period=2016-02 - Warning! If resource does not have SLA attached to it, it is not included in ordered response. Example query for ordering list of resources by actual SLA: /api/<resource_endpoint>/?o=actual_sla&period=2016-02 Service list is displaying current SLAs for each of the items. By default, SLA period is set to the current month. To change the period pass it as a query argument: - ?period=YYYY-MM - return a list with SLAs for a given month - ?period=YYYY - return a list with SLAs for a given year In all cases all currently running resources are returned, if SLA for the given period is not known or not present, it will be shown as **null** in the response. Resources may have monitoring items attached to it. Example rendering of monitoring items: .. code-block:: javascript "monitoring_items": { "application_state": 1 } You may filter or order resources by monitoring item. - Example query for filtering list of resources by installation state: /api/<resource_endpoint>/?monitoring__installation_state=1 - Warning! If resource does not have monitoring item attached to it, it is not included in ordered response. Example query for ordering list of resources by installation state: /api/<resource_endpoint>/?o=monitoring__installation_state Filtering by tags ^^^^^^^^^^^^^^^^^ Resource may have tags attached to it. Example of tags rendering: .. code-block:: javascript "tags": [ "license-os:centos7", "os-family:linux", "license-application:postgresql", "support:premium" ] Tags filtering: - ?tag=IaaS - filter by full tag name, using method OR. Can be list. - ?rtag=os-family:linux - filter by full tag name, using AND method. Can be list. - ?tag__license-os=centos7 - filter by tags with particular prefix. Tags ordering: - ?o=tag__license-os - order by tag with particular prefix. Instances without given tag will not be returned. """ return super(ResourceSummaryViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ResourceSummaryViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To get a list of supported resources' actions, run **OPTIONS** against */api/<resource_url>/* as an authenticated user. It is possible to filter and order by resource-specific fields, but this filters will be applied only to resources that support such filtering. For example it is possible to sort resource by ?o=ram, but SugarCRM crms will ignore this ordering, because they do not support such option. Filter resources by type or category ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ There are two query argument to select resources by their type. - Specify explicitly list of resource types, for example: /api/<resource_endpoint>/?resource_type=DigitalOcean.Droplet&resource_type=OpenStack.Instance - Specify category, one of vms, apps, private_clouds or storages for example: /api/<resource_endpoint>/?category=vms Filtering by monitoring fields ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Resources may have SLA attached to it. Example rendering of SLA: .. code-block:: javascript "sla": { "value": 95.0 "agreed_value": 99.0, "period": "2016-03" } You may filter or order resources by SLA. Default period is current year and month. - Example query for filtering list of resources by actual SLA: /api/<resource_endpoint>/?actual_sla=90&period=2016-02 - Warning! If resource does not have SLA attached to it, it is not included in ordered response. Example query for ordering list of resources by actual SLA: /api/<resource_endpoint>/?o=actual_sla&period=2016-02 Service list is displaying current SLAs for each of the items. By default, SLA period is set to the current month. To change the period pass it as a query argument: - ?period=YYYY-MM - return a list with SLAs for a given month - ?period=YYYY - return a list with SLAs for a given year In all cases all currently running resources are returned, if SLA for the given period is not known or not present, it will be shown as **null** in the response. Resources may have monitoring items attached to it. Example rendering of monitoring items: .. code-block:: javascript "monitoring_items": { "application_state": 1 } You may filter or order resources by monitoring item. - Example query for filtering list of resources by installation state: /api/<resource_endpoint>/?monitoring__installation_state=1 - Warning! If resource does not have monitoring item attached to it, it is not included in ordered response. Example query for ordering list of resources by installation state: /api/<resource_endpoint>/?o=monitoring__installation_state Filtering by tags ^^^^^^^^^^^^^^^^^ Resource may have tags attached to it. Example of tags rendering: .. code-block:: javascript "tags": [ "license-os:centos7", "os-family:linux", "license-application:postgresql", "support:premium" ] Tags filtering: - ?tag=IaaS - filter by full tag name, using method OR. Can be list. - ?rtag=os-family:linux - filter by full tag name, using AND method. Can be list. - ?tag__license-os=centos7 - filter by tags with particular prefix. Tags ordering: - ?o=tag__license-os - order by tag with particular prefix. Instances without given tag will not be returned.
[ "To", "get", "a", "list", "of", "supported", "resources", "actions", "run", "**", "OPTIONS", "**", "against", "*", "/", "api", "/", "<resource_url", ">", "/", "*", "as", "an", "authenticated", "user", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L1029-L1128
opennode/waldur-core
waldur_core/structure/views.py
ResourceSummaryViewSet.count
def count(self, request): """ Count resources by type. Example output: .. code-block:: javascript { "Amazon.Instance": 0, "GitLab.Project": 3, "Azure.VirtualMachine": 0, "DigitalOcean.Droplet": 0, "OpenStack.Instance": 0, "GitLab.Group": 8 } """ queryset = self.filter_queryset(self.get_queryset()) return Response({SupportedServices.get_name_for_model(qs.model): qs.count() for qs in queryset.querysets})
python
def count(self, request): """ Count resources by type. Example output: .. code-block:: javascript { "Amazon.Instance": 0, "GitLab.Project": 3, "Azure.VirtualMachine": 0, "DigitalOcean.Droplet": 0, "OpenStack.Instance": 0, "GitLab.Group": 8 } """ queryset = self.filter_queryset(self.get_queryset()) return Response({SupportedServices.get_name_for_model(qs.model): qs.count() for qs in queryset.querysets})
[ "def", "count", "(", "self", ",", "request", ")", ":", "queryset", "=", "self", ".", "filter_queryset", "(", "self", ".", "get_queryset", "(", ")", ")", "return", "Response", "(", "{", "SupportedServices", ".", "get_name_for_model", "(", "qs", ".", "model", ")", ":", "qs", ".", "count", "(", ")", "for", "qs", "in", "queryset", ".", "querysets", "}", ")" ]
Count resources by type. Example output: .. code-block:: javascript { "Amazon.Instance": 0, "GitLab.Project": 3, "Azure.VirtualMachine": 0, "DigitalOcean.Droplet": 0, "OpenStack.Instance": 0, "GitLab.Group": 8 }
[ "Count", "resources", "by", "type", ".", "Example", "output", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L1131-L1148
opennode/waldur-core
waldur_core/structure/views.py
ServicesViewSet.list
def list(self, request, *args, **kwargs): """ Filter services by type ^^^^^^^^^^^^^^^^^^^^^^^ It is possible to filter services by their types. Example: /api/services/?service_type=DigitalOcean&service_type=OpenStack """ return super(ServicesViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ Filter services by type ^^^^^^^^^^^^^^^^^^^^^^^ It is possible to filter services by their types. Example: /api/services/?service_type=DigitalOcean&service_type=OpenStack """ return super(ServicesViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ServicesViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Filter services by type ^^^^^^^^^^^^^^^^^^^^^^^ It is possible to filter services by their types. Example: /api/services/?service_type=DigitalOcean&service_type=OpenStack
[ "Filter", "services", "by", "type", "^^^^^^^^^^^^^^^^^^^^^^^" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L1172-L1181
opennode/waldur-core
waldur_core/structure/views.py
BaseServiceViewSet.list
def list(self, request, *args, **kwargs): """ To list all services without regard to its type, run **GET** against */api/services/* as an authenticated user. To list services of specific type issue **GET** to specific endpoint from a list above as a customer owner. Individual endpoint used for every service type. To create a service, issue a **POST** to specific endpoint from a list above as a customer owner. Individual endpoint used for every service type. You can create service based on shared service settings. Example: .. code-block:: http POST /api/digitalocean/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "Common DigitalOcean", "customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/", "settings": "http://example.com/api/service-settings/93ba615d6111466ebe3f792669059cb4/" } Or provide your own credentials. Example: .. code-block:: http POST /api/oracle/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "My Oracle", "customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/", "backend_url": "https://oracle.example.com:7802/em", "username": "admin", "password": "secret" } """ return super(BaseServiceViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ To list all services without regard to its type, run **GET** against */api/services/* as an authenticated user. To list services of specific type issue **GET** to specific endpoint from a list above as a customer owner. Individual endpoint used for every service type. To create a service, issue a **POST** to specific endpoint from a list above as a customer owner. Individual endpoint used for every service type. You can create service based on shared service settings. Example: .. code-block:: http POST /api/digitalocean/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "Common DigitalOcean", "customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/", "settings": "http://example.com/api/service-settings/93ba615d6111466ebe3f792669059cb4/" } Or provide your own credentials. Example: .. code-block:: http POST /api/oracle/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "My Oracle", "customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/", "backend_url": "https://oracle.example.com:7802/em", "username": "admin", "password": "secret" } """ return super(BaseServiceViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "BaseServiceViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To list all services without regard to its type, run **GET** against */api/services/* as an authenticated user. To list services of specific type issue **GET** to specific endpoint from a list above as a customer owner. Individual endpoint used for every service type. To create a service, issue a **POST** to specific endpoint from a list above as a customer owner. Individual endpoint used for every service type. You can create service based on shared service settings. Example: .. code-block:: http POST /api/digitalocean/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "Common DigitalOcean", "customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/", "settings": "http://example.com/api/service-settings/93ba615d6111466ebe3f792669059cb4/" } Or provide your own credentials. Example: .. code-block:: http POST /api/oracle/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "name": "My Oracle", "customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/", "backend_url": "https://oracle.example.com:7802/em", "username": "admin", "password": "secret" }
[ "To", "list", "all", "services", "without", "regard", "to", "its", "type", "run", "**", "GET", "**", "against", "*", "/", "api", "/", "services", "/", "*", "as", "an", "authenticated", "user", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L1369-L1413
opennode/waldur-core
waldur_core/structure/views.py
BaseServiceViewSet._require_staff_for_shared_settings
def _require_staff_for_shared_settings(request, view, obj=None): """ Allow to execute action only if service settings are not shared or user is staff """ if obj is None: return if obj.settings.shared and not request.user.is_staff: raise PermissionDenied(_('Only staff users are allowed to import resources from shared services.'))
python
def _require_staff_for_shared_settings(request, view, obj=None): """ Allow to execute action only if service settings are not shared or user is staff """ if obj is None: return if obj.settings.shared and not request.user.is_staff: raise PermissionDenied(_('Only staff users are allowed to import resources from shared services.'))
[ "def", "_require_staff_for_shared_settings", "(", "request", ",", "view", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "return", "if", "obj", ".", "settings", ".", "shared", "and", "not", "request", ".", "user", ".", "is_staff", ":", "raise", "PermissionDenied", "(", "_", "(", "'Only staff users are allowed to import resources from shared services.'", ")", ")" ]
Allow to execute action only if service settings are not shared or user is staff
[ "Allow", "to", "execute", "action", "only", "if", "service", "settings", "are", "not", "shared", "or", "user", "is", "staff" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L1452-L1458
opennode/waldur-core
waldur_core/structure/views.py
BaseServiceViewSet.link
def link(self, request, uuid=None): """ To get a list of resources available for import, run **GET** against */<service_endpoint>/link/* as an authenticated user. Optionally project_uuid parameter can be supplied for services requiring it like OpenStack. To import (link with Waldur) resource issue **POST** against the same endpoint with resource id. .. code-block:: http POST /api/openstack/08039f01c9794efc912f1689f4530cf0/link/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "backend_id": "bd5ec24d-9164-440b-a9f2-1b3c807c5df3", "project": "http://example.com/api/projects/e5f973af2eb14d2d8c38d62bcbaccb33/" } """ service = self.get_object() if self.request.method == 'GET': try: backend = self.get_backend(service) try: resources = backend.get_resources_for_import(**self.get_import_context()) except ServiceBackendNotImplemented: resources = [] page = self.paginate_queryset(resources) if page is not None: return self.get_paginated_response(page) return Response(resources) except (ServiceBackendError, ValidationError) as e: raise APIException(e) else: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) try: resource = serializer.save() except ServiceBackendError as e: raise APIException(e) resource_imported.send( sender=resource.__class__, instance=resource, ) return Response(serializer.data, status=status.HTTP_200_OK)
python
def link(self, request, uuid=None): """ To get a list of resources available for import, run **GET** against */<service_endpoint>/link/* as an authenticated user. Optionally project_uuid parameter can be supplied for services requiring it like OpenStack. To import (link with Waldur) resource issue **POST** against the same endpoint with resource id. .. code-block:: http POST /api/openstack/08039f01c9794efc912f1689f4530cf0/link/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "backend_id": "bd5ec24d-9164-440b-a9f2-1b3c807c5df3", "project": "http://example.com/api/projects/e5f973af2eb14d2d8c38d62bcbaccb33/" } """ service = self.get_object() if self.request.method == 'GET': try: backend = self.get_backend(service) try: resources = backend.get_resources_for_import(**self.get_import_context()) except ServiceBackendNotImplemented: resources = [] page = self.paginate_queryset(resources) if page is not None: return self.get_paginated_response(page) return Response(resources) except (ServiceBackendError, ValidationError) as e: raise APIException(e) else: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) try: resource = serializer.save() except ServiceBackendError as e: raise APIException(e) resource_imported.send( sender=resource.__class__, instance=resource, ) return Response(serializer.data, status=status.HTTP_200_OK)
[ "def", "link", "(", "self", ",", "request", ",", "uuid", "=", "None", ")", ":", "service", "=", "self", ".", "get_object", "(", ")", "if", "self", ".", "request", ".", "method", "==", "'GET'", ":", "try", ":", "backend", "=", "self", ".", "get_backend", "(", "service", ")", "try", ":", "resources", "=", "backend", ".", "get_resources_for_import", "(", "*", "*", "self", ".", "get_import_context", "(", ")", ")", "except", "ServiceBackendNotImplemented", ":", "resources", "=", "[", "]", "page", "=", "self", ".", "paginate_queryset", "(", "resources", ")", "if", "page", "is", "not", "None", ":", "return", "self", ".", "get_paginated_response", "(", "page", ")", "return", "Response", "(", "resources", ")", "except", "(", "ServiceBackendError", ",", "ValidationError", ")", "as", "e", ":", "raise", "APIException", "(", "e", ")", "else", ":", "serializer", "=", "self", ".", "get_serializer", "(", "data", "=", "request", ".", "data", ")", "serializer", ".", "is_valid", "(", "raise_exception", "=", "True", ")", "try", ":", "resource", "=", "serializer", ".", "save", "(", ")", "except", "ServiceBackendError", "as", "e", ":", "raise", "APIException", "(", "e", ")", "resource_imported", ".", "send", "(", "sender", "=", "resource", ".", "__class__", ",", "instance", "=", "resource", ",", ")", "return", "Response", "(", "serializer", ".", "data", ",", "status", "=", "status", ".", "HTTP_200_OK", ")" ]
To get a list of resources available for import, run **GET** against */<service_endpoint>/link/* as an authenticated user. Optionally project_uuid parameter can be supplied for services requiring it like OpenStack. To import (link with Waldur) resource issue **POST** against the same endpoint with resource id. .. code-block:: http POST /api/openstack/08039f01c9794efc912f1689f4530cf0/link/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "backend_id": "bd5ec24d-9164-440b-a9f2-1b3c807c5df3", "project": "http://example.com/api/projects/e5f973af2eb14d2d8c38d62bcbaccb33/" }
[ "To", "get", "a", "list", "of", "resources", "available", "for", "import", "run", "**", "GET", "**", "against", "*", "/", "<service_endpoint", ">", "/", "link", "/", "*", "as", "an", "authenticated", "user", ".", "Optionally", "project_uuid", "parameter", "can", "be", "supplied", "for", "services", "requiring", "it", "like", "OpenStack", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L1461-L1515
opennode/waldur-core
waldur_core/structure/views.py
BaseServiceViewSet.unlink
def unlink(self, request, uuid=None): """ Unlink all related resources, service project link and service itself. """ service = self.get_object() service.unlink_descendants() self.perform_destroy(service) return Response(status=status.HTTP_204_NO_CONTENT)
python
def unlink(self, request, uuid=None): """ Unlink all related resources, service project link and service itself. """ service = self.get_object() service.unlink_descendants() self.perform_destroy(service) return Response(status=status.HTTP_204_NO_CONTENT)
[ "def", "unlink", "(", "self", ",", "request", ",", "uuid", "=", "None", ")", ":", "service", "=", "self", ".", "get_object", "(", ")", "service", ".", "unlink_descendants", "(", ")", "self", ".", "perform_destroy", "(", "service", ")", "return", "Response", "(", "status", "=", "status", ".", "HTTP_204_NO_CONTENT", ")" ]
Unlink all related resources, service project link and service itself.
[ "Unlink", "all", "related", "resources", "service", "project", "link", "and", "service", "itself", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L1535-L1543
opennode/waldur-core
waldur_core/structure/views.py
BaseServiceProjectLinkViewSet.list
def list(self, request, *args, **kwargs): """ To get a list of connections between a project and an service, run **GET** against service_project_link_url as authenticated user. Note that a user can only see connections of a project where a user has a role. If service has `available_for_all` flag, project-service connections are created automatically. Otherwise, in order to be able to provision resources, service must first be linked to a project. To do that, **POST** a connection between project and a service to service_project_link_url as stuff user or customer owner. """ return super(BaseServiceProjectLinkViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ To get a list of connections between a project and an service, run **GET** against service_project_link_url as authenticated user. Note that a user can only see connections of a project where a user has a role. If service has `available_for_all` flag, project-service connections are created automatically. Otherwise, in order to be able to provision resources, service must first be linked to a project. To do that, **POST** a connection between project and a service to service_project_link_url as stuff user or customer owner. """ return super(BaseServiceProjectLinkViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "BaseServiceProjectLinkViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To get a list of connections between a project and an service, run **GET** against service_project_link_url as authenticated user. Note that a user can only see connections of a project where a user has a role. If service has `available_for_all` flag, project-service connections are created automatically. Otherwise, in order to be able to provision resources, service must first be linked to a project. To do that, **POST** a connection between project and a service to service_project_link_url as stuff user or customer owner.
[ "To", "get", "a", "list", "of", "connections", "between", "a", "project", "and", "an", "service", "run", "**", "GET", "**", "against", "service_project_link_url", "as", "authenticated", "user", ".", "Note", "that", "a", "user", "can", "only", "see", "connections", "of", "a", "project", "where", "a", "user", "has", "a", "role", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L1560-L1570
opennode/waldur-core
waldur_core/structure/views.py
BaseServiceProjectLinkViewSet.retrieve
def retrieve(self, request, *args, **kwargs): """ To remove a link, issue **DELETE** to URL of the corresponding connection as stuff user or customer owner. """ return super(BaseServiceProjectLinkViewSet, self).retrieve(request, *args, **kwargs)
python
def retrieve(self, request, *args, **kwargs): """ To remove a link, issue **DELETE** to URL of the corresponding connection as stuff user or customer owner. """ return super(BaseServiceProjectLinkViewSet, self).retrieve(request, *args, **kwargs)
[ "def", "retrieve", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "BaseServiceProjectLinkViewSet", ",", "self", ")", ".", "retrieve", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To remove a link, issue **DELETE** to URL of the corresponding connection as stuff user or customer owner.
[ "To", "remove", "a", "link", "issue", "**", "DELETE", "**", "to", "URL", "of", "the", "corresponding", "connection", "as", "stuff", "user", "or", "customer", "owner", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/views.py#L1572-L1576
opennode/waldur-core
waldur_core/quotas/fields.py
QuotaField.get_aggregator_quotas
def get_aggregator_quotas(self, quota): """ Fetch ancestors quotas that have the same name and are registered as aggregator quotas. """ ancestors = quota.scope.get_quota_ancestors() aggregator_quotas = [] for ancestor in ancestors: for ancestor_quota_field in ancestor.get_quotas_fields(field_class=AggregatorQuotaField): if ancestor_quota_field.get_child_quota_name() == quota.name: aggregator_quotas.append(ancestor.quotas.get(name=ancestor_quota_field)) return aggregator_quotas
python
def get_aggregator_quotas(self, quota): """ Fetch ancestors quotas that have the same name and are registered as aggregator quotas. """ ancestors = quota.scope.get_quota_ancestors() aggregator_quotas = [] for ancestor in ancestors: for ancestor_quota_field in ancestor.get_quotas_fields(field_class=AggregatorQuotaField): if ancestor_quota_field.get_child_quota_name() == quota.name: aggregator_quotas.append(ancestor.quotas.get(name=ancestor_quota_field)) return aggregator_quotas
[ "def", "get_aggregator_quotas", "(", "self", ",", "quota", ")", ":", "ancestors", "=", "quota", ".", "scope", ".", "get_quota_ancestors", "(", ")", "aggregator_quotas", "=", "[", "]", "for", "ancestor", "in", "ancestors", ":", "for", "ancestor_quota_field", "in", "ancestor", ".", "get_quotas_fields", "(", "field_class", "=", "AggregatorQuotaField", ")", ":", "if", "ancestor_quota_field", ".", "get_child_quota_name", "(", ")", "==", "quota", ".", "name", ":", "aggregator_quotas", ".", "append", "(", "ancestor", ".", "quotas", ".", "get", "(", "name", "=", "ancestor_quota_field", ")", ")", "return", "aggregator_quotas" ]
Fetch ancestors quotas that have the same name and are registered as aggregator quotas.
[ "Fetch", "ancestors", "quotas", "that", "have", "the", "same", "name", "and", "are", "registered", "as", "aggregator", "quotas", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/fields.py#L122-L130
quora/qcore
qcore/events.py
EventHook.subscribe
def subscribe(self, handler): """Adds a new event handler.""" assert callable(handler), "Invalid handler %s" % handler self.handlers.append(handler)
python
def subscribe(self, handler): """Adds a new event handler.""" assert callable(handler), "Invalid handler %s" % handler self.handlers.append(handler)
[ "def", "subscribe", "(", "self", ",", "handler", ")", ":", "assert", "callable", "(", "handler", ")", ",", "\"Invalid handler %s\"", "%", "handler", "self", ".", "handlers", ".", "append", "(", "handler", ")" ]
Adds a new event handler.
[ "Adds", "a", "new", "event", "handler", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/events.py#L46-L49
quora/qcore
qcore/events.py
EventHook.safe_trigger
def safe_trigger(self, *args): """*Safely* triggers the event by invoking all its handlers, even if few of them raise an exception. If a set of exceptions is raised during handler invocation sequence, this method rethrows the first one. :param args: the arguments to invoke event handlers with. """ error = None # iterate over a copy of the original list because some event handlers # may mutate the list for handler in list(self.handlers): try: handler(*args) except BaseException as e: if error is None: prepare_for_reraise(e) error = e if error is not None: reraise(error)
python
def safe_trigger(self, *args): """*Safely* triggers the event by invoking all its handlers, even if few of them raise an exception. If a set of exceptions is raised during handler invocation sequence, this method rethrows the first one. :param args: the arguments to invoke event handlers with. """ error = None # iterate over a copy of the original list because some event handlers # may mutate the list for handler in list(self.handlers): try: handler(*args) except BaseException as e: if error is None: prepare_for_reraise(e) error = e if error is not None: reraise(error)
[ "def", "safe_trigger", "(", "self", ",", "*", "args", ")", ":", "error", "=", "None", "# iterate over a copy of the original list because some event handlers", "# may mutate the list", "for", "handler", "in", "list", "(", "self", ".", "handlers", ")", ":", "try", ":", "handler", "(", "*", "args", ")", "except", "BaseException", "as", "e", ":", "if", "error", "is", "None", ":", "prepare_for_reraise", "(", "e", ")", "error", "=", "e", "if", "error", "is", "not", "None", ":", "reraise", "(", "error", ")" ]
*Safely* triggers the event by invoking all its handlers, even if few of them raise an exception. If a set of exceptions is raised during handler invocation sequence, this method rethrows the first one. :param args: the arguments to invoke event handlers with.
[ "*", "Safely", "*", "triggers", "the", "event", "by", "invoking", "all", "its", "handlers", "even", "if", "few", "of", "them", "raise", "an", "exception", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/events.py#L55-L76
quora/qcore
qcore/events.py
EventHub.on
def on(self, event, handler): """Attaches the handler to the specified event. @param event: event to attach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param handler: event handler. @return: self, so calls like this can be chained together. """ event_hook = self.get_or_create(event) event_hook.subscribe(handler) return self
python
def on(self, event, handler): """Attaches the handler to the specified event. @param event: event to attach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param handler: event handler. @return: self, so calls like this can be chained together. """ event_hook = self.get_or_create(event) event_hook.subscribe(handler) return self
[ "def", "on", "(", "self", ",", "event", ",", "handler", ")", ":", "event_hook", "=", "self", ".", "get_or_create", "(", "event", ")", "event_hook", ".", "subscribe", "(", "handler", ")", "return", "self" ]
Attaches the handler to the specified event. @param event: event to attach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param handler: event handler. @return: self, so calls like this can be chained together.
[ "Attaches", "the", "handler", "to", "the", "specified", "event", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/events.py#L217-L229
quora/qcore
qcore/events.py
EventHub.off
def off(self, event, handler): """Detaches the handler from the specified event. @param event: event to detach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param handler: event handler. @return: self, so calls like this can be chained together. """ event_hook = self.get_or_create(event) event_hook.unsubscribe(handler) return self
python
def off(self, event, handler): """Detaches the handler from the specified event. @param event: event to detach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param handler: event handler. @return: self, so calls like this can be chained together. """ event_hook = self.get_or_create(event) event_hook.unsubscribe(handler) return self
[ "def", "off", "(", "self", ",", "event", ",", "handler", ")", ":", "event_hook", "=", "self", ".", "get_or_create", "(", "event", ")", "event_hook", ".", "unsubscribe", "(", "handler", ")", "return", "self" ]
Detaches the handler from the specified event. @param event: event to detach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param handler: event handler. @return: self, so calls like this can be chained together.
[ "Detaches", "the", "handler", "from", "the", "specified", "event", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/events.py#L231-L243
quora/qcore
qcore/events.py
EventHub.trigger
def trigger(self, event, *args): """Triggers the specified event by invoking EventHook.trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param args: event arguments. @return: self, so calls like this can be chained together. """ event_hook = self.get_or_create(event) event_hook.trigger(*args) return self
python
def trigger(self, event, *args): """Triggers the specified event by invoking EventHook.trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param args: event arguments. @return: self, so calls like this can be chained together. """ event_hook = self.get_or_create(event) event_hook.trigger(*args) return self
[ "def", "trigger", "(", "self", ",", "event", ",", "*", "args", ")", ":", "event_hook", "=", "self", ".", "get_or_create", "(", "event", ")", "event_hook", ".", "trigger", "(", "*", "args", ")", "return", "self" ]
Triggers the specified event by invoking EventHook.trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param args: event arguments. @return: self, so calls like this can be chained together.
[ "Triggers", "the", "specified", "event", "by", "invoking", "EventHook", ".", "trigger", "under", "the", "hood", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/events.py#L245-L257
quora/qcore
qcore/events.py
EventHub.safe_trigger
def safe_trigger(self, event, *args): """Safely triggers the specified event by invoking EventHook.safe_trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param args: event arguments. @return: self, so calls like this can be chained together. """ event_hook = self.get_or_create(event) event_hook.safe_trigger(*args) return self
python
def safe_trigger(self, event, *args): """Safely triggers the specified event by invoking EventHook.safe_trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param args: event arguments. @return: self, so calls like this can be chained together. """ event_hook = self.get_or_create(event) event_hook.safe_trigger(*args) return self
[ "def", "safe_trigger", "(", "self", ",", "event", ",", "*", "args", ")", ":", "event_hook", "=", "self", ".", "get_or_create", "(", "event", ")", "event_hook", ".", "safe_trigger", "(", "*", "args", ")", "return", "self" ]
Safely triggers the specified event by invoking EventHook.safe_trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param args: event arguments. @return: self, so calls like this can be chained together.
[ "Safely", "triggers", "the", "specified", "event", "by", "invoking", "EventHook", ".", "safe_trigger", "under", "the", "hood", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/events.py#L259-L272
quora/qcore
qcore/events.py
EventHub.get_or_create
def get_or_create(self, event): """Gets or creates a new event hook for the specified event (key). This method treats qcore.EnumBase-typed event keys specially: enum_member.name is used as key instead of enum instance in case such a key is passed. Note that on/off/trigger/safe_trigger methods rely on this method, so you can pass enum members there as well. """ if isinstance(event, EnumBase): event = event.short_name return self.__dict__.setdefault(event, EventHook())
python
def get_or_create(self, event): """Gets or creates a new event hook for the specified event (key). This method treats qcore.EnumBase-typed event keys specially: enum_member.name is used as key instead of enum instance in case such a key is passed. Note that on/off/trigger/safe_trigger methods rely on this method, so you can pass enum members there as well. """ if isinstance(event, EnumBase): event = event.short_name return self.__dict__.setdefault(event, EventHook())
[ "def", "get_or_create", "(", "self", ",", "event", ")", ":", "if", "isinstance", "(", "event", ",", "EnumBase", ")", ":", "event", "=", "event", ".", "short_name", "return", "self", ".", "__dict__", ".", "setdefault", "(", "event", ",", "EventHook", "(", ")", ")" ]
Gets or creates a new event hook for the specified event (key). This method treats qcore.EnumBase-typed event keys specially: enum_member.name is used as key instead of enum instance in case such a key is passed. Note that on/off/trigger/safe_trigger methods rely on this method, so you can pass enum members there as well.
[ "Gets", "or", "creates", "a", "new", "event", "hook", "for", "the", "specified", "event", "(", "key", ")", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/events.py#L274-L287
opennode/waldur-core
waldur_core/users/tasks.py
cancel_expired_invitations
def cancel_expired_invitations(invitations=None): """ Invitation lifetime must be specified in Waldur Core settings with parameter "INVITATION_LIFETIME". If invitation creation time is less than expiration time, the invitation will set as expired. """ expiration_date = timezone.now() - settings.WALDUR_CORE['INVITATION_LIFETIME'] if not invitations: invitations = models.Invitation.objects.filter(state=models.Invitation.State.PENDING) invitations = invitations.filter(created__lte=expiration_date) invitations.update(state=models.Invitation.State.EXPIRED)
python
def cancel_expired_invitations(invitations=None): """ Invitation lifetime must be specified in Waldur Core settings with parameter "INVITATION_LIFETIME". If invitation creation time is less than expiration time, the invitation will set as expired. """ expiration_date = timezone.now() - settings.WALDUR_CORE['INVITATION_LIFETIME'] if not invitations: invitations = models.Invitation.objects.filter(state=models.Invitation.State.PENDING) invitations = invitations.filter(created__lte=expiration_date) invitations.update(state=models.Invitation.State.EXPIRED)
[ "def", "cancel_expired_invitations", "(", "invitations", "=", "None", ")", ":", "expiration_date", "=", "timezone", ".", "now", "(", ")", "-", "settings", ".", "WALDUR_CORE", "[", "'INVITATION_LIFETIME'", "]", "if", "not", "invitations", ":", "invitations", "=", "models", ".", "Invitation", ".", "objects", ".", "filter", "(", "state", "=", "models", ".", "Invitation", ".", "State", ".", "PENDING", ")", "invitations", "=", "invitations", ".", "filter", "(", "created__lte", "=", "expiration_date", ")", "invitations", ".", "update", "(", "state", "=", "models", ".", "Invitation", ".", "State", ".", "EXPIRED", ")" ]
Invitation lifetime must be specified in Waldur Core settings with parameter "INVITATION_LIFETIME". If invitation creation time is less than expiration time, the invitation will set as expired.
[ "Invitation", "lifetime", "must", "be", "specified", "in", "Waldur", "Core", "settings", "with", "parameter", "INVITATION_LIFETIME", ".", "If", "invitation", "creation", "time", "is", "less", "than", "expiration", "time", "the", "invitation", "will", "set", "as", "expired", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/users/tasks.py#L19-L28
tintinweb/ethereum-input-decoder
ethereum_input_decoder/decoder.py
FourByteDirectory.get_pseudo_abi_for_input
def get_pseudo_abi_for_input(s, timeout=None, proxies=None): """ Lookup sighash from 4bytes.directory, create a pseudo api and try to decode it with the parsed abi. May return multiple results as sighashes may collide. :param s: bytes input :return: pseudo abi for method """ sighash = Utils.bytes_to_str(s[:4]) for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_sighash(sighash, timeout=timeout, proxies=proxies): types = [ti["type"] for ti in pseudo_abi['inputs']] try: # test decoding _ = decode_abi(types, s[4:]) yield pseudo_abi except eth_abi.exceptions.DecodingError as e: continue
python
def get_pseudo_abi_for_input(s, timeout=None, proxies=None): """ Lookup sighash from 4bytes.directory, create a pseudo api and try to decode it with the parsed abi. May return multiple results as sighashes may collide. :param s: bytes input :return: pseudo abi for method """ sighash = Utils.bytes_to_str(s[:4]) for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_sighash(sighash, timeout=timeout, proxies=proxies): types = [ti["type"] for ti in pseudo_abi['inputs']] try: # test decoding _ = decode_abi(types, s[4:]) yield pseudo_abi except eth_abi.exceptions.DecodingError as e: continue
[ "def", "get_pseudo_abi_for_input", "(", "s", ",", "timeout", "=", "None", ",", "proxies", "=", "None", ")", ":", "sighash", "=", "Utils", ".", "bytes_to_str", "(", "s", "[", ":", "4", "]", ")", "for", "pseudo_abi", "in", "FourByteDirectory", ".", "get_pseudo_abi_for_sighash", "(", "sighash", ",", "timeout", "=", "timeout", ",", "proxies", "=", "proxies", ")", ":", "types", "=", "[", "ti", "[", "\"type\"", "]", "for", "ti", "in", "pseudo_abi", "[", "'inputs'", "]", "]", "try", ":", "# test decoding", "_", "=", "decode_abi", "(", "types", ",", "s", "[", "4", ":", "]", ")", "yield", "pseudo_abi", "except", "eth_abi", ".", "exceptions", ".", "DecodingError", "as", "e", ":", "continue" ]
Lookup sighash from 4bytes.directory, create a pseudo api and try to decode it with the parsed abi. May return multiple results as sighashes may collide. :param s: bytes input :return: pseudo abi for method
[ "Lookup", "sighash", "from", "4bytes", ".", "directory", "create", "a", "pseudo", "api", "and", "try", "to", "decode", "it", "with", "the", "parsed", "abi", ".", "May", "return", "multiple", "results", "as", "sighashes", "may", "collide", ".", ":", "param", "s", ":", "bytes", "input", ":", "return", ":", "pseudo", "abi", "for", "method" ]
train
https://github.com/tintinweb/ethereum-input-decoder/blob/aa96623e352fe096b6679cc3ea10ef62a260a711/ethereum_input_decoder/decoder.py#L70-L85
tintinweb/ethereum-input-decoder
ethereum_input_decoder/decoder.py
ContractAbi._prepare_abi
def _prepare_abi(self, jsonabi): """ Prepare the contract json abi for sighash lookups and fast access :param jsonabi: contracts abi in json format :return: """ self.signatures = {} for element_description in jsonabi: abi_e = AbiMethod(element_description) if abi_e["type"] == "constructor": self.signatures[b"__constructor__"] = abi_e elif abi_e["type"] == "fallback": abi_e.setdefault("inputs", []) self.signatures[b"__fallback__"] = abi_e elif abi_e["type"] == "function": # function and signature present # todo: we could generate the sighash ourselves? requires keccak256 if abi_e.get("signature"): self.signatures[Utils.str_to_bytes(abi_e["signature"])] = abi_e elif abi_e["type"] == "event": self.signatures[b"__event__"] = abi_e else: raise Exception("Invalid abi type: %s - %s - %s" % (abi_e.get("type"), element_description, abi_e))
python
def _prepare_abi(self, jsonabi): """ Prepare the contract json abi for sighash lookups and fast access :param jsonabi: contracts abi in json format :return: """ self.signatures = {} for element_description in jsonabi: abi_e = AbiMethod(element_description) if abi_e["type"] == "constructor": self.signatures[b"__constructor__"] = abi_e elif abi_e["type"] == "fallback": abi_e.setdefault("inputs", []) self.signatures[b"__fallback__"] = abi_e elif abi_e["type"] == "function": # function and signature present # todo: we could generate the sighash ourselves? requires keccak256 if abi_e.get("signature"): self.signatures[Utils.str_to_bytes(abi_e["signature"])] = abi_e elif abi_e["type"] == "event": self.signatures[b"__event__"] = abi_e else: raise Exception("Invalid abi type: %s - %s - %s" % (abi_e.get("type"), element_description, abi_e))
[ "def", "_prepare_abi", "(", "self", ",", "jsonabi", ")", ":", "self", ".", "signatures", "=", "{", "}", "for", "element_description", "in", "jsonabi", ":", "abi_e", "=", "AbiMethod", "(", "element_description", ")", "if", "abi_e", "[", "\"type\"", "]", "==", "\"constructor\"", ":", "self", ".", "signatures", "[", "b\"__constructor__\"", "]", "=", "abi_e", "elif", "abi_e", "[", "\"type\"", "]", "==", "\"fallback\"", ":", "abi_e", ".", "setdefault", "(", "\"inputs\"", ",", "[", "]", ")", "self", ".", "signatures", "[", "b\"__fallback__\"", "]", "=", "abi_e", "elif", "abi_e", "[", "\"type\"", "]", "==", "\"function\"", ":", "# function and signature present", "# todo: we could generate the sighash ourselves? requires keccak256", "if", "abi_e", ".", "get", "(", "\"signature\"", ")", ":", "self", ".", "signatures", "[", "Utils", ".", "str_to_bytes", "(", "abi_e", "[", "\"signature\"", "]", ")", "]", "=", "abi_e", "elif", "abi_e", "[", "\"type\"", "]", "==", "\"event\"", ":", "self", ".", "signatures", "[", "b\"__event__\"", "]", "=", "abi_e", "else", ":", "raise", "Exception", "(", "\"Invalid abi type: %s - %s - %s\"", "%", "(", "abi_e", ".", "get", "(", "\"type\"", ")", ",", "element_description", ",", "abi_e", ")", ")" ]
Prepare the contract json abi for sighash lookups and fast access :param jsonabi: contracts abi in json format :return:
[ "Prepare", "the", "contract", "json", "abi", "for", "sighash", "lookups", "and", "fast", "access" ]
train
https://github.com/tintinweb/ethereum-input-decoder/blob/aa96623e352fe096b6679cc3ea10ef62a260a711/ethereum_input_decoder/decoder.py#L101-L125
tintinweb/ethereum-input-decoder
ethereum_input_decoder/decoder.py
ContractAbi.describe_constructor
def describe_constructor(self, s): """ Describe the input bytesequence (constructor arguments) s based on the loaded contract abi definition :param s: bytes constructor arguments :return: AbiMethod instance """ method = self.signatures.get(b"__constructor__") if not method: # constructor not available m = AbiMethod({"type": "constructor", "name": "", "inputs": [], "outputs": []}) return m types_def = method["inputs"] types = [t["type"] for t in types_def] names = [t["name"] for t in types_def] if not len(s): values = len(types) * ["<nA>"] else: values = decode_abi(types, s) # (type, name, data) method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list( zip(types, names, values))] return method
python
def describe_constructor(self, s): """ Describe the input bytesequence (constructor arguments) s based on the loaded contract abi definition :param s: bytes constructor arguments :return: AbiMethod instance """ method = self.signatures.get(b"__constructor__") if not method: # constructor not available m = AbiMethod({"type": "constructor", "name": "", "inputs": [], "outputs": []}) return m types_def = method["inputs"] types = [t["type"] for t in types_def] names = [t["name"] for t in types_def] if not len(s): values = len(types) * ["<nA>"] else: values = decode_abi(types, s) # (type, name, data) method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list( zip(types, names, values))] return method
[ "def", "describe_constructor", "(", "self", ",", "s", ")", ":", "method", "=", "self", ".", "signatures", ".", "get", "(", "b\"__constructor__\"", ")", "if", "not", "method", ":", "# constructor not available", "m", "=", "AbiMethod", "(", "{", "\"type\"", ":", "\"constructor\"", ",", "\"name\"", ":", "\"\"", ",", "\"inputs\"", ":", "[", "]", ",", "\"outputs\"", ":", "[", "]", "}", ")", "return", "m", "types_def", "=", "method", "[", "\"inputs\"", "]", "types", "=", "[", "t", "[", "\"type\"", "]", "for", "t", "in", "types_def", "]", "names", "=", "[", "t", "[", "\"name\"", "]", "for", "t", "in", "types_def", "]", "if", "not", "len", "(", "s", ")", ":", "values", "=", "len", "(", "types", ")", "*", "[", "\"<nA>\"", "]", "else", ":", "values", "=", "decode_abi", "(", "types", ",", "s", ")", "# (type, name, data)", "method", ".", "inputs", "=", "[", "{", "\"type\"", ":", "t", ",", "\"name\"", ":", "n", ",", "\"data\"", ":", "v", "}", "for", "t", ",", "n", ",", "v", "in", "list", "(", "zip", "(", "types", ",", "names", ",", "values", ")", ")", "]", "return", "method" ]
Describe the input bytesequence (constructor arguments) s based on the loaded contract abi definition :param s: bytes constructor arguments :return: AbiMethod instance
[ "Describe", "the", "input", "bytesequence", "(", "constructor", "arguments", ")", "s", "based", "on", "the", "loaded", "contract", "abi", "definition" ]
train
https://github.com/tintinweb/ethereum-input-decoder/blob/aa96623e352fe096b6679cc3ea10ef62a260a711/ethereum_input_decoder/decoder.py#L127-L153
tintinweb/ethereum-input-decoder
ethereum_input_decoder/decoder.py
ContractAbi.describe_input
def describe_input(self, s): """ Describe the input bytesequence s based on the loaded contract abi definition :param s: bytes input :return: AbiMethod instance """ signatures = self.signatures.items() for sighash, method in signatures: if sighash is None or sighash.startswith(b"__"): continue # skip constructor if s.startswith(sighash): s = s[len(sighash):] types_def = self.signatures.get(sighash)["inputs"] types = [t["type"] for t in types_def] names = [t["name"] for t in types_def] if not len(s): values = len(types) * ["<nA>"] else: values = decode_abi(types, s) # (type, name, data) method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list( zip(types, names, values))] return method else: method = AbiMethod({"type": "fallback", "name": "__fallback__", "inputs": [], "outputs": []}) types_def = self.signatures.get(b"__fallback__", {"inputs": []})["inputs"] types = [t["type"] for t in types_def] names = [t["name"] for t in types_def] values = decode_abi(types, s) # (type, name, data) method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list( zip(types, names, values))] return method
python
def describe_input(self, s): """ Describe the input bytesequence s based on the loaded contract abi definition :param s: bytes input :return: AbiMethod instance """ signatures = self.signatures.items() for sighash, method in signatures: if sighash is None or sighash.startswith(b"__"): continue # skip constructor if s.startswith(sighash): s = s[len(sighash):] types_def = self.signatures.get(sighash)["inputs"] types = [t["type"] for t in types_def] names = [t["name"] for t in types_def] if not len(s): values = len(types) * ["<nA>"] else: values = decode_abi(types, s) # (type, name, data) method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list( zip(types, names, values))] return method else: method = AbiMethod({"type": "fallback", "name": "__fallback__", "inputs": [], "outputs": []}) types_def = self.signatures.get(b"__fallback__", {"inputs": []})["inputs"] types = [t["type"] for t in types_def] names = [t["name"] for t in types_def] values = decode_abi(types, s) # (type, name, data) method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list( zip(types, names, values))] return method
[ "def", "describe_input", "(", "self", ",", "s", ")", ":", "signatures", "=", "self", ".", "signatures", ".", "items", "(", ")", "for", "sighash", ",", "method", "in", "signatures", ":", "if", "sighash", "is", "None", "or", "sighash", ".", "startswith", "(", "b\"__\"", ")", ":", "continue", "# skip constructor", "if", "s", ".", "startswith", "(", "sighash", ")", ":", "s", "=", "s", "[", "len", "(", "sighash", ")", ":", "]", "types_def", "=", "self", ".", "signatures", ".", "get", "(", "sighash", ")", "[", "\"inputs\"", "]", "types", "=", "[", "t", "[", "\"type\"", "]", "for", "t", "in", "types_def", "]", "names", "=", "[", "t", "[", "\"name\"", "]", "for", "t", "in", "types_def", "]", "if", "not", "len", "(", "s", ")", ":", "values", "=", "len", "(", "types", ")", "*", "[", "\"<nA>\"", "]", "else", ":", "values", "=", "decode_abi", "(", "types", ",", "s", ")", "# (type, name, data)", "method", ".", "inputs", "=", "[", "{", "\"type\"", ":", "t", ",", "\"name\"", ":", "n", ",", "\"data\"", ":", "v", "}", "for", "t", ",", "n", ",", "v", "in", "list", "(", "zip", "(", "types", ",", "names", ",", "values", ")", ")", "]", "return", "method", "else", ":", "method", "=", "AbiMethod", "(", "{", "\"type\"", ":", "\"fallback\"", ",", "\"name\"", ":", "\"__fallback__\"", ",", "\"inputs\"", ":", "[", "]", ",", "\"outputs\"", ":", "[", "]", "}", ")", "types_def", "=", "self", ".", "signatures", ".", "get", "(", "b\"__fallback__\"", ",", "{", "\"inputs\"", ":", "[", "]", "}", ")", "[", "\"inputs\"", "]", "types", "=", "[", "t", "[", "\"type\"", "]", "for", "t", "in", "types_def", "]", "names", "=", "[", "t", "[", "\"name\"", "]", "for", "t", "in", "types_def", "]", "values", "=", "decode_abi", "(", "types", ",", "s", ")", "# (type, name, data)", "method", ".", "inputs", "=", "[", "{", "\"type\"", ":", "t", ",", "\"name\"", ":", "n", ",", "\"data\"", ":", "v", "}", "for", "t", ",", "n", ",", "v", "in", "list", "(", "zip", "(", "types", ",", "names", ",", "values", ")", ")", "]", "return", "method" ]
Describe the input bytesequence s based on the loaded contract abi definition :param s: bytes input :return: AbiMethod instance
[ "Describe", "the", "input", "bytesequence", "s", "based", "on", "the", "loaded", "contract", "abi", "definition" ]
train
https://github.com/tintinweb/ethereum-input-decoder/blob/aa96623e352fe096b6679cc3ea10ef62a260a711/ethereum_input_decoder/decoder.py#L155-L197
tintinweb/ethereum-input-decoder
ethereum_input_decoder/decoder.py
AbiMethod.from_input_lookup
def from_input_lookup(s): """ Return a new AbiMethod object from an input stream :param s: binary input :return: new AbiMethod object matching the provided input stream """ for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_input(s): method = AbiMethod(pseudo_abi) types_def = pseudo_abi["inputs"] types = [t["type"] for t in types_def] names = [t["name"] for t in types_def] values = decode_abi(types, s[4:]) # (type, name, data) method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list( zip(types, names, values))] return method
python
def from_input_lookup(s): """ Return a new AbiMethod object from an input stream :param s: binary input :return: new AbiMethod object matching the provided input stream """ for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_input(s): method = AbiMethod(pseudo_abi) types_def = pseudo_abi["inputs"] types = [t["type"] for t in types_def] names = [t["name"] for t in types_def] values = decode_abi(types, s[4:]) # (type, name, data) method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list( zip(types, names, values))] return method
[ "def", "from_input_lookup", "(", "s", ")", ":", "for", "pseudo_abi", "in", "FourByteDirectory", ".", "get_pseudo_abi_for_input", "(", "s", ")", ":", "method", "=", "AbiMethod", "(", "pseudo_abi", ")", "types_def", "=", "pseudo_abi", "[", "\"inputs\"", "]", "types", "=", "[", "t", "[", "\"type\"", "]", "for", "t", "in", "types_def", "]", "names", "=", "[", "t", "[", "\"name\"", "]", "for", "t", "in", "types_def", "]", "values", "=", "decode_abi", "(", "types", ",", "s", "[", "4", ":", "]", ")", "# (type, name, data)", "method", ".", "inputs", "=", "[", "{", "\"type\"", ":", "t", ",", "\"name\"", ":", "n", ",", "\"data\"", ":", "v", "}", "for", "t", ",", "n", ",", "v", "in", "list", "(", "zip", "(", "types", ",", "names", ",", "values", ")", ")", "]", "return", "method" ]
Return a new AbiMethod object from an input stream :param s: binary input :return: new AbiMethod object matching the provided input stream
[ "Return", "a", "new", "AbiMethod", "object", "from", "an", "input", "stream", ":", "param", "s", ":", "binary", "input", ":", "return", ":", "new", "AbiMethod", "object", "matching", "the", "provided", "input", "stream" ]
train
https://github.com/tintinweb/ethereum-input-decoder/blob/aa96623e352fe096b6679cc3ea10ef62a260a711/ethereum_input_decoder/decoder.py#L213-L230
quora/qcore
qcore/asserts.py
assert_is
def assert_is(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is not actual.""" assert expected is actual, _assert_fail_message( message, expected, actual, "is not", extra )
python
def assert_is(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is not actual.""" assert expected is actual, _assert_fail_message( message, expected, actual, "is not", extra )
[ "def", "assert_is", "(", "expected", ",", "actual", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "expected", "is", "actual", ",", "_assert_fail_message", "(", "message", ",", "expected", ",", "actual", ",", "\"is not\"", ",", "extra", ")" ]
Raises an AssertionError if expected is not actual.
[ "Raises", "an", "AssertionError", "if", "expected", "is", "not", "actual", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L83-L87
quora/qcore
qcore/asserts.py
assert_is_not
def assert_is_not(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is actual.""" assert expected is not actual, _assert_fail_message( message, expected, actual, "is", extra )
python
def assert_is_not(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is actual.""" assert expected is not actual, _assert_fail_message( message, expected, actual, "is", extra )
[ "def", "assert_is_not", "(", "expected", ",", "actual", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "expected", "is", "not", "actual", ",", "_assert_fail_message", "(", "message", ",", "expected", ",", "actual", ",", "\"is\"", ",", "extra", ")" ]
Raises an AssertionError if expected is actual.
[ "Raises", "an", "AssertionError", "if", "expected", "is", "actual", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L90-L94
quora/qcore
qcore/asserts.py
assert_is_instance
def assert_is_instance(value, types, message=None, extra=None): """Raises an AssertionError if value is not an instance of type(s).""" assert isinstance(value, types), _assert_fail_message( message, value, types, "is not an instance of", extra )
python
def assert_is_instance(value, types, message=None, extra=None): """Raises an AssertionError if value is not an instance of type(s).""" assert isinstance(value, types), _assert_fail_message( message, value, types, "is not an instance of", extra )
[ "def", "assert_is_instance", "(", "value", ",", "types", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "isinstance", "(", "value", ",", "types", ")", ",", "_assert_fail_message", "(", "message", ",", "value", ",", "types", ",", "\"is not an instance of\"", ",", "extra", ")" ]
Raises an AssertionError if value is not an instance of type(s).
[ "Raises", "an", "AssertionError", "if", "value", "is", "not", "an", "instance", "of", "type", "(", "s", ")", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L97-L101
quora/qcore
qcore/asserts.py
assert_eq
def assert_eq(expected, actual, message=None, tolerance=None, extra=None): """Raises an AssertionError if expected != actual. If tolerance is specified, raises an AssertionError if either - expected or actual isn't a number, or - the difference between expected and actual is larger than the tolerance. """ if tolerance is None: assert expected == actual, _assert_fail_message( message, expected, actual, "!=", extra ) else: assert isinstance(tolerance, _number_types), ( "tolerance parameter to assert_eq must be a number: %r" % tolerance ) assert isinstance(expected, _number_types) and isinstance( actual, _number_types ), ( "parameters must be numbers when tolerance is specified: %r, %r" % (expected, actual) ) diff = abs(expected - actual) assert diff <= tolerance, _assert_fail_message( message, expected, actual, "is more than %r away from" % tolerance, extra )
python
def assert_eq(expected, actual, message=None, tolerance=None, extra=None): """Raises an AssertionError if expected != actual. If tolerance is specified, raises an AssertionError if either - expected or actual isn't a number, or - the difference between expected and actual is larger than the tolerance. """ if tolerance is None: assert expected == actual, _assert_fail_message( message, expected, actual, "!=", extra ) else: assert isinstance(tolerance, _number_types), ( "tolerance parameter to assert_eq must be a number: %r" % tolerance ) assert isinstance(expected, _number_types) and isinstance( actual, _number_types ), ( "parameters must be numbers when tolerance is specified: %r, %r" % (expected, actual) ) diff = abs(expected - actual) assert diff <= tolerance, _assert_fail_message( message, expected, actual, "is more than %r away from" % tolerance, extra )
[ "def", "assert_eq", "(", "expected", ",", "actual", ",", "message", "=", "None", ",", "tolerance", "=", "None", ",", "extra", "=", "None", ")", ":", "if", "tolerance", "is", "None", ":", "assert", "expected", "==", "actual", ",", "_assert_fail_message", "(", "message", ",", "expected", ",", "actual", ",", "\"!=\"", ",", "extra", ")", "else", ":", "assert", "isinstance", "(", "tolerance", ",", "_number_types", ")", ",", "(", "\"tolerance parameter to assert_eq must be a number: %r\"", "%", "tolerance", ")", "assert", "isinstance", "(", "expected", ",", "_number_types", ")", "and", "isinstance", "(", "actual", ",", "_number_types", ")", ",", "(", "\"parameters must be numbers when tolerance is specified: %r, %r\"", "%", "(", "expected", ",", "actual", ")", ")", "diff", "=", "abs", "(", "expected", "-", "actual", ")", "assert", "diff", "<=", "tolerance", ",", "_assert_fail_message", "(", "message", ",", "expected", ",", "actual", ",", "\"is more than %r away from\"", "%", "tolerance", ",", "extra", ")" ]
Raises an AssertionError if expected != actual. If tolerance is specified, raises an AssertionError if either - expected or actual isn't a number, or - the difference between expected and actual is larger than the tolerance.
[ "Raises", "an", "AssertionError", "if", "expected", "!", "=", "actual", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L104-L130
quora/qcore
qcore/asserts.py
assert_dict_eq
def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): """Asserts that two dictionaries are equal, producing a custom message if they are not.""" assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys = set(expected.keys()) actual_keys = set(actual.keys()) assert expected_keys <= actual_keys, "Actual dict at %s is missing keys: %r" % ( _dict_path_string(dict_path), expected_keys - actual_keys, ) assert actual_keys <= expected_keys, "Actual dict at %s has extra keys: %r" % ( _dict_path_string(dict_path), actual_keys - expected_keys, ) for k in expected_keys: key_path = dict_path + [k] assert_is_instance( actual[k], type(expected[k]), extra="Types don't match for %s" % _dict_path_string(key_path), ) assert_is_instance( expected[k], type(actual[k]), extra="Types don't match for %s" % _dict_path_string(key_path), ) if isinstance(actual[k], dict): assert_dict_eq( expected[k], actual[k], number_tolerance=number_tolerance, dict_path=key_path, ) elif isinstance(actual[k], _number_types): assert_eq( expected[k], actual[k], extra="Value doesn't match for %s" % _dict_path_string(key_path), tolerance=number_tolerance, ) else: assert_eq( expected[k], actual[k], extra="Value doesn't match for %s" % _dict_path_string(key_path), )
python
def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): """Asserts that two dictionaries are equal, producing a custom message if they are not.""" assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys = set(expected.keys()) actual_keys = set(actual.keys()) assert expected_keys <= actual_keys, "Actual dict at %s is missing keys: %r" % ( _dict_path_string(dict_path), expected_keys - actual_keys, ) assert actual_keys <= expected_keys, "Actual dict at %s has extra keys: %r" % ( _dict_path_string(dict_path), actual_keys - expected_keys, ) for k in expected_keys: key_path = dict_path + [k] assert_is_instance( actual[k], type(expected[k]), extra="Types don't match for %s" % _dict_path_string(key_path), ) assert_is_instance( expected[k], type(actual[k]), extra="Types don't match for %s" % _dict_path_string(key_path), ) if isinstance(actual[k], dict): assert_dict_eq( expected[k], actual[k], number_tolerance=number_tolerance, dict_path=key_path, ) elif isinstance(actual[k], _number_types): assert_eq( expected[k], actual[k], extra="Value doesn't match for %s" % _dict_path_string(key_path), tolerance=number_tolerance, ) else: assert_eq( expected[k], actual[k], extra="Value doesn't match for %s" % _dict_path_string(key_path), )
[ "def", "assert_dict_eq", "(", "expected", ",", "actual", ",", "number_tolerance", "=", "None", ",", "dict_path", "=", "[", "]", ")", ":", "assert_is_instance", "(", "expected", ",", "dict", ")", "assert_is_instance", "(", "actual", ",", "dict", ")", "expected_keys", "=", "set", "(", "expected", ".", "keys", "(", ")", ")", "actual_keys", "=", "set", "(", "actual", ".", "keys", "(", ")", ")", "assert", "expected_keys", "<=", "actual_keys", ",", "\"Actual dict at %s is missing keys: %r\"", "%", "(", "_dict_path_string", "(", "dict_path", ")", ",", "expected_keys", "-", "actual_keys", ",", ")", "assert", "actual_keys", "<=", "expected_keys", ",", "\"Actual dict at %s has extra keys: %r\"", "%", "(", "_dict_path_string", "(", "dict_path", ")", ",", "actual_keys", "-", "expected_keys", ",", ")", "for", "k", "in", "expected_keys", ":", "key_path", "=", "dict_path", "+", "[", "k", "]", "assert_is_instance", "(", "actual", "[", "k", "]", ",", "type", "(", "expected", "[", "k", "]", ")", ",", "extra", "=", "\"Types don't match for %s\"", "%", "_dict_path_string", "(", "key_path", ")", ",", ")", "assert_is_instance", "(", "expected", "[", "k", "]", ",", "type", "(", "actual", "[", "k", "]", ")", ",", "extra", "=", "\"Types don't match for %s\"", "%", "_dict_path_string", "(", "key_path", ")", ",", ")", "if", "isinstance", "(", "actual", "[", "k", "]", ",", "dict", ")", ":", "assert_dict_eq", "(", "expected", "[", "k", "]", ",", "actual", "[", "k", "]", ",", "number_tolerance", "=", "number_tolerance", ",", "dict_path", "=", "key_path", ",", ")", "elif", "isinstance", "(", "actual", "[", "k", "]", ",", "_number_types", ")", ":", "assert_eq", "(", "expected", "[", "k", "]", ",", "actual", "[", "k", "]", ",", "extra", "=", "\"Value doesn't match for %s\"", "%", "_dict_path_string", "(", "key_path", ")", ",", "tolerance", "=", "number_tolerance", ",", ")", "else", ":", "assert_eq", "(", "expected", "[", "k", "]", ",", "actual", "[", "k", "]", ",", "extra", "=", "\"Value doesn't match for %s\"", "%", "_dict_path_string", "(", "key_path", ")", ",", ")" ]
Asserts that two dictionaries are equal, producing a custom message if they are not.
[ "Asserts", "that", "two", "dictionaries", "are", "equal", "producing", "a", "custom", "message", "if", "they", "are", "not", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L139-L187
quora/qcore
qcore/asserts.py
assert_gt
def assert_gt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand <= right_hand.""" assert left > right, _assert_fail_message(message, left, right, "<=", extra)
python
def assert_gt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand <= right_hand.""" assert left > right, _assert_fail_message(message, left, right, "<=", extra)
[ "def", "assert_gt", "(", "left", ",", "right", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "left", ">", "right", ",", "_assert_fail_message", "(", "message", ",", "left", ",", "right", ",", "\"<=\"", ",", "extra", ")" ]
Raises an AssertionError if left_hand <= right_hand.
[ "Raises", "an", "AssertionError", "if", "left_hand", "<", "=", "right_hand", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L219-L221
quora/qcore
qcore/asserts.py
assert_ge
def assert_ge(left, right, message=None, extra=None): """Raises an AssertionError if left_hand < right_hand.""" assert left >= right, _assert_fail_message(message, left, right, "<", extra)
python
def assert_ge(left, right, message=None, extra=None): """Raises an AssertionError if left_hand < right_hand.""" assert left >= right, _assert_fail_message(message, left, right, "<", extra)
[ "def", "assert_ge", "(", "left", ",", "right", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "left", ">=", "right", ",", "_assert_fail_message", "(", "message", ",", "left", ",", "right", ",", "\"<\"", ",", "extra", ")" ]
Raises an AssertionError if left_hand < right_hand.
[ "Raises", "an", "AssertionError", "if", "left_hand", "<", "right_hand", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L224-L226
quora/qcore
qcore/asserts.py
assert_lt
def assert_lt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand >= right_hand.""" assert left < right, _assert_fail_message(message, left, right, ">=", extra)
python
def assert_lt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand >= right_hand.""" assert left < right, _assert_fail_message(message, left, right, ">=", extra)
[ "def", "assert_lt", "(", "left", ",", "right", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "left", "<", "right", ",", "_assert_fail_message", "(", "message", ",", "left", ",", "right", ",", "\">=\"", ",", "extra", ")" ]
Raises an AssertionError if left_hand >= right_hand.
[ "Raises", "an", "AssertionError", "if", "left_hand", ">", "=", "right_hand", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L229-L231
quora/qcore
qcore/asserts.py
assert_le
def assert_le(left, right, message=None, extra=None): """Raises an AssertionError if left_hand > right_hand.""" assert left <= right, _assert_fail_message(message, left, right, ">", extra)
python
def assert_le(left, right, message=None, extra=None): """Raises an AssertionError if left_hand > right_hand.""" assert left <= right, _assert_fail_message(message, left, right, ">", extra)
[ "def", "assert_le", "(", "left", ",", "right", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "left", "<=", "right", ",", "_assert_fail_message", "(", "message", ",", "left", ",", "right", ",", "\">\"", ",", "extra", ")" ]
Raises an AssertionError if left_hand > right_hand.
[ "Raises", "an", "AssertionError", "if", "left_hand", ">", "right_hand", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L234-L236
quora/qcore
qcore/asserts.py
assert_in
def assert_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is not in seq.""" assert obj in seq, _assert_fail_message(message, obj, seq, "is not in", extra)
python
def assert_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is not in seq.""" assert obj in seq, _assert_fail_message(message, obj, seq, "is not in", extra)
[ "def", "assert_in", "(", "obj", ",", "seq", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "obj", "in", "seq", ",", "_assert_fail_message", "(", "message", ",", "obj", ",", "seq", ",", "\"is not in\"", ",", "extra", ")" ]
Raises an AssertionError if obj is not in seq.
[ "Raises", "an", "AssertionError", "if", "obj", "is", "not", "in", "seq", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L239-L241
quora/qcore
qcore/asserts.py
assert_not_in
def assert_not_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is in iter.""" # for very long strings, provide a truncated error if isinstance(seq, six.string_types) and obj in seq and len(seq) > 200: index = seq.find(obj) start_index = index - 50 if start_index > 0: truncated = "(truncated) ..." else: truncated = "" start_index = 0 end_index = index + len(obj) + 50 truncated += seq[start_index:end_index] if end_index < len(seq): truncated += "... (truncated)" assert False, _assert_fail_message(message, obj, truncated, "is in", extra) assert obj not in seq, _assert_fail_message(message, obj, seq, "is in", extra)
python
def assert_not_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is in iter.""" # for very long strings, provide a truncated error if isinstance(seq, six.string_types) and obj in seq and len(seq) > 200: index = seq.find(obj) start_index = index - 50 if start_index > 0: truncated = "(truncated) ..." else: truncated = "" start_index = 0 end_index = index + len(obj) + 50 truncated += seq[start_index:end_index] if end_index < len(seq): truncated += "... (truncated)" assert False, _assert_fail_message(message, obj, truncated, "is in", extra) assert obj not in seq, _assert_fail_message(message, obj, seq, "is in", extra)
[ "def", "assert_not_in", "(", "obj", ",", "seq", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "# for very long strings, provide a truncated error", "if", "isinstance", "(", "seq", ",", "six", ".", "string_types", ")", "and", "obj", "in", "seq", "and", "len", "(", "seq", ")", ">", "200", ":", "index", "=", "seq", ".", "find", "(", "obj", ")", "start_index", "=", "index", "-", "50", "if", "start_index", ">", "0", ":", "truncated", "=", "\"(truncated) ...\"", "else", ":", "truncated", "=", "\"\"", "start_index", "=", "0", "end_index", "=", "index", "+", "len", "(", "obj", ")", "+", "50", "truncated", "+=", "seq", "[", "start_index", ":", "end_index", "]", "if", "end_index", "<", "len", "(", "seq", ")", ":", "truncated", "+=", "\"... (truncated)\"", "assert", "False", ",", "_assert_fail_message", "(", "message", ",", "obj", ",", "truncated", ",", "\"is in\"", ",", "extra", ")", "assert", "obj", "not", "in", "seq", ",", "_assert_fail_message", "(", "message", ",", "obj", ",", "seq", ",", "\"is in\"", ",", "extra", ")" ]
Raises an AssertionError if obj is in iter.
[ "Raises", "an", "AssertionError", "if", "obj", "is", "in", "iter", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L244-L260
quora/qcore
qcore/asserts.py
assert_in_with_tolerance
def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): """Raises an AssertionError if obj is not in seq using assert_eq cmp.""" for i in seq: try: assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra) return except AssertionError: pass assert False, _assert_fail_message(message, obj, seq, "is not in", extra)
python
def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): """Raises an AssertionError if obj is not in seq using assert_eq cmp.""" for i in seq: try: assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra) return except AssertionError: pass assert False, _assert_fail_message(message, obj, seq, "is not in", extra)
[ "def", "assert_in_with_tolerance", "(", "obj", ",", "seq", ",", "tolerance", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "for", "i", "in", "seq", ":", "try", ":", "assert_eq", "(", "obj", ",", "i", ",", "tolerance", "=", "tolerance", ",", "message", "=", "message", ",", "extra", "=", "extra", ")", "return", "except", "AssertionError", ":", "pass", "assert", "False", ",", "_assert_fail_message", "(", "message", ",", "obj", ",", "seq", ",", "\"is not in\"", ",", "extra", ")" ]
Raises an AssertionError if obj is not in seq using assert_eq cmp.
[ "Raises", "an", "AssertionError", "if", "obj", "is", "not", "in", "seq", "using", "assert_eq", "cmp", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L263-L271
quora/qcore
qcore/asserts.py
assert_is_substring
def assert_is_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is not a substring of subject.""" assert ( (subject is not None) and (substring is not None) and (subject.find(substring) != -1) ), _assert_fail_message(message, substring, subject, "is not in", extra)
python
def assert_is_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is not a substring of subject.""" assert ( (subject is not None) and (substring is not None) and (subject.find(substring) != -1) ), _assert_fail_message(message, substring, subject, "is not in", extra)
[ "def", "assert_is_substring", "(", "substring", ",", "subject", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "(", "(", "subject", "is", "not", "None", ")", "and", "(", "substring", "is", "not", "None", ")", "and", "(", "subject", ".", "find", "(", "substring", ")", "!=", "-", "1", ")", ")", ",", "_assert_fail_message", "(", "message", ",", "substring", ",", "subject", ",", "\"is not in\"", ",", "extra", ")" ]
Raises an AssertionError if substring is not a substring of subject.
[ "Raises", "an", "AssertionError", "if", "substring", "is", "not", "a", "substring", "of", "subject", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L274-L280
quora/qcore
qcore/asserts.py
assert_is_not_substring
def assert_is_not_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is a substring of subject.""" assert ( (subject is not None) and (substring is not None) and (subject.find(substring) == -1) ), _assert_fail_message(message, substring, subject, "is in", extra)
python
def assert_is_not_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is a substring of subject.""" assert ( (subject is not None) and (substring is not None) and (subject.find(substring) == -1) ), _assert_fail_message(message, substring, subject, "is in", extra)
[ "def", "assert_is_not_substring", "(", "substring", ",", "subject", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "(", "(", "subject", "is", "not", "None", ")", "and", "(", "substring", "is", "not", "None", ")", "and", "(", "subject", ".", "find", "(", "substring", ")", "==", "-", "1", ")", ")", ",", "_assert_fail_message", "(", "message", ",", "substring", ",", "subject", ",", "\"is in\"", ",", "extra", ")" ]
Raises an AssertionError if substring is a substring of subject.
[ "Raises", "an", "AssertionError", "if", "substring", "is", "a", "substring", "of", "subject", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L283-L289
quora/qcore
qcore/asserts.py
assert_unordered_list_eq
def assert_unordered_list_eq(expected, actual, message=None): """Raises an AssertionError if the objects contained in expected are not equal to the objects contained in actual without regard to their order. This takes quadratic time in the umber of elements in actual; don't use it for very long lists. """ missing_in_actual = [] missing_in_expected = list(actual) for x in expected: try: missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x) if missing_in_actual or missing_in_expected: if not message: message = ( "%r not equal to %r; missing items: %r in expected, %r in actual." % (expected, actual, missing_in_expected, missing_in_actual) ) assert False, message
python
def assert_unordered_list_eq(expected, actual, message=None): """Raises an AssertionError if the objects contained in expected are not equal to the objects contained in actual without regard to their order. This takes quadratic time in the umber of elements in actual; don't use it for very long lists. """ missing_in_actual = [] missing_in_expected = list(actual) for x in expected: try: missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x) if missing_in_actual or missing_in_expected: if not message: message = ( "%r not equal to %r; missing items: %r in expected, %r in actual." % (expected, actual, missing_in_expected, missing_in_actual) ) assert False, message
[ "def", "assert_unordered_list_eq", "(", "expected", ",", "actual", ",", "message", "=", "None", ")", ":", "missing_in_actual", "=", "[", "]", "missing_in_expected", "=", "list", "(", "actual", ")", "for", "x", "in", "expected", ":", "try", ":", "missing_in_expected", ".", "remove", "(", "x", ")", "except", "ValueError", ":", "missing_in_actual", ".", "append", "(", "x", ")", "if", "missing_in_actual", "or", "missing_in_expected", ":", "if", "not", "message", ":", "message", "=", "(", "\"%r not equal to %r; missing items: %r in expected, %r in actual.\"", "%", "(", "expected", ",", "actual", ",", "missing_in_expected", ",", "missing_in_actual", ")", ")", "assert", "False", ",", "message" ]
Raises an AssertionError if the objects contained in expected are not equal to the objects contained in actual without regard to their order. This takes quadratic time in the umber of elements in actual; don't use it for very long lists.
[ "Raises", "an", "AssertionError", "if", "the", "objects", "contained", "in", "expected", "are", "not", "equal", "to", "the", "objects", "contained", "in", "actual", "without", "regard", "to", "their", "order", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L292-L314
opennode/waldur-core
waldur_core/logging/elasticsearch_client.py
_execute_if_not_empty
def _execute_if_not_empty(func): """ Execute function only if one of input parameters is not empty """ def wrapper(*args, **kwargs): if any(args[1:]) or any(kwargs.items()): return func(*args, **kwargs) return wrapper
python
def _execute_if_not_empty(func): """ Execute function only if one of input parameters is not empty """ def wrapper(*args, **kwargs): if any(args[1:]) or any(kwargs.items()): return func(*args, **kwargs) return wrapper
[ "def", "_execute_if_not_empty", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "any", "(", "args", "[", "1", ":", "]", ")", "or", "any", "(", "kwargs", ".", "items", "(", ")", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Execute function only if one of input parameters is not empty
[ "Execute", "function", "only", "if", "one", "of", "input", "parameters", "is", "not", "empty" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/elasticsearch_client.py#L89-L94
opennode/waldur-core
waldur_core/logging/elasticsearch_client.py
ElasticsearchClient.prepare_search_body
def prepare_search_body(self, should_terms=None, must_terms=None, must_not_terms=None, search_text='', start=None, end=None): """ Prepare body for elasticsearch query Search parameters ^^^^^^^^^^^^^^^^^ These parameters are dictionaries and have format: <term>: [<value 1>, <value 2> ...] should_terms: it resembles logical OR must_terms: it resembles logical AND must_not_terms: it resembles logical NOT search_text : string Text for FTS(full text search) start, end : datetime Filter for event creation time """ self.body = self.SearchBody() self.body.set_should_terms(should_terms) self.body.set_must_terms(must_terms) self.body.set_must_not_terms(must_not_terms) self.body.set_search_text(search_text) self.body.set_timestamp_filter(start, end) self.body.prepare()
python
def prepare_search_body(self, should_terms=None, must_terms=None, must_not_terms=None, search_text='', start=None, end=None): """ Prepare body for elasticsearch query Search parameters ^^^^^^^^^^^^^^^^^ These parameters are dictionaries and have format: <term>: [<value 1>, <value 2> ...] should_terms: it resembles logical OR must_terms: it resembles logical AND must_not_terms: it resembles logical NOT search_text : string Text for FTS(full text search) start, end : datetime Filter for event creation time """ self.body = self.SearchBody() self.body.set_should_terms(should_terms) self.body.set_must_terms(must_terms) self.body.set_must_not_terms(must_not_terms) self.body.set_search_text(search_text) self.body.set_timestamp_filter(start, end) self.body.prepare()
[ "def", "prepare_search_body", "(", "self", ",", "should_terms", "=", "None", ",", "must_terms", "=", "None", ",", "must_not_terms", "=", "None", ",", "search_text", "=", "''", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "self", ".", "body", "=", "self", ".", "SearchBody", "(", ")", "self", ".", "body", ".", "set_should_terms", "(", "should_terms", ")", "self", ".", "body", ".", "set_must_terms", "(", "must_terms", ")", "self", ".", "body", ".", "set_must_not_terms", "(", "must_not_terms", ")", "self", ".", "body", ".", "set_search_text", "(", "search_text", ")", "self", ".", "body", ".", "set_timestamp_filter", "(", "start", ",", "end", ")", "self", ".", "body", ".", "prepare", "(", ")" ]
Prepare body for elasticsearch query Search parameters ^^^^^^^^^^^^^^^^^ These parameters are dictionaries and have format: <term>: [<value 1>, <value 2> ...] should_terms: it resembles logical OR must_terms: it resembles logical AND must_not_terms: it resembles logical NOT search_text : string Text for FTS(full text search) start, end : datetime Filter for event creation time
[ "Prepare", "body", "for", "elasticsearch", "query" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/elasticsearch_client.py#L227-L249
opennode/waldur-core
waldur_core/core/executors.py
BaseExecutor.execute
def execute(cls, instance, async=True, countdown=2, is_heavy_task=False, **kwargs): """ Execute high level-operation """ cls.pre_apply(instance, async=async, **kwargs) result = cls.apply_signature(instance, async=async, countdown=countdown, is_heavy_task=is_heavy_task, **kwargs) cls.post_apply(instance, async=async, **kwargs) return result
python
def execute(cls, instance, async=True, countdown=2, is_heavy_task=False, **kwargs): """ Execute high level-operation """ cls.pre_apply(instance, async=async, **kwargs) result = cls.apply_signature(instance, async=async, countdown=countdown, is_heavy_task=is_heavy_task, **kwargs) cls.post_apply(instance, async=async, **kwargs) return result
[ "def", "execute", "(", "cls", ",", "instance", ",", "async", "=", "True", ",", "countdown", "=", "2", ",", "is_heavy_task", "=", "False", ",", "*", "*", "kwargs", ")", ":", "cls", ".", "pre_apply", "(", "instance", ",", "async", "=", "async", ",", "*", "*", "kwargs", ")", "result", "=", "cls", ".", "apply_signature", "(", "instance", ",", "async", "=", "async", ",", "countdown", "=", "countdown", ",", "is_heavy_task", "=", "is_heavy_task", ",", "*", "*", "kwargs", ")", "cls", ".", "post_apply", "(", "instance", ",", "async", "=", "async", ",", "*", "*", "kwargs", ")", "return", "result" ]
Execute high level-operation
[ "Execute", "high", "level", "-", "operation" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/executors.py#L40-L46
opennode/waldur-core
waldur_core/core/executors.py
BaseExecutor.apply_signature
def apply_signature(cls, instance, async=True, countdown=None, is_heavy_task=False, **kwargs): """ Serialize input data and apply signature """ serialized_instance = utils.serialize_instance(instance) signature = cls.get_task_signature(instance, serialized_instance, **kwargs) link = cls.get_success_signature(instance, serialized_instance, **kwargs) link_error = cls.get_failure_signature(instance, serialized_instance, **kwargs) if async: return signature.apply_async(link=link, link_error=link_error, countdown=countdown, queue=is_heavy_task and 'heavy' or None) else: result = signature.apply() callback = link if not result.failed() else link_error if callback is not None: cls._apply_callback(callback, result) return result.get()
python
def apply_signature(cls, instance, async=True, countdown=None, is_heavy_task=False, **kwargs): """ Serialize input data and apply signature """ serialized_instance = utils.serialize_instance(instance) signature = cls.get_task_signature(instance, serialized_instance, **kwargs) link = cls.get_success_signature(instance, serialized_instance, **kwargs) link_error = cls.get_failure_signature(instance, serialized_instance, **kwargs) if async: return signature.apply_async(link=link, link_error=link_error, countdown=countdown, queue=is_heavy_task and 'heavy' or None) else: result = signature.apply() callback = link if not result.failed() else link_error if callback is not None: cls._apply_callback(callback, result) return result.get()
[ "def", "apply_signature", "(", "cls", ",", "instance", ",", "async", "=", "True", ",", "countdown", "=", "None", ",", "is_heavy_task", "=", "False", ",", "*", "*", "kwargs", ")", ":", "serialized_instance", "=", "utils", ".", "serialize_instance", "(", "instance", ")", "signature", "=", "cls", ".", "get_task_signature", "(", "instance", ",", "serialized_instance", ",", "*", "*", "kwargs", ")", "link", "=", "cls", ".", "get_success_signature", "(", "instance", ",", "serialized_instance", ",", "*", "*", "kwargs", ")", "link_error", "=", "cls", ".", "get_failure_signature", "(", "instance", ",", "serialized_instance", ",", "*", "*", "kwargs", ")", "if", "async", ":", "return", "signature", ".", "apply_async", "(", "link", "=", "link", ",", "link_error", "=", "link_error", ",", "countdown", "=", "countdown", ",", "queue", "=", "is_heavy_task", "and", "'heavy'", "or", "None", ")", "else", ":", "result", "=", "signature", ".", "apply", "(", ")", "callback", "=", "link", "if", "not", "result", ".", "failed", "(", ")", "else", "link_error", "if", "callback", "is", "not", "None", ":", "cls", ".", "_apply_callback", "(", "callback", ",", "result", ")", "return", "result", ".", "get", "(", ")" ]
Serialize input data and apply signature
[ "Serialize", "input", "data", "and", "apply", "signature" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/executors.py#L59-L76
opennode/waldur-core
waldur_core/core/executors.py
BaseExecutor._apply_callback
def _apply_callback(cls, callback, result): """ Synchronously execute callback """ if not callback.immutable: callback.args = (result.id, ) + callback.args callback.apply()
python
def _apply_callback(cls, callback, result): """ Synchronously execute callback """ if not callback.immutable: callback.args = (result.id, ) + callback.args callback.apply()
[ "def", "_apply_callback", "(", "cls", ",", "callback", ",", "result", ")", ":", "if", "not", "callback", ".", "immutable", ":", "callback", ".", "args", "=", "(", "result", ".", "id", ",", ")", "+", "callback", ".", "args", "callback", ".", "apply", "(", ")" ]
Synchronously execute callback
[ "Synchronously", "execute", "callback" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/executors.py#L79-L83
opennode/waldur-core
waldur_core/core/schemas.py
get_entity_description
def get_entity_description(entity): """ Returns description in format: * entity human readable name * docstring """ try: entity_name = entity.__name__.strip('_') except AttributeError: # entity is a class instance entity_name = entity.__class__.__name__ label = '* %s' % formatting.camelcase_to_spaces(entity_name) if entity.__doc__ is not None: entity_docstring = formatting.dedent(smart_text(entity.__doc__)).replace('\n', '\n\t') return '%s\n * %s' % (label, entity_docstring) return label
python
def get_entity_description(entity): """ Returns description in format: * entity human readable name * docstring """ try: entity_name = entity.__name__.strip('_') except AttributeError: # entity is a class instance entity_name = entity.__class__.__name__ label = '* %s' % formatting.camelcase_to_spaces(entity_name) if entity.__doc__ is not None: entity_docstring = formatting.dedent(smart_text(entity.__doc__)).replace('\n', '\n\t') return '%s\n * %s' % (label, entity_docstring) return label
[ "def", "get_entity_description", "(", "entity", ")", ":", "try", ":", "entity_name", "=", "entity", ".", "__name__", ".", "strip", "(", "'_'", ")", "except", "AttributeError", ":", "# entity is a class instance", "entity_name", "=", "entity", ".", "__class__", ".", "__name__", "label", "=", "'* %s'", "%", "formatting", ".", "camelcase_to_spaces", "(", "entity_name", ")", "if", "entity", ".", "__doc__", "is", "not", "None", ":", "entity_docstring", "=", "formatting", ".", "dedent", "(", "smart_text", "(", "entity", ".", "__doc__", ")", ")", ".", "replace", "(", "'\\n'", ",", "'\\n\\t'", ")", "return", "'%s\\n * %s'", "%", "(", "label", ",", "entity_docstring", ")", "return", "label" ]
Returns description in format: * entity human readable name * docstring
[ "Returns", "description", "in", "format", ":", "*", "entity", "human", "readable", "name", "*", "docstring" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L37-L55
opennode/waldur-core
waldur_core/core/schemas.py
get_validators_description
def get_validators_description(view): """ Returns validators description in format: ### Validators: * validator1 name * validator1 docstring * validator2 name * validator2 docstring """ action = getattr(view, 'action', None) if action is None: return '' description = '' validators = getattr(view, action + '_validators', []) for validator in validators: validator_description = get_entity_description(validator) description += '\n' + validator_description if description else validator_description return '### Validators:\n' + description if description else ''
python
def get_validators_description(view): """ Returns validators description in format: ### Validators: * validator1 name * validator1 docstring * validator2 name * validator2 docstring """ action = getattr(view, 'action', None) if action is None: return '' description = '' validators = getattr(view, action + '_validators', []) for validator in validators: validator_description = get_entity_description(validator) description += '\n' + validator_description if description else validator_description return '### Validators:\n' + description if description else ''
[ "def", "get_validators_description", "(", "view", ")", ":", "action", "=", "getattr", "(", "view", ",", "'action'", ",", "None", ")", "if", "action", "is", "None", ":", "return", "''", "description", "=", "''", "validators", "=", "getattr", "(", "view", ",", "action", "+", "'_validators'", ",", "[", "]", ")", "for", "validator", "in", "validators", ":", "validator_description", "=", "get_entity_description", "(", "validator", ")", "description", "+=", "'\\n'", "+", "validator_description", "if", "description", "else", "validator_description", "return", "'### Validators:\\n'", "+", "description", "if", "description", "else", "''" ]
Returns validators description in format: ### Validators: * validator1 name * validator1 docstring * validator2 name * validator2 docstring
[ "Returns", "validators", "description", "in", "format", ":", "###", "Validators", ":", "*", "validator1", "name", "*", "validator1", "docstring", "*", "validator2", "name", "*", "validator2", "docstring" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L58-L77
opennode/waldur-core
waldur_core/core/schemas.py
get_actions_permission_description
def get_actions_permission_description(view, method): """ Returns actions permissions description in format: * permission1 name * permission1 docstring * permission2 name * permission2 docstring """ action = getattr(view, 'action', None) if action is None: return '' if hasattr(view, action + '_permissions'): permission_types = (action,) elif method in SAFE_METHODS: permission_types = ('safe_methods', '%s_extra' % action) else: permission_types = ('unsafe_methods', '%s_extra' % action) description = '' for permission_type in permission_types: action_perms = getattr(view, permission_type + '_permissions', []) for permission in action_perms: action_perm_description = get_entity_description(permission) description += '\n' + action_perm_description if description else action_perm_description return description
python
def get_actions_permission_description(view, method): """ Returns actions permissions description in format: * permission1 name * permission1 docstring * permission2 name * permission2 docstring """ action = getattr(view, 'action', None) if action is None: return '' if hasattr(view, action + '_permissions'): permission_types = (action,) elif method in SAFE_METHODS: permission_types = ('safe_methods', '%s_extra' % action) else: permission_types = ('unsafe_methods', '%s_extra' % action) description = '' for permission_type in permission_types: action_perms = getattr(view, permission_type + '_permissions', []) for permission in action_perms: action_perm_description = get_entity_description(permission) description += '\n' + action_perm_description if description else action_perm_description return description
[ "def", "get_actions_permission_description", "(", "view", ",", "method", ")", ":", "action", "=", "getattr", "(", "view", ",", "'action'", ",", "None", ")", "if", "action", "is", "None", ":", "return", "''", "if", "hasattr", "(", "view", ",", "action", "+", "'_permissions'", ")", ":", "permission_types", "=", "(", "action", ",", ")", "elif", "method", "in", "SAFE_METHODS", ":", "permission_types", "=", "(", "'safe_methods'", ",", "'%s_extra'", "%", "action", ")", "else", ":", "permission_types", "=", "(", "'unsafe_methods'", ",", "'%s_extra'", "%", "action", ")", "description", "=", "''", "for", "permission_type", "in", "permission_types", ":", "action_perms", "=", "getattr", "(", "view", ",", "permission_type", "+", "'_permissions'", ",", "[", "]", ")", "for", "permission", "in", "action_perms", ":", "action_perm_description", "=", "get_entity_description", "(", "permission", ")", "description", "+=", "'\\n'", "+", "action_perm_description", "if", "description", "else", "action_perm_description", "return", "description" ]
Returns actions permissions description in format: * permission1 name * permission1 docstring * permission2 name * permission2 docstring
[ "Returns", "actions", "permissions", "description", "in", "format", ":", "*", "permission1", "name", "*", "permission1", "docstring", "*", "permission2", "name", "*", "permission2", "docstring" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L80-L106
opennode/waldur-core
waldur_core/core/schemas.py
get_permissions_description
def get_permissions_description(view, method): """ Returns permissions description in format: ### Permissions: * permission1 name * permission1 docstring * permission2 name * permission2 docstring """ if not hasattr(view, 'permission_classes'): return '' description = '' for permission_class in view.permission_classes: if permission_class == core_permissions.ActionsPermission: actions_perm_description = get_actions_permission_description(view, method) if actions_perm_description: description += '\n' + actions_perm_description if description else actions_perm_description continue perm_description = get_entity_description(permission_class) description += '\n' + perm_description if description else perm_description return '### Permissions:\n' + description if description else ''
python
def get_permissions_description(view, method): """ Returns permissions description in format: ### Permissions: * permission1 name * permission1 docstring * permission2 name * permission2 docstring """ if not hasattr(view, 'permission_classes'): return '' description = '' for permission_class in view.permission_classes: if permission_class == core_permissions.ActionsPermission: actions_perm_description = get_actions_permission_description(view, method) if actions_perm_description: description += '\n' + actions_perm_description if description else actions_perm_description continue perm_description = get_entity_description(permission_class) description += '\n' + perm_description if description else perm_description return '### Permissions:\n' + description if description else ''
[ "def", "get_permissions_description", "(", "view", ",", "method", ")", ":", "if", "not", "hasattr", "(", "view", ",", "'permission_classes'", ")", ":", "return", "''", "description", "=", "''", "for", "permission_class", "in", "view", ".", "permission_classes", ":", "if", "permission_class", "==", "core_permissions", ".", "ActionsPermission", ":", "actions_perm_description", "=", "get_actions_permission_description", "(", "view", ",", "method", ")", "if", "actions_perm_description", ":", "description", "+=", "'\\n'", "+", "actions_perm_description", "if", "description", "else", "actions_perm_description", "continue", "perm_description", "=", "get_entity_description", "(", "permission_class", ")", "description", "+=", "'\\n'", "+", "perm_description", "if", "description", "else", "perm_description", "return", "'### Permissions:\\n'", "+", "description", "if", "description", "else", "''" ]
Returns permissions description in format: ### Permissions: * permission1 name * permission1 docstring * permission2 name * permission2 docstring
[ "Returns", "permissions", "description", "in", "format", ":", "###", "Permissions", ":", "*", "permission1", "name", "*", "permission1", "docstring", "*", "permission2", "name", "*", "permission2", "docstring" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L109-L131
opennode/waldur-core
waldur_core/core/schemas.py
get_validation_description
def get_validation_description(view, method): """ Returns validation description in format: ### Validation: validate method docstring * field1 name * field1 validation docstring * field2 name * field2 validation docstring """ if method not in ('PUT', 'PATCH', 'POST') or not hasattr(view, 'get_serializer'): return '' serializer = view.get_serializer() description = '' if hasattr(serializer, 'validate') and serializer.validate.__doc__ is not None: description += formatting.dedent(smart_text(serializer.validate.__doc__)) for field in serializer.fields.values(): if not hasattr(serializer, 'validate_' + field.field_name): continue field_validation = getattr(serializer, 'validate_' + field.field_name) if field_validation.__doc__ is not None: docstring = formatting.dedent(smart_text(field_validation.__doc__)).replace('\n', '\n\t') field_description = '* %s\n * %s' % (field.field_name, docstring) description += '\n' + field_description if description else field_description return '### Validation:\n' + description if description else ''
python
def get_validation_description(view, method): """ Returns validation description in format: ### Validation: validate method docstring * field1 name * field1 validation docstring * field2 name * field2 validation docstring """ if method not in ('PUT', 'PATCH', 'POST') or not hasattr(view, 'get_serializer'): return '' serializer = view.get_serializer() description = '' if hasattr(serializer, 'validate') and serializer.validate.__doc__ is not None: description += formatting.dedent(smart_text(serializer.validate.__doc__)) for field in serializer.fields.values(): if not hasattr(serializer, 'validate_' + field.field_name): continue field_validation = getattr(serializer, 'validate_' + field.field_name) if field_validation.__doc__ is not None: docstring = formatting.dedent(smart_text(field_validation.__doc__)).replace('\n', '\n\t') field_description = '* %s\n * %s' % (field.field_name, docstring) description += '\n' + field_description if description else field_description return '### Validation:\n' + description if description else ''
[ "def", "get_validation_description", "(", "view", ",", "method", ")", ":", "if", "method", "not", "in", "(", "'PUT'", ",", "'PATCH'", ",", "'POST'", ")", "or", "not", "hasattr", "(", "view", ",", "'get_serializer'", ")", ":", "return", "''", "serializer", "=", "view", ".", "get_serializer", "(", ")", "description", "=", "''", "if", "hasattr", "(", "serializer", ",", "'validate'", ")", "and", "serializer", ".", "validate", ".", "__doc__", "is", "not", "None", ":", "description", "+=", "formatting", ".", "dedent", "(", "smart_text", "(", "serializer", ".", "validate", ".", "__doc__", ")", ")", "for", "field", "in", "serializer", ".", "fields", ".", "values", "(", ")", ":", "if", "not", "hasattr", "(", "serializer", ",", "'validate_'", "+", "field", ".", "field_name", ")", ":", "continue", "field_validation", "=", "getattr", "(", "serializer", ",", "'validate_'", "+", "field", ".", "field_name", ")", "if", "field_validation", ".", "__doc__", "is", "not", "None", ":", "docstring", "=", "formatting", ".", "dedent", "(", "smart_text", "(", "field_validation", ".", "__doc__", ")", ")", ".", "replace", "(", "'\\n'", ",", "'\\n\\t'", ")", "field_description", "=", "'* %s\\n * %s'", "%", "(", "field", ".", "field_name", ",", "docstring", ")", "description", "+=", "'\\n'", "+", "field_description", "if", "description", "else", "field_description", "return", "'### Validation:\\n'", "+", "description", "if", "description", "else", "''" ]
Returns validation description in format: ### Validation: validate method docstring * field1 name * field1 validation docstring * field2 name * field2 validation docstring
[ "Returns", "validation", "description", "in", "format", ":", "###", "Validation", ":", "validate", "method", "docstring", "*", "field1", "name", "*", "field1", "validation", "docstring", "*", "field2", "name", "*", "field2", "validation", "docstring" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L134-L163
opennode/waldur-core
waldur_core/core/schemas.py
get_field_type
def get_field_type(field): """ Returns field type/possible values. """ if isinstance(field, core_filters.MappedMultipleChoiceFilter): return ' | '.join(['"%s"' % f for f in sorted(field.mapped_to_model)]) if isinstance(field, OrderingFilter) or isinstance(field, ChoiceFilter): return ' | '.join(['"%s"' % f[0] for f in field.extra['choices']]) if isinstance(field, ChoiceField): return ' | '.join(['"%s"' % f for f in sorted(field.choices)]) if isinstance(field, HyperlinkedRelatedField): if field.view_name.endswith('detail'): return 'link to %s' % reverse(field.view_name, kwargs={'%s' % field.lookup_field: "'%s'" % field.lookup_field}) return reverse(field.view_name) if isinstance(field, structure_filters.ServiceTypeFilter): return ' | '.join(['"%s"' % f for f in SupportedServices.get_filter_mapping().keys()]) if isinstance(field, ResourceTypeFilter): return ' | '.join(['"%s"' % f for f in SupportedServices.get_resource_models().keys()]) if isinstance(field, core_serializers.GenericRelatedField): links = [] for model in field.related_models: detail_view_name = core_utils.get_detail_view_name(model) for f in field.lookup_fields: try: link = reverse(detail_view_name, kwargs={'%s' % f: "'%s'" % f}) except NoReverseMatch: pass else: links.append(link) break path = ', '.join(links) if path: return 'link to any: %s' % path if isinstance(field, core_filters.ContentTypeFilter): return "string in form 'app_label'.'model_name'" if isinstance(field, ModelMultipleChoiceFilter): return get_field_type(field.field) if isinstance(field, ListSerializer): return 'list of [%s]' % get_field_type(field.child) if isinstance(field, ManyRelatedField): return 'list of [%s]' % get_field_type(field.child_relation) if isinstance(field, ModelField): return get_field_type(field.model_field) name = field.__class__.__name__ for w in ('Filter', 'Field', 'Serializer'): name = name.replace(w, '') return FIELDS.get(name, name)
python
def get_field_type(field): """ Returns field type/possible values. """ if isinstance(field, core_filters.MappedMultipleChoiceFilter): return ' | '.join(['"%s"' % f for f in sorted(field.mapped_to_model)]) if isinstance(field, OrderingFilter) or isinstance(field, ChoiceFilter): return ' | '.join(['"%s"' % f[0] for f in field.extra['choices']]) if isinstance(field, ChoiceField): return ' | '.join(['"%s"' % f for f in sorted(field.choices)]) if isinstance(field, HyperlinkedRelatedField): if field.view_name.endswith('detail'): return 'link to %s' % reverse(field.view_name, kwargs={'%s' % field.lookup_field: "'%s'" % field.lookup_field}) return reverse(field.view_name) if isinstance(field, structure_filters.ServiceTypeFilter): return ' | '.join(['"%s"' % f for f in SupportedServices.get_filter_mapping().keys()]) if isinstance(field, ResourceTypeFilter): return ' | '.join(['"%s"' % f for f in SupportedServices.get_resource_models().keys()]) if isinstance(field, core_serializers.GenericRelatedField): links = [] for model in field.related_models: detail_view_name = core_utils.get_detail_view_name(model) for f in field.lookup_fields: try: link = reverse(detail_view_name, kwargs={'%s' % f: "'%s'" % f}) except NoReverseMatch: pass else: links.append(link) break path = ', '.join(links) if path: return 'link to any: %s' % path if isinstance(field, core_filters.ContentTypeFilter): return "string in form 'app_label'.'model_name'" if isinstance(field, ModelMultipleChoiceFilter): return get_field_type(field.field) if isinstance(field, ListSerializer): return 'list of [%s]' % get_field_type(field.child) if isinstance(field, ManyRelatedField): return 'list of [%s]' % get_field_type(field.child_relation) if isinstance(field, ModelField): return get_field_type(field.model_field) name = field.__class__.__name__ for w in ('Filter', 'Field', 'Serializer'): name = name.replace(w, '') return FIELDS.get(name, name)
[ "def", "get_field_type", "(", "field", ")", ":", "if", "isinstance", "(", "field", ",", "core_filters", ".", "MappedMultipleChoiceFilter", ")", ":", "return", "' | '", ".", "join", "(", "[", "'\"%s\"'", "%", "f", "for", "f", "in", "sorted", "(", "field", ".", "mapped_to_model", ")", "]", ")", "if", "isinstance", "(", "field", ",", "OrderingFilter", ")", "or", "isinstance", "(", "field", ",", "ChoiceFilter", ")", ":", "return", "' | '", ".", "join", "(", "[", "'\"%s\"'", "%", "f", "[", "0", "]", "for", "f", "in", "field", ".", "extra", "[", "'choices'", "]", "]", ")", "if", "isinstance", "(", "field", ",", "ChoiceField", ")", ":", "return", "' | '", ".", "join", "(", "[", "'\"%s\"'", "%", "f", "for", "f", "in", "sorted", "(", "field", ".", "choices", ")", "]", ")", "if", "isinstance", "(", "field", ",", "HyperlinkedRelatedField", ")", ":", "if", "field", ".", "view_name", ".", "endswith", "(", "'detail'", ")", ":", "return", "'link to %s'", "%", "reverse", "(", "field", ".", "view_name", ",", "kwargs", "=", "{", "'%s'", "%", "field", ".", "lookup_field", ":", "\"'%s'\"", "%", "field", ".", "lookup_field", "}", ")", "return", "reverse", "(", "field", ".", "view_name", ")", "if", "isinstance", "(", "field", ",", "structure_filters", ".", "ServiceTypeFilter", ")", ":", "return", "' | '", ".", "join", "(", "[", "'\"%s\"'", "%", "f", "for", "f", "in", "SupportedServices", ".", "get_filter_mapping", "(", ")", ".", "keys", "(", ")", "]", ")", "if", "isinstance", "(", "field", ",", "ResourceTypeFilter", ")", ":", "return", "' | '", ".", "join", "(", "[", "'\"%s\"'", "%", "f", "for", "f", "in", "SupportedServices", ".", "get_resource_models", "(", ")", ".", "keys", "(", ")", "]", ")", "if", "isinstance", "(", "field", ",", "core_serializers", ".", "GenericRelatedField", ")", ":", "links", "=", "[", "]", "for", "model", "in", "field", ".", "related_models", ":", "detail_view_name", "=", "core_utils", ".", "get_detail_view_name", "(", "model", ")", "for", "f", "in", "field", ".", "lookup_fields", ":", "try", ":", "link", "=", "reverse", "(", "detail_view_name", ",", "kwargs", "=", "{", "'%s'", "%", "f", ":", "\"'%s'\"", "%", "f", "}", ")", "except", "NoReverseMatch", ":", "pass", "else", ":", "links", ".", "append", "(", "link", ")", "break", "path", "=", "', '", ".", "join", "(", "links", ")", "if", "path", ":", "return", "'link to any: %s'", "%", "path", "if", "isinstance", "(", "field", ",", "core_filters", ".", "ContentTypeFilter", ")", ":", "return", "\"string in form 'app_label'.'model_name'\"", "if", "isinstance", "(", "field", ",", "ModelMultipleChoiceFilter", ")", ":", "return", "get_field_type", "(", "field", ".", "field", ")", "if", "isinstance", "(", "field", ",", "ListSerializer", ")", ":", "return", "'list of [%s]'", "%", "get_field_type", "(", "field", ".", "child", ")", "if", "isinstance", "(", "field", ",", "ManyRelatedField", ")", ":", "return", "'list of [%s]'", "%", "get_field_type", "(", "field", ".", "child_relation", ")", "if", "isinstance", "(", "field", ",", "ModelField", ")", ":", "return", "get_field_type", "(", "field", ".", "model_field", ")", "name", "=", "field", ".", "__class__", ".", "__name__", "for", "w", "in", "(", "'Filter'", ",", "'Field'", ",", "'Serializer'", ")", ":", "name", "=", "name", ".", "replace", "(", "w", ",", "''", ")", "return", "FIELDS", ".", "get", "(", "name", ",", "name", ")" ]
Returns field type/possible values.
[ "Returns", "field", "type", "/", "possible", "values", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L185-L233
opennode/waldur-core
waldur_core/core/schemas.py
is_disabled_action
def is_disabled_action(view): """ Checks whether Link action is disabled. """ if not isinstance(view, core_views.ActionsViewSet): return False action = getattr(view, 'action', None) return action in view.disabled_actions if action is not None else False
python
def is_disabled_action(view): """ Checks whether Link action is disabled. """ if not isinstance(view, core_views.ActionsViewSet): return False action = getattr(view, 'action', None) return action in view.disabled_actions if action is not None else False
[ "def", "is_disabled_action", "(", "view", ")", ":", "if", "not", "isinstance", "(", "view", ",", "core_views", ".", "ActionsViewSet", ")", ":", "return", "False", "action", "=", "getattr", "(", "view", ",", "'action'", ",", "None", ")", "return", "action", "in", "view", ".", "disabled_actions", "if", "action", "is", "not", "None", "else", "False" ]
Checks whether Link action is disabled.
[ "Checks", "whether", "Link", "action", "is", "disabled", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L236-L244
opennode/waldur-core
waldur_core/core/schemas.py
WaldurEndpointInspector.get_allowed_methods
def get_allowed_methods(self, callback): """ Return a list of the valid HTTP methods for this endpoint. """ if hasattr(callback, 'actions'): return [method.upper() for method in callback.actions.keys() if method != 'head'] return [ method for method in callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD') ]
python
def get_allowed_methods(self, callback): """ Return a list of the valid HTTP methods for this endpoint. """ if hasattr(callback, 'actions'): return [method.upper() for method in callback.actions.keys() if method != 'head'] return [ method for method in callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD') ]
[ "def", "get_allowed_methods", "(", "self", ",", "callback", ")", ":", "if", "hasattr", "(", "callback", ",", "'actions'", ")", ":", "return", "[", "method", ".", "upper", "(", ")", "for", "method", "in", "callback", ".", "actions", ".", "keys", "(", ")", "if", "method", "!=", "'head'", "]", "return", "[", "method", "for", "method", "in", "callback", ".", "cls", "(", ")", ".", "allowed_methods", "if", "method", "not", "in", "(", "'OPTIONS'", ",", "'HEAD'", ")", "]" ]
Return a list of the valid HTTP methods for this endpoint.
[ "Return", "a", "list", "of", "the", "valid", "HTTP", "methods", "for", "this", "endpoint", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L24-L34
opennode/waldur-core
waldur_core/core/schemas.py
WaldurSchemaGenerator.create_view
def create_view(self, callback, method, request=None): """ Given a callback, return an actual view instance. """ view = super(WaldurSchemaGenerator, self).create_view(callback, method, request) if is_disabled_action(view): view.exclude_from_schema = True return view
python
def create_view(self, callback, method, request=None): """ Given a callback, return an actual view instance. """ view = super(WaldurSchemaGenerator, self).create_view(callback, method, request) if is_disabled_action(view): view.exclude_from_schema = True return view
[ "def", "create_view", "(", "self", ",", "callback", ",", "method", ",", "request", "=", "None", ")", ":", "view", "=", "super", "(", "WaldurSchemaGenerator", ",", "self", ")", ".", "create_view", "(", "callback", ",", "method", ",", "request", ")", "if", "is_disabled_action", "(", "view", ")", ":", "view", ".", "exclude_from_schema", "=", "True", "return", "view" ]
Given a callback, return an actual view instance.
[ "Given", "a", "callback", "return", "an", "actual", "view", "instance", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L250-L258
opennode/waldur-core
waldur_core/core/schemas.py
WaldurSchemaGenerator.get_description
def get_description(self, path, method, view): """ Determine a link description. This will be based on the method docstring if one exists, or else the class docstring. """ description = super(WaldurSchemaGenerator, self).get_description(path, method, view) permissions_description = get_permissions_description(view, method) if permissions_description: description += '\n\n' + permissions_description if description else permissions_description if isinstance(view, core_views.ActionsViewSet): validators_description = get_validators_description(view) if validators_description: description += '\n\n' + validators_description if description else validators_description validation_description = get_validation_description(view, method) if validation_description: description += '\n\n' + validation_description if description else validation_description return description
python
def get_description(self, path, method, view): """ Determine a link description. This will be based on the method docstring if one exists, or else the class docstring. """ description = super(WaldurSchemaGenerator, self).get_description(path, method, view) permissions_description = get_permissions_description(view, method) if permissions_description: description += '\n\n' + permissions_description if description else permissions_description if isinstance(view, core_views.ActionsViewSet): validators_description = get_validators_description(view) if validators_description: description += '\n\n' + validators_description if description else validators_description validation_description = get_validation_description(view, method) if validation_description: description += '\n\n' + validation_description if description else validation_description return description
[ "def", "get_description", "(", "self", ",", "path", ",", "method", ",", "view", ")", ":", "description", "=", "super", "(", "WaldurSchemaGenerator", ",", "self", ")", ".", "get_description", "(", "path", ",", "method", ",", "view", ")", "permissions_description", "=", "get_permissions_description", "(", "view", ",", "method", ")", "if", "permissions_description", ":", "description", "+=", "'\\n\\n'", "+", "permissions_description", "if", "description", "else", "permissions_description", "if", "isinstance", "(", "view", ",", "core_views", ".", "ActionsViewSet", ")", ":", "validators_description", "=", "get_validators_description", "(", "view", ")", "if", "validators_description", ":", "description", "+=", "'\\n\\n'", "+", "validators_description", "if", "description", "else", "validators_description", "validation_description", "=", "get_validation_description", "(", "view", ",", "method", ")", "if", "validation_description", ":", "description", "+=", "'\\n\\n'", "+", "validation_description", "if", "description", "else", "validation_description", "return", "description" ]
Determine a link description. This will be based on the method docstring if one exists, or else the class docstring.
[ "Determine", "a", "link", "description", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L260-L282
opennode/waldur-core
waldur_core/core/schemas.py
WaldurSchemaGenerator.get_serializer_fields
def get_serializer_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. """ if method not in ('PUT', 'PATCH', 'POST'): return [] if not hasattr(view, 'get_serializer'): return [] serializer = view.get_serializer() if not isinstance(serializer, Serializer): return [] fields = [] for field in serializer.fields.values(): if field.read_only or isinstance(field, HiddenField): continue required = field.required and method != 'PATCH' description = force_text(field.help_text) if field.help_text else '' field_type = get_field_type(field) description += '; ' + field_type if description else field_type field = coreapi.Field( name=field.field_name, location='form', required=required, description=description, schema=schemas.field_to_schema(field), ) fields.append(field) return fields
python
def get_serializer_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. """ if method not in ('PUT', 'PATCH', 'POST'): return [] if not hasattr(view, 'get_serializer'): return [] serializer = view.get_serializer() if not isinstance(serializer, Serializer): return [] fields = [] for field in serializer.fields.values(): if field.read_only or isinstance(field, HiddenField): continue required = field.required and method != 'PATCH' description = force_text(field.help_text) if field.help_text else '' field_type = get_field_type(field) description += '; ' + field_type if description else field_type field = coreapi.Field( name=field.field_name, location='form', required=required, description=description, schema=schemas.field_to_schema(field), ) fields.append(field) return fields
[ "def", "get_serializer_fields", "(", "self", ",", "path", ",", "method", ",", "view", ")", ":", "if", "method", "not", "in", "(", "'PUT'", ",", "'PATCH'", ",", "'POST'", ")", ":", "return", "[", "]", "if", "not", "hasattr", "(", "view", ",", "'get_serializer'", ")", ":", "return", "[", "]", "serializer", "=", "view", ".", "get_serializer", "(", ")", "if", "not", "isinstance", "(", "serializer", ",", "Serializer", ")", ":", "return", "[", "]", "fields", "=", "[", "]", "for", "field", "in", "serializer", ".", "fields", ".", "values", "(", ")", ":", "if", "field", ".", "read_only", "or", "isinstance", "(", "field", ",", "HiddenField", ")", ":", "continue", "required", "=", "field", ".", "required", "and", "method", "!=", "'PATCH'", "description", "=", "force_text", "(", "field", ".", "help_text", ")", "if", "field", ".", "help_text", "else", "''", "field_type", "=", "get_field_type", "(", "field", ")", "description", "+=", "'; '", "+", "field_type", "if", "description", "else", "field_type", "field", "=", "coreapi", ".", "Field", "(", "name", "=", "field", ".", "field_name", ",", "location", "=", "'form'", ",", "required", "=", "required", ",", "description", "=", "description", ",", "schema", "=", "schemas", ".", "field_to_schema", "(", "field", ")", ",", ")", "fields", ".", "append", "(", "field", ")", "return", "fields" ]
Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class.
[ "Return", "a", "list", "of", "coreapi", ".", "Field", "instances", "corresponding", "to", "any", "request", "body", "input", "as", "determined", "by", "the", "serializer", "class", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/schemas.py#L315-L348
opennode/waldur-core
waldur_core/core/handlers.py
delete_error_message
def delete_error_message(sender, instance, name, source, target, **kwargs): """ Delete error message if instance state changed from erred """ if source != StateMixin.States.ERRED: return instance.error_message = '' instance.save(update_fields=['error_message'])
python
def delete_error_message(sender, instance, name, source, target, **kwargs): """ Delete error message if instance state changed from erred """ if source != StateMixin.States.ERRED: return instance.error_message = '' instance.save(update_fields=['error_message'])
[ "def", "delete_error_message", "(", "sender", ",", "instance", ",", "name", ",", "source", ",", "target", ",", "*", "*", "kwargs", ")", ":", "if", "source", "!=", "StateMixin", ".", "States", ".", "ERRED", ":", "return", "instance", ".", "error_message", "=", "''", "instance", ".", "save", "(", "update_fields", "=", "[", "'error_message'", "]", ")" ]
Delete error message if instance state changed from erred
[ "Delete", "error", "message", "if", "instance", "state", "changed", "from", "erred" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/handlers.py#L31-L36
zeromake/aiosqlite3
setup.py
find_version
def find_version(*file_paths): """ read __init__.py """ file_path = os.path.join(*file_paths) with open(file_path, 'r') as version_file: line = version_file.readline() while line: if line.startswith('__version__'): version_match = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]", line, re.M ) if version_match: return version_match.group(1) line = version_file.readline() raise RuntimeError('Unable to find version string.')
python
def find_version(*file_paths): """ read __init__.py """ file_path = os.path.join(*file_paths) with open(file_path, 'r') as version_file: line = version_file.readline() while line: if line.startswith('__version__'): version_match = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]", line, re.M ) if version_match: return version_match.group(1) line = version_file.readline() raise RuntimeError('Unable to find version string.')
[ "def", "find_version", "(", "*", "file_paths", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "*", "file_paths", ")", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "version_file", ":", "line", "=", "version_file", ".", "readline", "(", ")", "while", "line", ":", "if", "line", ".", "startswith", "(", "'__version__'", ")", ":", "version_match", "=", "re", ".", "search", "(", "r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"", ",", "line", ",", "re", ".", "M", ")", "if", "version_match", ":", "return", "version_match", ".", "group", "(", "1", ")", "line", "=", "version_file", ".", "readline", "(", ")", "raise", "RuntimeError", "(", "'Unable to find version string.'", ")" ]
read __init__.py
[ "read", "__init__", ".", "py" ]
train
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/setup.py#L25-L42
quora/qcore
qcore/debug.py
trace
def trace(enter=False, exit=True): """ This decorator prints entry and exit message when the decorated method is called, as well as call arguments, result and thrown exception (if any). :param enter: indicates whether entry message should be printed. :param exit: indicates whether exit message should be printed. :return: decorated function. """ def decorate(fn): @inspection.wraps(fn) def new_fn(*args, **kwargs): name = fn.__module__ + "." + fn.__name__ if enter: print( "%s(args = %s, kwargs = %s) <-" % (name, repr(args), repr(kwargs)) ) try: result = fn(*args, **kwargs) if exit: print( "%s(args = %s, kwargs = %s) -> %s" % (name, repr(args), repr(kwargs), repr(result)) ) return result except Exception as e: if exit: print( "%s(args = %s, kwargs = %s) -> thrown %s" % (name, repr(args), repr(kwargs), str(e)) ) raise return new_fn return decorate
python
def trace(enter=False, exit=True): """ This decorator prints entry and exit message when the decorated method is called, as well as call arguments, result and thrown exception (if any). :param enter: indicates whether entry message should be printed. :param exit: indicates whether exit message should be printed. :return: decorated function. """ def decorate(fn): @inspection.wraps(fn) def new_fn(*args, **kwargs): name = fn.__module__ + "." + fn.__name__ if enter: print( "%s(args = %s, kwargs = %s) <-" % (name, repr(args), repr(kwargs)) ) try: result = fn(*args, **kwargs) if exit: print( "%s(args = %s, kwargs = %s) -> %s" % (name, repr(args), repr(kwargs), repr(result)) ) return result except Exception as e: if exit: print( "%s(args = %s, kwargs = %s) -> thrown %s" % (name, repr(args), repr(kwargs), str(e)) ) raise return new_fn return decorate
[ "def", "trace", "(", "enter", "=", "False", ",", "exit", "=", "True", ")", ":", "def", "decorate", "(", "fn", ")", ":", "@", "inspection", ".", "wraps", "(", "fn", ")", "def", "new_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "fn", ".", "__module__", "+", "\".\"", "+", "fn", ".", "__name__", "if", "enter", ":", "print", "(", "\"%s(args = %s, kwargs = %s) <-\"", "%", "(", "name", ",", "repr", "(", "args", ")", ",", "repr", "(", "kwargs", ")", ")", ")", "try", ":", "result", "=", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "exit", ":", "print", "(", "\"%s(args = %s, kwargs = %s) -> %s\"", "%", "(", "name", ",", "repr", "(", "args", ")", ",", "repr", "(", "kwargs", ")", ",", "repr", "(", "result", ")", ")", ")", "return", "result", "except", "Exception", "as", "e", ":", "if", "exit", ":", "print", "(", "\"%s(args = %s, kwargs = %s) -> thrown %s\"", "%", "(", "name", ",", "repr", "(", "args", ")", ",", "repr", "(", "kwargs", ")", ",", "str", "(", "e", ")", ")", ")", "raise", "return", "new_fn", "return", "decorate" ]
This decorator prints entry and exit message when the decorated method is called, as well as call arguments, result and thrown exception (if any). :param enter: indicates whether entry message should be printed. :param exit: indicates whether exit message should be printed. :return: decorated function.
[ "This", "decorator", "prints", "entry", "and", "exit", "message", "when", "the", "decorated", "method", "is", "called", "as", "well", "as", "call", "arguments", "result", "and", "thrown", "exception", "(", "if", "any", ")", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/debug.py#L33-L71
quora/qcore
qcore/enum.py
EnumType._make_value
def _make_value(self, value): """Instantiates an enum with an arbitrary value.""" member = self.__new__(self, value) member.__init__(value) return member
python
def _make_value(self, value): """Instantiates an enum with an arbitrary value.""" member = self.__new__(self, value) member.__init__(value) return member
[ "def", "_make_value", "(", "self", ",", "value", ")", ":", "member", "=", "self", ".", "__new__", "(", "self", ",", "value", ")", "member", ".", "__init__", "(", "value", ")", "return", "member" ]
Instantiates an enum with an arbitrary value.
[ "Instantiates", "an", "enum", "with", "an", "arbitrary", "value", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/enum.py#L89-L93
quora/qcore
qcore/enum.py
EnumBase.create
def create(cls, name, members): """Creates a new enum type based on this one (cls) and adds newly passed members to the newly created subclass of cls. This method helps to create enums having the same member values as values of other enum(s). :param name: name of the newly created type :param members: 1) a dict or 2) a list of (name, value) tuples and/or EnumBase instances describing new members :return: newly created enum type. """ NewEnum = type(name, (cls,), {}) if isinstance(members, dict): members = members.items() for member in members: if isinstance(member, tuple): name, value = member setattr(NewEnum, name, value) elif isinstance(member, EnumBase): setattr(NewEnum, member.short_name, member.value) else: assert False, ( "members must be either a dict, " + "a list of (name, value) tuples, " + "or a list of EnumBase instances." ) NewEnum.process() # needed for pickling to work (hopefully); taken from the namedtuple implementation in the # standard library try: NewEnum.__module__ = sys._getframe(1).f_globals.get("__name__", "__main__") except (AttributeError, ValueError): pass return NewEnum
python
def create(cls, name, members): """Creates a new enum type based on this one (cls) and adds newly passed members to the newly created subclass of cls. This method helps to create enums having the same member values as values of other enum(s). :param name: name of the newly created type :param members: 1) a dict or 2) a list of (name, value) tuples and/or EnumBase instances describing new members :return: newly created enum type. """ NewEnum = type(name, (cls,), {}) if isinstance(members, dict): members = members.items() for member in members: if isinstance(member, tuple): name, value = member setattr(NewEnum, name, value) elif isinstance(member, EnumBase): setattr(NewEnum, member.short_name, member.value) else: assert False, ( "members must be either a dict, " + "a list of (name, value) tuples, " + "or a list of EnumBase instances." ) NewEnum.process() # needed for pickling to work (hopefully); taken from the namedtuple implementation in the # standard library try: NewEnum.__module__ = sys._getframe(1).f_globals.get("__name__", "__main__") except (AttributeError, ValueError): pass return NewEnum
[ "def", "create", "(", "cls", ",", "name", ",", "members", ")", ":", "NewEnum", "=", "type", "(", "name", ",", "(", "cls", ",", ")", ",", "{", "}", ")", "if", "isinstance", "(", "members", ",", "dict", ")", ":", "members", "=", "members", ".", "items", "(", ")", "for", "member", "in", "members", ":", "if", "isinstance", "(", "member", ",", "tuple", ")", ":", "name", ",", "value", "=", "member", "setattr", "(", "NewEnum", ",", "name", ",", "value", ")", "elif", "isinstance", "(", "member", ",", "EnumBase", ")", ":", "setattr", "(", "NewEnum", ",", "member", ".", "short_name", ",", "member", ".", "value", ")", "else", ":", "assert", "False", ",", "(", "\"members must be either a dict, \"", "+", "\"a list of (name, value) tuples, \"", "+", "\"or a list of EnumBase instances.\"", ")", "NewEnum", ".", "process", "(", ")", "# needed for pickling to work (hopefully); taken from the namedtuple implementation in the", "# standard library", "try", ":", "NewEnum", ".", "__module__", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", ".", "get", "(", "\"__name__\"", ",", "\"__main__\"", ")", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "pass", "return", "NewEnum" ]
Creates a new enum type based on this one (cls) and adds newly passed members to the newly created subclass of cls. This method helps to create enums having the same member values as values of other enum(s). :param name: name of the newly created type :param members: 1) a dict or 2) a list of (name, value) tuples and/or EnumBase instances describing new members :return: newly created enum type.
[ "Creates", "a", "new", "enum", "type", "based", "on", "this", "one", "(", "cls", ")", "and", "adds", "newly", "passed", "members", "to", "the", "newly", "created", "subclass", "of", "cls", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/enum.py#L175-L214
quora/qcore
qcore/enum.py
Enum.parse
def parse(cls, value, default=_no_default): """Parses an enum member name or value into an enum member. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. If there is an enum member with the integer as a value, that member is returned. - Strings. If there is an enum member with the string as its name, that member is returned. For integers and strings that don't correspond to an enum member, default is returned; if no default is given the function raises KeyError instead. Examples: >>> class Color(Enum): ... red = 1 ... blue = 2 >>> Color.parse(Color.red) Color.red >>> Color.parse(1) Color.red >>> Color.parse('blue') Color.blue """ if isinstance(value, cls): return value elif isinstance(value, six.integer_types) and not isinstance(value, EnumBase): e = cls._value_to_member.get(value, _no_default) else: e = cls._name_to_member.get(value, _no_default) if e is _no_default or not e.is_valid(): if default is _no_default: raise _create_invalid_value_error(cls, value) return default return e
python
def parse(cls, value, default=_no_default): """Parses an enum member name or value into an enum member. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. If there is an enum member with the integer as a value, that member is returned. - Strings. If there is an enum member with the string as its name, that member is returned. For integers and strings that don't correspond to an enum member, default is returned; if no default is given the function raises KeyError instead. Examples: >>> class Color(Enum): ... red = 1 ... blue = 2 >>> Color.parse(Color.red) Color.red >>> Color.parse(1) Color.red >>> Color.parse('blue') Color.blue """ if isinstance(value, cls): return value elif isinstance(value, six.integer_types) and not isinstance(value, EnumBase): e = cls._value_to_member.get(value, _no_default) else: e = cls._name_to_member.get(value, _no_default) if e is _no_default or not e.is_valid(): if default is _no_default: raise _create_invalid_value_error(cls, value) return default return e
[ "def", "parse", "(", "cls", ",", "value", ",", "default", "=", "_no_default", ")", ":", "if", "isinstance", "(", "value", ",", "cls", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "six", ".", "integer_types", ")", "and", "not", "isinstance", "(", "value", ",", "EnumBase", ")", ":", "e", "=", "cls", ".", "_value_to_member", ".", "get", "(", "value", ",", "_no_default", ")", "else", ":", "e", "=", "cls", ".", "_name_to_member", ".", "get", "(", "value", ",", "_no_default", ")", "if", "e", "is", "_no_default", "or", "not", "e", ".", "is_valid", "(", ")", ":", "if", "default", "is", "_no_default", ":", "raise", "_create_invalid_value_error", "(", "cls", ",", "value", ")", "return", "default", "return", "e" ]
Parses an enum member name or value into an enum member. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. If there is an enum member with the integer as a value, that member is returned. - Strings. If there is an enum member with the string as its name, that member is returned. For integers and strings that don't correspond to an enum member, default is returned; if no default is given the function raises KeyError instead. Examples: >>> class Color(Enum): ... red = 1 ... blue = 2 >>> Color.parse(Color.red) Color.red >>> Color.parse(1) Color.red >>> Color.parse('blue') Color.blue
[ "Parses", "an", "enum", "member", "name", "or", "value", "into", "an", "enum", "member", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/enum.py#L239-L272
quora/qcore
qcore/enum.py
Flags.parse
def parse(cls, value, default=_no_default): """Parses a flag integer or string into a Flags instance. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. These are converted directly into a Flags instance with the given name. - Strings. The function accepts a comma-delimited list of flag names, corresponding to members of the enum. These are all ORed together. Examples: >>> class Car(Flags): ... is_big = 1 ... has_wheels = 2 >>> Car.parse(1) Car.is_big >>> Car.parse(3) Car.parse('has_wheels,is_big') >>> Car.parse('is_big,has_wheels') Car.parse('has_wheels,is_big') """ if isinstance(value, cls): return value elif isinstance(value, int): e = cls._make_value(value) else: if not value: e = cls._make_value(0) else: r = 0 for k in value.split(","): v = cls._name_to_member.get(k, _no_default) if v is _no_default: if default is _no_default: raise _create_invalid_value_error(cls, value) else: return default r |= v.value e = cls._make_value(r) if not e.is_valid(): if default is _no_default: raise _create_invalid_value_error(cls, value) return default return e
python
def parse(cls, value, default=_no_default): """Parses a flag integer or string into a Flags instance. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. These are converted directly into a Flags instance with the given name. - Strings. The function accepts a comma-delimited list of flag names, corresponding to members of the enum. These are all ORed together. Examples: >>> class Car(Flags): ... is_big = 1 ... has_wheels = 2 >>> Car.parse(1) Car.is_big >>> Car.parse(3) Car.parse('has_wheels,is_big') >>> Car.parse('is_big,has_wheels') Car.parse('has_wheels,is_big') """ if isinstance(value, cls): return value elif isinstance(value, int): e = cls._make_value(value) else: if not value: e = cls._make_value(0) else: r = 0 for k in value.split(","): v = cls._name_to_member.get(k, _no_default) if v is _no_default: if default is _no_default: raise _create_invalid_value_error(cls, value) else: return default r |= v.value e = cls._make_value(r) if not e.is_valid(): if default is _no_default: raise _create_invalid_value_error(cls, value) return default return e
[ "def", "parse", "(", "cls", ",", "value", ",", "default", "=", "_no_default", ")", ":", "if", "isinstance", "(", "value", ",", "cls", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "int", ")", ":", "e", "=", "cls", ".", "_make_value", "(", "value", ")", "else", ":", "if", "not", "value", ":", "e", "=", "cls", ".", "_make_value", "(", "0", ")", "else", ":", "r", "=", "0", "for", "k", "in", "value", ".", "split", "(", "\",\"", ")", ":", "v", "=", "cls", ".", "_name_to_member", ".", "get", "(", "k", ",", "_no_default", ")", "if", "v", "is", "_no_default", ":", "if", "default", "is", "_no_default", ":", "raise", "_create_invalid_value_error", "(", "cls", ",", "value", ")", "else", ":", "return", "default", "r", "|=", "v", ".", "value", "e", "=", "cls", ".", "_make_value", "(", "r", ")", "if", "not", "e", ".", "is_valid", "(", ")", ":", "if", "default", "is", "_no_default", ":", "raise", "_create_invalid_value_error", "(", "cls", ",", "value", ")", "return", "default", "return", "e" ]
Parses a flag integer or string into a Flags instance. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. These are converted directly into a Flags instance with the given name. - Strings. The function accepts a comma-delimited list of flag names, corresponding to members of the enum. These are all ORed together. Examples: >>> class Car(Flags): ... is_big = 1 ... has_wheels = 2 >>> Car.parse(1) Car.is_big >>> Car.parse(3) Car.parse('has_wheels,is_big') >>> Car.parse('is_big,has_wheels') Car.parse('has_wheels,is_big')
[ "Parses", "a", "flag", "integer", "or", "string", "into", "a", "Flags", "instance", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/enum.py#L300-L344
opennode/waldur-core
waldur_core/cost_tracking/views.py
PriceEstimateViewSet.list
def list(self, request, *args, **kwargs): """ To get a list of price estimates, run **GET** against */api/price-estimates/* as authenticated user. You can filter price estimates by scope type, scope URL, customer UUID. `scope_type` is generic type of object for which price estimate is calculated. Currently there are following types: customer, project, service, serviceprojectlink, resource. `date` parameter accepts list of dates. `start` and `end` parameters together specify date range. Each valid date should in format YYYY.MM You can specify GET parameter ?depth to show price estimate children. For example with ?depth=2 customer price estimate will shows its children - project and service and grandchildren - serviceprojectlink. """ return super(PriceEstimateViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ To get a list of price estimates, run **GET** against */api/price-estimates/* as authenticated user. You can filter price estimates by scope type, scope URL, customer UUID. `scope_type` is generic type of object for which price estimate is calculated. Currently there are following types: customer, project, service, serviceprojectlink, resource. `date` parameter accepts list of dates. `start` and `end` parameters together specify date range. Each valid date should in format YYYY.MM You can specify GET parameter ?depth to show price estimate children. For example with ?depth=2 customer price estimate will shows its children - project and service and grandchildren - serviceprojectlink. """ return super(PriceEstimateViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "PriceEstimateViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To get a list of price estimates, run **GET** against */api/price-estimates/* as authenticated user. You can filter price estimates by scope type, scope URL, customer UUID. `scope_type` is generic type of object for which price estimate is calculated. Currently there are following types: customer, project, service, serviceprojectlink, resource. `date` parameter accepts list of dates. `start` and `end` parameters together specify date range. Each valid date should in format YYYY.MM You can specify GET parameter ?depth to show price estimate children. For example with ?depth=2 customer price estimate will shows its children - project and service and grandchildren - serviceprojectlink.
[ "To", "get", "a", "list", "of", "price", "estimates", "run", "**", "GET", "**", "against", "*", "/", "api", "/", "price", "-", "estimates", "/", "*", "as", "authenticated", "user", ".", "You", "can", "filter", "price", "estimates", "by", "scope", "type", "scope", "URL", "customer", "UUID", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/views.py#L40-L54
opennode/waldur-core
waldur_core/cost_tracking/views.py
PriceListItemViewSet.list
def list(self, request, *args, **kwargs): """ To get a list of price list items, run **GET** against */api/price-list-items/* as an authenticated user. """ return super(PriceListItemViewSet, self).list(request, *args, **kwargs)
python
def list(self, request, *args, **kwargs): """ To get a list of price list items, run **GET** against */api/price-list-items/* as an authenticated user. """ return super(PriceListItemViewSet, self).list(request, *args, **kwargs)
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "PriceListItemViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
To get a list of price list items, run **GET** against */api/price-list-items/* as an authenticated user.
[ "To", "get", "a", "list", "of", "price", "list", "items", "run", "**", "GET", "**", "against", "*", "/", "api", "/", "price", "-", "list", "-", "items", "/", "*", "as", "an", "authenticated", "user", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/views.py#L73-L77