repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
kwikteam/phy | phy/plot/transform.py | _glslify | def _glslify(r):
"""Transform a string or a n-tuple to a valid GLSL expression."""
if isinstance(r, string_types):
return r
else:
assert 2 <= len(r) <= 4
return 'vec{}({})'.format(len(r), ', '.join(map(str, r))) | python | def _glslify(r):
"""Transform a string or a n-tuple to a valid GLSL expression."""
if isinstance(r, string_types):
return r
else:
assert 2 <= len(r) <= 4
return 'vec{}({})'.format(len(r), ', '.join(map(str, r))) | [
"def",
"_glslify",
"(",
"r",
")",
":",
"if",
"isinstance",
"(",
"r",
",",
"string_types",
")",
":",
"return",
"r",
"else",
":",
"assert",
"2",
"<=",
"len",
"(",
"r",
")",
"<=",
"4",
"return",
"'vec{}({})'",
".",
"format",
"(",
"len",
"(",
"r",
")",
",",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"r",
")",
")",
")"
]
| Transform a string or a n-tuple to a valid GLSL expression. | [
"Transform",
"a",
"string",
"or",
"a",
"n",
"-",
"tuple",
"to",
"a",
"valid",
"GLSL",
"expression",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L48-L54 | train |
kwikteam/phy | phy/plot/transform.py | TransformChain.get | def get(self, class_name):
"""Get a transform in the chain from its name."""
for transform in self.cpu_transforms + self.gpu_transforms:
if transform.__class__.__name__ == class_name:
return transform | python | def get(self, class_name):
"""Get a transform in the chain from its name."""
for transform in self.cpu_transforms + self.gpu_transforms:
if transform.__class__.__name__ == class_name:
return transform | [
"def",
"get",
"(",
"self",
",",
"class_name",
")",
":",
"for",
"transform",
"in",
"self",
".",
"cpu_transforms",
"+",
"self",
".",
"gpu_transforms",
":",
"if",
"transform",
".",
"__class__",
".",
"__name__",
"==",
"class_name",
":",
"return",
"transform"
]
| Get a transform in the chain from its name. | [
"Get",
"a",
"transform",
"in",
"the",
"chain",
"from",
"its",
"name",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L291-L295 | train |
kwikteam/phy | phy/plot/transform.py | TransformChain.remove | def remove(self, name):
"""Remove a transform in the chain."""
cpu_transforms = self._remove_transform(self.cpu_transforms, name)
gpu_transforms = self._remove_transform(self.gpu_transforms, name)
return (TransformChain().add_on_cpu(cpu_transforms).
add_on_gpu(gpu_transforms)) | python | def remove(self, name):
"""Remove a transform in the chain."""
cpu_transforms = self._remove_transform(self.cpu_transforms, name)
gpu_transforms = self._remove_transform(self.gpu_transforms, name)
return (TransformChain().add_on_cpu(cpu_transforms).
add_on_gpu(gpu_transforms)) | [
"def",
"remove",
"(",
"self",
",",
"name",
")",
":",
"cpu_transforms",
"=",
"self",
".",
"_remove_transform",
"(",
"self",
".",
"cpu_transforms",
",",
"name",
")",
"gpu_transforms",
"=",
"self",
".",
"_remove_transform",
"(",
"self",
".",
"gpu_transforms",
",",
"name",
")",
"return",
"(",
"TransformChain",
"(",
")",
".",
"add_on_cpu",
"(",
"cpu_transforms",
")",
".",
"add_on_gpu",
"(",
"gpu_transforms",
")",
")"
]
| Remove a transform in the chain. | [
"Remove",
"a",
"transform",
"in",
"the",
"chain",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L300-L305 | train |
kwikteam/phy | phy/plot/transform.py | TransformChain.apply | def apply(self, arr):
"""Apply all CPU transforms on an array."""
for t in self.cpu_transforms:
arr = t.apply(arr)
return arr | python | def apply(self, arr):
"""Apply all CPU transforms on an array."""
for t in self.cpu_transforms:
arr = t.apply(arr)
return arr | [
"def",
"apply",
"(",
"self",
",",
"arr",
")",
":",
"for",
"t",
"in",
"self",
".",
"cpu_transforms",
":",
"arr",
"=",
"t",
".",
"apply",
"(",
"arr",
")",
"return",
"arr"
]
| Apply all CPU transforms on an array. | [
"Apply",
"all",
"CPU",
"transforms",
"on",
"an",
"array",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L307-L311 | train |
kwikteam/phy | phy/plot/transform.py | TransformChain.inverse | def inverse(self):
"""Return the inverse chain of transforms."""
transforms = self.cpu_transforms + self.gpu_transforms
inv_transforms = [transform.inverse()
for transform in transforms[::-1]]
return TransformChain().add_on_cpu(inv_transforms) | python | def inverse(self):
"""Return the inverse chain of transforms."""
transforms = self.cpu_transforms + self.gpu_transforms
inv_transforms = [transform.inverse()
for transform in transforms[::-1]]
return TransformChain().add_on_cpu(inv_transforms) | [
"def",
"inverse",
"(",
"self",
")",
":",
"transforms",
"=",
"self",
".",
"cpu_transforms",
"+",
"self",
".",
"gpu_transforms",
"inv_transforms",
"=",
"[",
"transform",
".",
"inverse",
"(",
")",
"for",
"transform",
"in",
"transforms",
"[",
":",
":",
"-",
"1",
"]",
"]",
"return",
"TransformChain",
"(",
")",
".",
"add_on_cpu",
"(",
"inv_transforms",
")"
]
| Return the inverse chain of transforms. | [
"Return",
"the",
"inverse",
"chain",
"of",
"transforms",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/plot/transform.py#L313-L318 | train |
kwikteam/phy | phy/utils/event.py | EventEmitter._create_emitter | def _create_emitter(self, event):
"""Create a method that emits an event of the same name."""
if not hasattr(self, event):
setattr(self, event,
lambda *args, **kwargs: self.emit(event, *args, **kwargs)) | python | def _create_emitter(self, event):
"""Create a method that emits an event of the same name."""
if not hasattr(self, event):
setattr(self, event,
lambda *args, **kwargs: self.emit(event, *args, **kwargs)) | [
"def",
"_create_emitter",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"event",
")",
":",
"setattr",
"(",
"self",
",",
"event",
",",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"self",
".",
"emit",
"(",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
]
| Create a method that emits an event of the same name. | [
"Create",
"a",
"method",
"that",
"emits",
"an",
"event",
"of",
"the",
"same",
"name",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L62-L66 | train |
kwikteam/phy | phy/utils/event.py | EventEmitter.connect | def connect(self, func=None, event=None, set_method=False):
"""Register a callback function to a given event.
To register a callback function to the `spam` event, where `obj` is
an instance of a class deriving from `EventEmitter`:
```python
@obj.connect
def on_spam(arg1, arg2):
pass
```
This is called when `obj.emit('spam', arg1, arg2)` is called.
Several callback functions can be registered for a given event.
The registration order is conserved and may matter in applications.
"""
if func is None:
return partial(self.connect, set_method=set_method)
# Get the event name from the function.
if event is None:
event = self._get_on_name(func)
# We register the callback function.
self._callbacks[event].append(func)
# A new method self.event() emitting the event is created.
if set_method:
self._create_emitter(event)
return func | python | def connect(self, func=None, event=None, set_method=False):
"""Register a callback function to a given event.
To register a callback function to the `spam` event, where `obj` is
an instance of a class deriving from `EventEmitter`:
```python
@obj.connect
def on_spam(arg1, arg2):
pass
```
This is called when `obj.emit('spam', arg1, arg2)` is called.
Several callback functions can be registered for a given event.
The registration order is conserved and may matter in applications.
"""
if func is None:
return partial(self.connect, set_method=set_method)
# Get the event name from the function.
if event is None:
event = self._get_on_name(func)
# We register the callback function.
self._callbacks[event].append(func)
# A new method self.event() emitting the event is created.
if set_method:
self._create_emitter(event)
return func | [
"def",
"connect",
"(",
"self",
",",
"func",
"=",
"None",
",",
"event",
"=",
"None",
",",
"set_method",
"=",
"False",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"partial",
"(",
"self",
".",
"connect",
",",
"set_method",
"=",
"set_method",
")",
"# Get the event name from the function.",
"if",
"event",
"is",
"None",
":",
"event",
"=",
"self",
".",
"_get_on_name",
"(",
"func",
")",
"# We register the callback function.",
"self",
".",
"_callbacks",
"[",
"event",
"]",
".",
"append",
"(",
"func",
")",
"# A new method self.event() emitting the event is created.",
"if",
"set_method",
":",
"self",
".",
"_create_emitter",
"(",
"event",
")",
"return",
"func"
]
| Register a callback function to a given event.
To register a callback function to the `spam` event, where `obj` is
an instance of a class deriving from `EventEmitter`:
```python
@obj.connect
def on_spam(arg1, arg2):
pass
```
This is called when `obj.emit('spam', arg1, arg2)` is called.
Several callback functions can be registered for a given event.
The registration order is conserved and may matter in applications. | [
"Register",
"a",
"callback",
"function",
"to",
"a",
"given",
"event",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L68-L101 | train |
kwikteam/phy | phy/utils/event.py | EventEmitter.unconnect | def unconnect(self, *funcs):
"""Unconnect specified callback functions."""
for func in funcs:
for callbacks in self._callbacks.values():
if func in callbacks:
callbacks.remove(func) | python | def unconnect(self, *funcs):
"""Unconnect specified callback functions."""
for func in funcs:
for callbacks in self._callbacks.values():
if func in callbacks:
callbacks.remove(func) | [
"def",
"unconnect",
"(",
"self",
",",
"*",
"funcs",
")",
":",
"for",
"func",
"in",
"funcs",
":",
"for",
"callbacks",
"in",
"self",
".",
"_callbacks",
".",
"values",
"(",
")",
":",
"if",
"func",
"in",
"callbacks",
":",
"callbacks",
".",
"remove",
"(",
"func",
")"
]
| Unconnect specified callback functions. | [
"Unconnect",
"specified",
"callback",
"functions",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L103-L108 | train |
kwikteam/phy | phy/utils/event.py | EventEmitter.emit | def emit(self, event, *args, **kwargs):
"""Call all callback functions registered with an event.
Any positional and keyword arguments can be passed here, and they will
be forwarded to the callback functions.
Return the list of callback return results.
"""
callbacks = self._callbacks.get(event, [])
# Call the last callback if this is a single event.
single = kwargs.pop('single', None)
if single and callbacks:
return callbacks[-1](*args, **kwargs)
# Otherwise, return the list of callback outputs.
res = []
for callback in callbacks:
res.append(callback(*args, **kwargs))
return res | python | def emit(self, event, *args, **kwargs):
"""Call all callback functions registered with an event.
Any positional and keyword arguments can be passed here, and they will
be forwarded to the callback functions.
Return the list of callback return results.
"""
callbacks = self._callbacks.get(event, [])
# Call the last callback if this is a single event.
single = kwargs.pop('single', None)
if single and callbacks:
return callbacks[-1](*args, **kwargs)
# Otherwise, return the list of callback outputs.
res = []
for callback in callbacks:
res.append(callback(*args, **kwargs))
return res | [
"def",
"emit",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"callbacks",
"=",
"self",
".",
"_callbacks",
".",
"get",
"(",
"event",
",",
"[",
"]",
")",
"# Call the last callback if this is a single event.",
"single",
"=",
"kwargs",
".",
"pop",
"(",
"'single'",
",",
"None",
")",
"if",
"single",
"and",
"callbacks",
":",
"return",
"callbacks",
"[",
"-",
"1",
"]",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Otherwise, return the list of callback outputs.",
"res",
"=",
"[",
"]",
"for",
"callback",
"in",
"callbacks",
":",
"res",
".",
"append",
"(",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"res"
]
| Call all callback functions registered with an event.
Any positional and keyword arguments can be passed here, and they will
be forwarded to the callback functions.
Return the list of callback return results. | [
"Call",
"all",
"callback",
"functions",
"registered",
"with",
"an",
"event",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L110-L128 | train |
kwikteam/phy | phy/utils/event.py | ProgressReporter.set_progress_message | def set_progress_message(self, message, line_break=False):
"""Set a progress message.
The string needs to contain `{progress}`.
"""
end = '\r' if not line_break else None
@self.connect
def on_progress(value, value_max, **kwargs):
kwargs['end'] = None if value == value_max else end
_default_on_progress(message, value, value_max, **kwargs) | python | def set_progress_message(self, message, line_break=False):
"""Set a progress message.
The string needs to contain `{progress}`.
"""
end = '\r' if not line_break else None
@self.connect
def on_progress(value, value_max, **kwargs):
kwargs['end'] = None if value == value_max else end
_default_on_progress(message, value, value_max, **kwargs) | [
"def",
"set_progress_message",
"(",
"self",
",",
"message",
",",
"line_break",
"=",
"False",
")",
":",
"end",
"=",
"'\\r'",
"if",
"not",
"line_break",
"else",
"None",
"@",
"self",
".",
"connect",
"def",
"on_progress",
"(",
"value",
",",
"value_max",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'end'",
"]",
"=",
"None",
"if",
"value",
"==",
"value_max",
"else",
"end",
"_default_on_progress",
"(",
"message",
",",
"value",
",",
"value_max",
",",
"*",
"*",
"kwargs",
")"
]
| Set a progress message.
The string needs to contain `{progress}`. | [
"Set",
"a",
"progress",
"message",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L204-L216 | train |
kwikteam/phy | phy/utils/event.py | ProgressReporter.set_complete_message | def set_complete_message(self, message):
"""Set a complete message."""
@self.connect
def on_complete(**kwargs):
_default_on_complete(message, **kwargs) | python | def set_complete_message(self, message):
"""Set a complete message."""
@self.connect
def on_complete(**kwargs):
_default_on_complete(message, **kwargs) | [
"def",
"set_complete_message",
"(",
"self",
",",
"message",
")",
":",
"@",
"self",
".",
"connect",
"def",
"on_complete",
"(",
"*",
"*",
"kwargs",
")",
":",
"_default_on_complete",
"(",
"message",
",",
"*",
"*",
"kwargs",
")"
]
| Set a complete message. | [
"Set",
"a",
"complete",
"message",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/event.py#L218-L223 | train |
kwikteam/phy | phy/utils/plugin.py | get_plugin | def get_plugin(name):
"""Get a plugin class from its name."""
for plugin in IPluginRegistry.plugins:
if name in plugin.__name__:
return plugin
raise ValueError("The plugin %s cannot be found." % name) | python | def get_plugin(name):
"""Get a plugin class from its name."""
for plugin in IPluginRegistry.plugins:
if name in plugin.__name__:
return plugin
raise ValueError("The plugin %s cannot be found." % name) | [
"def",
"get_plugin",
"(",
"name",
")",
":",
"for",
"plugin",
"in",
"IPluginRegistry",
".",
"plugins",
":",
"if",
"name",
"in",
"plugin",
".",
"__name__",
":",
"return",
"plugin",
"raise",
"ValueError",
"(",
"\"The plugin %s cannot be found.\"",
"%",
"name",
")"
]
| Get a plugin class from its name. | [
"Get",
"a",
"plugin",
"class",
"from",
"its",
"name",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/plugin.py#L50-L55 | train |
kwikteam/phy | phy/utils/plugin.py | discover_plugins | def discover_plugins(dirs):
"""Discover the plugin classes contained in Python files.
Parameters
----------
dirs : list
List of directory names to scan.
Returns
-------
plugins : list
List of plugin classes.
"""
# Scan all subdirectories recursively.
for path in _iter_plugin_files(dirs):
filename = op.basename(path)
subdir = op.dirname(path)
modname, ext = op.splitext(filename)
file, path, descr = imp.find_module(modname, [subdir])
if file:
# Loading the module registers the plugin in
# IPluginRegistry.
try:
mod = imp.load_module(modname, file, path, descr) # noqa
except Exception as e: # pragma: no cover
logger.exception(e)
finally:
file.close()
return IPluginRegistry.plugins | python | def discover_plugins(dirs):
"""Discover the plugin classes contained in Python files.
Parameters
----------
dirs : list
List of directory names to scan.
Returns
-------
plugins : list
List of plugin classes.
"""
# Scan all subdirectories recursively.
for path in _iter_plugin_files(dirs):
filename = op.basename(path)
subdir = op.dirname(path)
modname, ext = op.splitext(filename)
file, path, descr = imp.find_module(modname, [subdir])
if file:
# Loading the module registers the plugin in
# IPluginRegistry.
try:
mod = imp.load_module(modname, file, path, descr) # noqa
except Exception as e: # pragma: no cover
logger.exception(e)
finally:
file.close()
return IPluginRegistry.plugins | [
"def",
"discover_plugins",
"(",
"dirs",
")",
":",
"# Scan all subdirectories recursively.",
"for",
"path",
"in",
"_iter_plugin_files",
"(",
"dirs",
")",
":",
"filename",
"=",
"op",
".",
"basename",
"(",
"path",
")",
"subdir",
"=",
"op",
".",
"dirname",
"(",
"path",
")",
"modname",
",",
"ext",
"=",
"op",
".",
"splitext",
"(",
"filename",
")",
"file",
",",
"path",
",",
"descr",
"=",
"imp",
".",
"find_module",
"(",
"modname",
",",
"[",
"subdir",
"]",
")",
"if",
"file",
":",
"# Loading the module registers the plugin in",
"# IPluginRegistry.",
"try",
":",
"mod",
"=",
"imp",
".",
"load_module",
"(",
"modname",
",",
"file",
",",
"path",
",",
"descr",
")",
"# noqa",
"except",
"Exception",
"as",
"e",
":",
"# pragma: no cover",
"logger",
".",
"exception",
"(",
"e",
")",
"finally",
":",
"file",
".",
"close",
"(",
")",
"return",
"IPluginRegistry",
".",
"plugins"
]
| Discover the plugin classes contained in Python files.
Parameters
----------
dirs : list
List of directory names to scan.
Returns
-------
plugins : list
List of plugin classes. | [
"Discover",
"the",
"plugin",
"classes",
"contained",
"in",
"Python",
"files",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/plugin.py#L81-L112 | train |
kwikteam/phy | phy/gui/gui.py | GUI.add_view | def add_view(self,
view,
name=None,
position=None,
closable=False,
floatable=True,
floating=None):
"""Add a widget to the main window."""
# Set the name in the view.
view.view_index = self._get_view_index(view)
# The view name is `<class_name><view_index>`, e.g. `MyView0`.
view.name = name or view.__class__.__name__ + str(view.view_index)
# Get the Qt canvas for VisPy and matplotlib views.
widget = _try_get_vispy_canvas(view)
widget = _try_get_matplotlib_canvas(widget)
dock_widget = _create_dock_widget(widget, view.name,
closable=closable,
floatable=floatable,
)
self.addDockWidget(_get_dock_position(position), dock_widget)
if floating is not None:
dock_widget.setFloating(floating)
dock_widget.view = view
# Emit the close_view event when the dock widget is closed.
@dock_widget.connect_
def on_close_widget():
self.emit('close_view', view)
dock_widget.show()
self.emit('add_view', view)
logger.log(5, "Add %s to GUI.", view.name)
return dock_widget | python | def add_view(self,
view,
name=None,
position=None,
closable=False,
floatable=True,
floating=None):
"""Add a widget to the main window."""
# Set the name in the view.
view.view_index = self._get_view_index(view)
# The view name is `<class_name><view_index>`, e.g. `MyView0`.
view.name = name or view.__class__.__name__ + str(view.view_index)
# Get the Qt canvas for VisPy and matplotlib views.
widget = _try_get_vispy_canvas(view)
widget = _try_get_matplotlib_canvas(widget)
dock_widget = _create_dock_widget(widget, view.name,
closable=closable,
floatable=floatable,
)
self.addDockWidget(_get_dock_position(position), dock_widget)
if floating is not None:
dock_widget.setFloating(floating)
dock_widget.view = view
# Emit the close_view event when the dock widget is closed.
@dock_widget.connect_
def on_close_widget():
self.emit('close_view', view)
dock_widget.show()
self.emit('add_view', view)
logger.log(5, "Add %s to GUI.", view.name)
return dock_widget | [
"def",
"add_view",
"(",
"self",
",",
"view",
",",
"name",
"=",
"None",
",",
"position",
"=",
"None",
",",
"closable",
"=",
"False",
",",
"floatable",
"=",
"True",
",",
"floating",
"=",
"None",
")",
":",
"# Set the name in the view.",
"view",
".",
"view_index",
"=",
"self",
".",
"_get_view_index",
"(",
"view",
")",
"# The view name is `<class_name><view_index>`, e.g. `MyView0`.",
"view",
".",
"name",
"=",
"name",
"or",
"view",
".",
"__class__",
".",
"__name__",
"+",
"str",
"(",
"view",
".",
"view_index",
")",
"# Get the Qt canvas for VisPy and matplotlib views.",
"widget",
"=",
"_try_get_vispy_canvas",
"(",
"view",
")",
"widget",
"=",
"_try_get_matplotlib_canvas",
"(",
"widget",
")",
"dock_widget",
"=",
"_create_dock_widget",
"(",
"widget",
",",
"view",
".",
"name",
",",
"closable",
"=",
"closable",
",",
"floatable",
"=",
"floatable",
",",
")",
"self",
".",
"addDockWidget",
"(",
"_get_dock_position",
"(",
"position",
")",
",",
"dock_widget",
")",
"if",
"floating",
"is",
"not",
"None",
":",
"dock_widget",
".",
"setFloating",
"(",
"floating",
")",
"dock_widget",
".",
"view",
"=",
"view",
"# Emit the close_view event when the dock widget is closed.",
"@",
"dock_widget",
".",
"connect_",
"def",
"on_close_widget",
"(",
")",
":",
"self",
".",
"emit",
"(",
"'close_view'",
",",
"view",
")",
"dock_widget",
".",
"show",
"(",
")",
"self",
".",
"emit",
"(",
"'add_view'",
",",
"view",
")",
"logger",
".",
"log",
"(",
"5",
",",
"\"Add %s to GUI.\"",
",",
"view",
".",
"name",
")",
"return",
"dock_widget"
]
| Add a widget to the main window. | [
"Add",
"a",
"widget",
"to",
"the",
"main",
"window",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L267-L302 | train |
kwikteam/phy | phy/gui/gui.py | GUI.list_views | def list_views(self, name='', is_visible=True):
"""List all views which name start with a given string."""
children = self.findChildren(QWidget)
return [child.view for child in children
if isinstance(child, QDockWidget) and
child.view.name.startswith(name) and
(child.isVisible() if is_visible else True) and
child.width() >= 10 and
child.height() >= 10
] | python | def list_views(self, name='', is_visible=True):
"""List all views which name start with a given string."""
children = self.findChildren(QWidget)
return [child.view for child in children
if isinstance(child, QDockWidget) and
child.view.name.startswith(name) and
(child.isVisible() if is_visible else True) and
child.width() >= 10 and
child.height() >= 10
] | [
"def",
"list_views",
"(",
"self",
",",
"name",
"=",
"''",
",",
"is_visible",
"=",
"True",
")",
":",
"children",
"=",
"self",
".",
"findChildren",
"(",
"QWidget",
")",
"return",
"[",
"child",
".",
"view",
"for",
"child",
"in",
"children",
"if",
"isinstance",
"(",
"child",
",",
"QDockWidget",
")",
"and",
"child",
".",
"view",
".",
"name",
".",
"startswith",
"(",
"name",
")",
"and",
"(",
"child",
".",
"isVisible",
"(",
")",
"if",
"is_visible",
"else",
"True",
")",
"and",
"child",
".",
"width",
"(",
")",
">=",
"10",
"and",
"child",
".",
"height",
"(",
")",
">=",
"10",
"]"
]
| List all views which name start with a given string. | [
"List",
"all",
"views",
"which",
"name",
"start",
"with",
"a",
"given",
"string",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L304-L313 | train |
kwikteam/phy | phy/gui/gui.py | GUI.get_view | def get_view(self, name, is_visible=True):
"""Return a view from its name."""
views = self.list_views(name, is_visible=is_visible)
return views[0] if views else None | python | def get_view(self, name, is_visible=True):
"""Return a view from its name."""
views = self.list_views(name, is_visible=is_visible)
return views[0] if views else None | [
"def",
"get_view",
"(",
"self",
",",
"name",
",",
"is_visible",
"=",
"True",
")",
":",
"views",
"=",
"self",
".",
"list_views",
"(",
"name",
",",
"is_visible",
"=",
"is_visible",
")",
"return",
"views",
"[",
"0",
"]",
"if",
"views",
"else",
"None"
]
| Return a view from its name. | [
"Return",
"a",
"view",
"from",
"its",
"name",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L315-L318 | train |
kwikteam/phy | phy/gui/gui.py | GUI.view_count | def view_count(self):
"""Return the number of opened views."""
views = self.list_views()
counts = defaultdict(lambda: 0)
for view in views:
counts[view.name] += 1
return dict(counts) | python | def view_count(self):
"""Return the number of opened views."""
views = self.list_views()
counts = defaultdict(lambda: 0)
for view in views:
counts[view.name] += 1
return dict(counts) | [
"def",
"view_count",
"(",
"self",
")",
":",
"views",
"=",
"self",
".",
"list_views",
"(",
")",
"counts",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"for",
"view",
"in",
"views",
":",
"counts",
"[",
"view",
".",
"name",
"]",
"+=",
"1",
"return",
"dict",
"(",
"counts",
")"
]
| Return the number of opened views. | [
"Return",
"the",
"number",
"of",
"opened",
"views",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L320-L326 | train |
kwikteam/phy | phy/gui/gui.py | GUI.get_menu | def get_menu(self, name):
"""Return or create a menu."""
if name not in self._menus:
self._menus[name] = self.menuBar().addMenu(name)
return self._menus[name] | python | def get_menu(self, name):
"""Return or create a menu."""
if name not in self._menus:
self._menus[name] = self.menuBar().addMenu(name)
return self._menus[name] | [
"def",
"get_menu",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_menus",
":",
"self",
".",
"_menus",
"[",
"name",
"]",
"=",
"self",
".",
"menuBar",
"(",
")",
".",
"addMenu",
"(",
"name",
")",
"return",
"self",
".",
"_menus",
"[",
"name",
"]"
]
| Return or create a menu. | [
"Return",
"or",
"create",
"a",
"menu",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L331-L335 | train |
kwikteam/phy | phy/gui/gui.py | GUI.restore_geometry_state | def restore_geometry_state(self, gs):
"""Restore the position of the main window and the docks.
The gui widgets need to be recreated first.
This function can be called in `on_show()`.
"""
if not gs:
return
if gs.get('geometry', None):
self.restoreGeometry((gs['geometry']))
if gs.get('state', None):
self.restoreState((gs['state'])) | python | def restore_geometry_state(self, gs):
"""Restore the position of the main window and the docks.
The gui widgets need to be recreated first.
This function can be called in `on_show()`.
"""
if not gs:
return
if gs.get('geometry', None):
self.restoreGeometry((gs['geometry']))
if gs.get('state', None):
self.restoreState((gs['state'])) | [
"def",
"restore_geometry_state",
"(",
"self",
",",
"gs",
")",
":",
"if",
"not",
"gs",
":",
"return",
"if",
"gs",
".",
"get",
"(",
"'geometry'",
",",
"None",
")",
":",
"self",
".",
"restoreGeometry",
"(",
"(",
"gs",
"[",
"'geometry'",
"]",
")",
")",
"if",
"gs",
".",
"get",
"(",
"'state'",
",",
"None",
")",
":",
"self",
".",
"restoreState",
"(",
"(",
"gs",
"[",
"'state'",
"]",
")",
")"
]
| Restore the position of the main window and the docks.
The gui widgets need to be recreated first.
This function can be called in `on_show()`. | [
"Restore",
"the",
"position",
"of",
"the",
"main",
"window",
"and",
"the",
"docks",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L377-L390 | train |
kwikteam/phy | phy/gui/gui.py | GUIState.update_view_state | def update_view_state(self, view, state):
"""Update the state of a view."""
if view.name not in self:
self[view.name] = Bunch()
self[view.name].update(state) | python | def update_view_state(self, view, state):
"""Update the state of a view."""
if view.name not in self:
self[view.name] = Bunch()
self[view.name].update(state) | [
"def",
"update_view_state",
"(",
"self",
",",
"view",
",",
"state",
")",
":",
"if",
"view",
".",
"name",
"not",
"in",
"self",
":",
"self",
"[",
"view",
".",
"name",
"]",
"=",
"Bunch",
"(",
")",
"self",
"[",
"view",
".",
"name",
"]",
".",
"update",
"(",
"state",
")"
]
| Update the state of a view. | [
"Update",
"the",
"state",
"of",
"a",
"view",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L415-L419 | train |
kwikteam/phy | phy/gui/gui.py | GUIState.load | def load(self):
"""Load the state from the JSON file in the config dir."""
if not op.exists(self.path):
logger.debug("The GUI state file `%s` doesn't exist.", self.path)
# TODO: create the default state.
return
assert op.exists(self.path)
logger.debug("Load the GUI state from `%s`.", self.path)
self.update(_bunchify(_load_json(self.path))) | python | def load(self):
"""Load the state from the JSON file in the config dir."""
if not op.exists(self.path):
logger.debug("The GUI state file `%s` doesn't exist.", self.path)
# TODO: create the default state.
return
assert op.exists(self.path)
logger.debug("Load the GUI state from `%s`.", self.path)
self.update(_bunchify(_load_json(self.path))) | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"not",
"op",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"logger",
".",
"debug",
"(",
"\"The GUI state file `%s` doesn't exist.\"",
",",
"self",
".",
"path",
")",
"# TODO: create the default state.",
"return",
"assert",
"op",
".",
"exists",
"(",
"self",
".",
"path",
")",
"logger",
".",
"debug",
"(",
"\"Load the GUI state from `%s`.\"",
",",
"self",
".",
"path",
")",
"self",
".",
"update",
"(",
"_bunchify",
"(",
"_load_json",
"(",
"self",
".",
"path",
")",
")",
")"
]
| Load the state from the JSON file in the config dir. | [
"Load",
"the",
"state",
"from",
"the",
"JSON",
"file",
"in",
"the",
"config",
"dir",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L425-L433 | train |
kwikteam/phy | phy/gui/gui.py | GUIState.save | def save(self):
"""Save the state to the JSON file in the config dir."""
logger.debug("Save the GUI state to `%s`.", self.path)
_save_json(self.path, {k: v for k, v in self.items()
if k not in ('config_dir', 'name')}) | python | def save(self):
"""Save the state to the JSON file in the config dir."""
logger.debug("Save the GUI state to `%s`.", self.path)
_save_json(self.path, {k: v for k, v in self.items()
if k not in ('config_dir', 'name')}) | [
"def",
"save",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Save the GUI state to `%s`.\"",
",",
"self",
".",
"path",
")",
"_save_json",
"(",
"self",
".",
"path",
",",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"(",
"'config_dir'",
",",
"'name'",
")",
"}",
")"
]
| Save the state to the JSON file in the config dir. | [
"Save",
"the",
"state",
"to",
"the",
"JSON",
"file",
"in",
"the",
"config",
"dir",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/gui.py#L435-L439 | train |
kwikteam/phy | phy/io/context.py | Context.cache | def cache(self, f):
"""Cache a function using the context's cache directory."""
if self._memory is None: # pragma: no cover
logger.debug("Joblib is not installed: skipping cacheing.")
return f
assert f
# NOTE: discard self in instance methods.
if 'self' in inspect.getargspec(f).args:
ignore = ['self']
else:
ignore = None
disk_cached = self._memory.cache(f, ignore=ignore)
return disk_cached | python | def cache(self, f):
"""Cache a function using the context's cache directory."""
if self._memory is None: # pragma: no cover
logger.debug("Joblib is not installed: skipping cacheing.")
return f
assert f
# NOTE: discard self in instance methods.
if 'self' in inspect.getargspec(f).args:
ignore = ['self']
else:
ignore = None
disk_cached = self._memory.cache(f, ignore=ignore)
return disk_cached | [
"def",
"cache",
"(",
"self",
",",
"f",
")",
":",
"if",
"self",
".",
"_memory",
"is",
"None",
":",
"# pragma: no cover",
"logger",
".",
"debug",
"(",
"\"Joblib is not installed: skipping cacheing.\"",
")",
"return",
"f",
"assert",
"f",
"# NOTE: discard self in instance methods.",
"if",
"'self'",
"in",
"inspect",
".",
"getargspec",
"(",
"f",
")",
".",
"args",
":",
"ignore",
"=",
"[",
"'self'",
"]",
"else",
":",
"ignore",
"=",
"None",
"disk_cached",
"=",
"self",
".",
"_memory",
".",
"cache",
"(",
"f",
",",
"ignore",
"=",
"ignore",
")",
"return",
"disk_cached"
]
| Cache a function using the context's cache directory. | [
"Cache",
"a",
"function",
"using",
"the",
"context",
"s",
"cache",
"directory",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/context.py#L73-L85 | train |
kwikteam/phy | phy/io/context.py | Context.memcache | def memcache(self, f):
"""Cache a function in memory using an internal dictionary."""
name = _fullname(f)
cache = self.load_memcache(name)
@wraps(f)
def memcached(*args):
"""Cache the function in memory."""
# The arguments need to be hashable. Much faster than using hash().
h = args
out = cache.get(h, None)
if out is None:
out = f(*args)
cache[h] = out
return out
return memcached | python | def memcache(self, f):
"""Cache a function in memory using an internal dictionary."""
name = _fullname(f)
cache = self.load_memcache(name)
@wraps(f)
def memcached(*args):
"""Cache the function in memory."""
# The arguments need to be hashable. Much faster than using hash().
h = args
out = cache.get(h, None)
if out is None:
out = f(*args)
cache[h] = out
return out
return memcached | [
"def",
"memcache",
"(",
"self",
",",
"f",
")",
":",
"name",
"=",
"_fullname",
"(",
"f",
")",
"cache",
"=",
"self",
".",
"load_memcache",
"(",
"name",
")",
"@",
"wraps",
"(",
"f",
")",
"def",
"memcached",
"(",
"*",
"args",
")",
":",
"\"\"\"Cache the function in memory.\"\"\"",
"# The arguments need to be hashable. Much faster than using hash().",
"h",
"=",
"args",
"out",
"=",
"cache",
".",
"get",
"(",
"h",
",",
"None",
")",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"f",
"(",
"*",
"args",
")",
"cache",
"[",
"h",
"]",
"=",
"out",
"return",
"out",
"return",
"memcached"
]
| Cache a function in memory using an internal dictionary. | [
"Cache",
"a",
"function",
"in",
"memory",
"using",
"an",
"internal",
"dictionary",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/context.py#L106-L121 | train |
kwikteam/phy | phy/io/context.py | Context.save | def save(self, name, data, location='local', kind='json'):
"""Save a dictionary in a JSON file within the cache directory."""
file_ext = '.json' if kind == 'json' else '.pkl'
path = self._get_path(name, location, file_ext=file_ext)
_ensure_dir_exists(op.dirname(path))
logger.debug("Save data to `%s`.", path)
if kind == 'json':
_save_json(path, data)
else:
_save_pickle(path, data) | python | def save(self, name, data, location='local', kind='json'):
"""Save a dictionary in a JSON file within the cache directory."""
file_ext = '.json' if kind == 'json' else '.pkl'
path = self._get_path(name, location, file_ext=file_ext)
_ensure_dir_exists(op.dirname(path))
logger.debug("Save data to `%s`.", path)
if kind == 'json':
_save_json(path, data)
else:
_save_pickle(path, data) | [
"def",
"save",
"(",
"self",
",",
"name",
",",
"data",
",",
"location",
"=",
"'local'",
",",
"kind",
"=",
"'json'",
")",
":",
"file_ext",
"=",
"'.json'",
"if",
"kind",
"==",
"'json'",
"else",
"'.pkl'",
"path",
"=",
"self",
".",
"_get_path",
"(",
"name",
",",
"location",
",",
"file_ext",
"=",
"file_ext",
")",
"_ensure_dir_exists",
"(",
"op",
".",
"dirname",
"(",
"path",
")",
")",
"logger",
".",
"debug",
"(",
"\"Save data to `%s`.\"",
",",
"path",
")",
"if",
"kind",
"==",
"'json'",
":",
"_save_json",
"(",
"path",
",",
"data",
")",
"else",
":",
"_save_pickle",
"(",
"path",
",",
"data",
")"
]
| Save a dictionary in a JSON file within the cache directory. | [
"Save",
"a",
"dictionary",
"in",
"a",
"JSON",
"file",
"within",
"the",
"cache",
"directory",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/context.py#L129-L138 | train |
kwikteam/phy | phy/io/context.py | Context.load | def load(self, name, location='local'):
"""Load saved data from the cache directory."""
path = self._get_path(name, location, file_ext='.json')
if op.exists(path):
return _load_json(path)
path = self._get_path(name, location, file_ext='.pkl')
if op.exists(path):
return _load_pickle(path)
logger.debug("The file `%s` doesn't exist.", path)
return {} | python | def load(self, name, location='local'):
"""Load saved data from the cache directory."""
path = self._get_path(name, location, file_ext='.json')
if op.exists(path):
return _load_json(path)
path = self._get_path(name, location, file_ext='.pkl')
if op.exists(path):
return _load_pickle(path)
logger.debug("The file `%s` doesn't exist.", path)
return {} | [
"def",
"load",
"(",
"self",
",",
"name",
",",
"location",
"=",
"'local'",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"name",
",",
"location",
",",
"file_ext",
"=",
"'.json'",
")",
"if",
"op",
".",
"exists",
"(",
"path",
")",
":",
"return",
"_load_json",
"(",
"path",
")",
"path",
"=",
"self",
".",
"_get_path",
"(",
"name",
",",
"location",
",",
"file_ext",
"=",
"'.pkl'",
")",
"if",
"op",
".",
"exists",
"(",
"path",
")",
":",
"return",
"_load_pickle",
"(",
"path",
")",
"logger",
".",
"debug",
"(",
"\"The file `%s` doesn't exist.\"",
",",
"path",
")",
"return",
"{",
"}"
]
| Load saved data from the cache directory. | [
"Load",
"saved",
"data",
"from",
"the",
"cache",
"directory",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/context.py#L140-L149 | train |
kwikteam/phy | phy/utils/config.py | _ensure_dir_exists | def _ensure_dir_exists(path):
"""Ensure a directory exists."""
if not op.exists(path):
os.makedirs(path)
assert op.exists(path) and op.isdir(path) | python | def _ensure_dir_exists(path):
"""Ensure a directory exists."""
if not op.exists(path):
os.makedirs(path)
assert op.exists(path) and op.isdir(path) | [
"def",
"_ensure_dir_exists",
"(",
"path",
")",
":",
"if",
"not",
"op",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"assert",
"op",
".",
"exists",
"(",
"path",
")",
"and",
"op",
".",
"isdir",
"(",
"path",
")"
]
| Ensure a directory exists. | [
"Ensure",
"a",
"directory",
"exists",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/config.py#L32-L36 | train |
kwikteam/phy | phy/utils/config.py | load_config | def load_config(path=None):
"""Load a Python or JSON config file."""
if not path or not op.exists(path):
return Config()
path = op.realpath(path)
dirpath, filename = op.split(path)
file_ext = op.splitext(path)[1]
logger.debug("Load config file `%s`.", path)
if file_ext == '.py':
config = PyFileConfigLoader(filename, dirpath,
log=logger).load_config()
elif file_ext == '.json':
config = JSONFileConfigLoader(filename, dirpath,
log=logger).load_config()
return config | python | def load_config(path=None):
"""Load a Python or JSON config file."""
if not path or not op.exists(path):
return Config()
path = op.realpath(path)
dirpath, filename = op.split(path)
file_ext = op.splitext(path)[1]
logger.debug("Load config file `%s`.", path)
if file_ext == '.py':
config = PyFileConfigLoader(filename, dirpath,
log=logger).load_config()
elif file_ext == '.json':
config = JSONFileConfigLoader(filename, dirpath,
log=logger).load_config()
return config | [
"def",
"load_config",
"(",
"path",
"=",
"None",
")",
":",
"if",
"not",
"path",
"or",
"not",
"op",
".",
"exists",
"(",
"path",
")",
":",
"return",
"Config",
"(",
")",
"path",
"=",
"op",
".",
"realpath",
"(",
"path",
")",
"dirpath",
",",
"filename",
"=",
"op",
".",
"split",
"(",
"path",
")",
"file_ext",
"=",
"op",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"logger",
".",
"debug",
"(",
"\"Load config file `%s`.\"",
",",
"path",
")",
"if",
"file_ext",
"==",
"'.py'",
":",
"config",
"=",
"PyFileConfigLoader",
"(",
"filename",
",",
"dirpath",
",",
"log",
"=",
"logger",
")",
".",
"load_config",
"(",
")",
"elif",
"file_ext",
"==",
"'.json'",
":",
"config",
"=",
"JSONFileConfigLoader",
"(",
"filename",
",",
"dirpath",
",",
"log",
"=",
"logger",
")",
".",
"load_config",
"(",
")",
"return",
"config"
]
| Load a Python or JSON config file. | [
"Load",
"a",
"Python",
"or",
"JSON",
"config",
"file",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/config.py#L39-L53 | train |
kwikteam/phy | phy/utils/config.py | save_config | def save_config(path, config):
"""Save a config object to a JSON file."""
import json
config['version'] = 1
with open(path, 'w') as f:
json.dump(config, f) | python | def save_config(path, config):
"""Save a config object to a JSON file."""
import json
config['version'] = 1
with open(path, 'w') as f:
json.dump(config, f) | [
"def",
"save_config",
"(",
"path",
",",
"config",
")",
":",
"import",
"json",
"config",
"[",
"'version'",
"]",
"=",
"1",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"config",
",",
"f",
")"
]
| Save a config object to a JSON file. | [
"Save",
"a",
"config",
"object",
"to",
"a",
"JSON",
"file",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/utils/config.py#L94-L99 | train |
kwikteam/phy | phy/electrode/mea.py | _edges_to_adjacency_list | def _edges_to_adjacency_list(edges):
"""Convert a list of edges into an adjacency list."""
adj = {}
for i, j in edges:
if i in adj: # pragma: no cover
ni = adj[i]
else:
ni = adj[i] = set()
if j in adj:
nj = adj[j]
else:
nj = adj[j] = set()
ni.add(j)
nj.add(i)
return adj | python | def _edges_to_adjacency_list(edges):
"""Convert a list of edges into an adjacency list."""
adj = {}
for i, j in edges:
if i in adj: # pragma: no cover
ni = adj[i]
else:
ni = adj[i] = set()
if j in adj:
nj = adj[j]
else:
nj = adj[j] = set()
ni.add(j)
nj.add(i)
return adj | [
"def",
"_edges_to_adjacency_list",
"(",
"edges",
")",
":",
"adj",
"=",
"{",
"}",
"for",
"i",
",",
"j",
"in",
"edges",
":",
"if",
"i",
"in",
"adj",
":",
"# pragma: no cover",
"ni",
"=",
"adj",
"[",
"i",
"]",
"else",
":",
"ni",
"=",
"adj",
"[",
"i",
"]",
"=",
"set",
"(",
")",
"if",
"j",
"in",
"adj",
":",
"nj",
"=",
"adj",
"[",
"j",
"]",
"else",
":",
"nj",
"=",
"adj",
"[",
"j",
"]",
"=",
"set",
"(",
")",
"ni",
".",
"add",
"(",
"j",
")",
"nj",
".",
"add",
"(",
"i",
")",
"return",
"adj"
]
| Convert a list of edges into an adjacency list. | [
"Convert",
"a",
"list",
"of",
"edges",
"into",
"an",
"adjacency",
"list",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L24-L38 | train |
kwikteam/phy | phy/electrode/mea.py | _probe_positions | def _probe_positions(probe, group):
"""Return the positions of a probe channel group."""
positions = probe['channel_groups'][group]['geometry']
channels = _probe_channels(probe, group)
return np.array([positions[channel] for channel in channels]) | python | def _probe_positions(probe, group):
"""Return the positions of a probe channel group."""
positions = probe['channel_groups'][group]['geometry']
channels = _probe_channels(probe, group)
return np.array([positions[channel] for channel in channels]) | [
"def",
"_probe_positions",
"(",
"probe",
",",
"group",
")",
":",
"positions",
"=",
"probe",
"[",
"'channel_groups'",
"]",
"[",
"group",
"]",
"[",
"'geometry'",
"]",
"channels",
"=",
"_probe_channels",
"(",
"probe",
",",
"group",
")",
"return",
"np",
".",
"array",
"(",
"[",
"positions",
"[",
"channel",
"]",
"for",
"channel",
"in",
"channels",
"]",
")"
]
| Return the positions of a probe channel group. | [
"Return",
"the",
"positions",
"of",
"a",
"probe",
"channel",
"group",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L53-L57 | train |
kwikteam/phy | phy/electrode/mea.py | _probe_adjacency_list | def _probe_adjacency_list(probe):
"""Return an adjacency list of a whole probe."""
cgs = probe['channel_groups'].values()
graphs = [cg['graph'] for cg in cgs]
edges = list(itertools.chain(*graphs))
adjacency_list = _edges_to_adjacency_list(edges)
return adjacency_list | python | def _probe_adjacency_list(probe):
"""Return an adjacency list of a whole probe."""
cgs = probe['channel_groups'].values()
graphs = [cg['graph'] for cg in cgs]
edges = list(itertools.chain(*graphs))
adjacency_list = _edges_to_adjacency_list(edges)
return adjacency_list | [
"def",
"_probe_adjacency_list",
"(",
"probe",
")",
":",
"cgs",
"=",
"probe",
"[",
"'channel_groups'",
"]",
".",
"values",
"(",
")",
"graphs",
"=",
"[",
"cg",
"[",
"'graph'",
"]",
"for",
"cg",
"in",
"cgs",
"]",
"edges",
"=",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"graphs",
")",
")",
"adjacency_list",
"=",
"_edges_to_adjacency_list",
"(",
"edges",
")",
"return",
"adjacency_list"
]
| Return an adjacency list of a whole probe. | [
"Return",
"an",
"adjacency",
"list",
"of",
"a",
"whole",
"probe",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L69-L75 | train |
kwikteam/phy | phy/electrode/mea.py | load_probe | def load_probe(name):
"""Load one of the built-in probes."""
if op.exists(name):
# The argument can be either a path to a PRB file.
path = name
else:
# Or the name of a built-in probe.
curdir = op.realpath(op.dirname(__file__))
path = op.join(curdir, 'probes/{}.prb'.format(name))
if not op.exists(path):
raise IOError("The probe `{}` cannot be found.".format(name))
return MEA(probe=_read_python(path)) | python | def load_probe(name):
"""Load one of the built-in probes."""
if op.exists(name):
# The argument can be either a path to a PRB file.
path = name
else:
# Or the name of a built-in probe.
curdir = op.realpath(op.dirname(__file__))
path = op.join(curdir, 'probes/{}.prb'.format(name))
if not op.exists(path):
raise IOError("The probe `{}` cannot be found.".format(name))
return MEA(probe=_read_python(path)) | [
"def",
"load_probe",
"(",
"name",
")",
":",
"if",
"op",
".",
"exists",
"(",
"name",
")",
":",
"# The argument can be either a path to a PRB file.",
"path",
"=",
"name",
"else",
":",
"# Or the name of a built-in probe.",
"curdir",
"=",
"op",
".",
"realpath",
"(",
"op",
".",
"dirname",
"(",
"__file__",
")",
")",
"path",
"=",
"op",
".",
"join",
"(",
"curdir",
",",
"'probes/{}.prb'",
".",
"format",
"(",
"name",
")",
")",
"if",
"not",
"op",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"IOError",
"(",
"\"The probe `{}` cannot be found.\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"MEA",
"(",
"probe",
"=",
"_read_python",
"(",
"path",
")",
")"
]
| Load one of the built-in probes. | [
"Load",
"one",
"of",
"the",
"built",
"-",
"in",
"probes",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L84-L95 | train |
kwikteam/phy | phy/electrode/mea.py | list_probes | def list_probes():
"""Return the list of built-in probes."""
curdir = op.realpath(op.dirname(__file__))
return [op.splitext(fn)[0] for fn in os.listdir(op.join(curdir, 'probes'))
if fn.endswith('.prb')] | python | def list_probes():
"""Return the list of built-in probes."""
curdir = op.realpath(op.dirname(__file__))
return [op.splitext(fn)[0] for fn in os.listdir(op.join(curdir, 'probes'))
if fn.endswith('.prb')] | [
"def",
"list_probes",
"(",
")",
":",
"curdir",
"=",
"op",
".",
"realpath",
"(",
"op",
".",
"dirname",
"(",
"__file__",
")",
")",
"return",
"[",
"op",
".",
"splitext",
"(",
"fn",
")",
"[",
"0",
"]",
"for",
"fn",
"in",
"os",
".",
"listdir",
"(",
"op",
".",
"join",
"(",
"curdir",
",",
"'probes'",
")",
")",
"if",
"fn",
".",
"endswith",
"(",
"'.prb'",
")",
"]"
]
| Return the list of built-in probes. | [
"Return",
"the",
"list",
"of",
"built",
"-",
"in",
"probes",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L98-L102 | train |
kwikteam/phy | phy/electrode/mea.py | linear_positions | def linear_positions(n_channels):
"""Linear channel positions along the vertical axis."""
return np.c_[np.zeros(n_channels),
np.linspace(0., 1., n_channels)] | python | def linear_positions(n_channels):
"""Linear channel positions along the vertical axis."""
return np.c_[np.zeros(n_channels),
np.linspace(0., 1., n_channels)] | [
"def",
"linear_positions",
"(",
"n_channels",
")",
":",
"return",
"np",
".",
"c_",
"[",
"np",
".",
"zeros",
"(",
"n_channels",
")",
",",
"np",
".",
"linspace",
"(",
"0.",
",",
"1.",
",",
"n_channels",
")",
"]"
]
| Linear channel positions along the vertical axis. | [
"Linear",
"channel",
"positions",
"along",
"the",
"vertical",
"axis",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L182-L185 | train |
kwikteam/phy | phy/electrode/mea.py | staggered_positions | def staggered_positions(n_channels):
"""Generate channel positions for a staggered probe."""
i = np.arange(n_channels - 1)
x, y = (-1) ** i * (5 + i), 10 * (i + 1)
pos = np.flipud(np.r_[np.zeros((1, 2)), np.c_[x, y]])
return pos | python | def staggered_positions(n_channels):
"""Generate channel positions for a staggered probe."""
i = np.arange(n_channels - 1)
x, y = (-1) ** i * (5 + i), 10 * (i + 1)
pos = np.flipud(np.r_[np.zeros((1, 2)), np.c_[x, y]])
return pos | [
"def",
"staggered_positions",
"(",
"n_channels",
")",
":",
"i",
"=",
"np",
".",
"arange",
"(",
"n_channels",
"-",
"1",
")",
"x",
",",
"y",
"=",
"(",
"-",
"1",
")",
"**",
"i",
"*",
"(",
"5",
"+",
"i",
")",
",",
"10",
"*",
"(",
"i",
"+",
"1",
")",
"pos",
"=",
"np",
".",
"flipud",
"(",
"np",
".",
"r_",
"[",
"np",
".",
"zeros",
"(",
"(",
"1",
",",
"2",
")",
")",
",",
"np",
".",
"c_",
"[",
"x",
",",
"y",
"]",
"]",
")",
"return",
"pos"
]
| Generate channel positions for a staggered probe. | [
"Generate",
"channel",
"positions",
"for",
"a",
"staggered",
"probe",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L188-L193 | train |
kwikteam/phy | phy/electrode/mea.py | MEA.change_channel_group | def change_channel_group(self, group):
"""Change the current channel group."""
assert self._probe is not None
self._channels = _probe_channels(self._probe, group)
self._positions = _probe_positions(self._probe, group) | python | def change_channel_group(self, group):
"""Change the current channel group."""
assert self._probe is not None
self._channels = _probe_channels(self._probe, group)
self._positions = _probe_positions(self._probe, group) | [
"def",
"change_channel_group",
"(",
"self",
",",
"group",
")",
":",
"assert",
"self",
".",
"_probe",
"is",
"not",
"None",
"self",
".",
"_channels",
"=",
"_probe_channels",
"(",
"self",
".",
"_probe",
",",
"group",
")",
"self",
".",
"_positions",
"=",
"_probe_positions",
"(",
"self",
".",
"_probe",
",",
"group",
")"
]
| Change the current channel group. | [
"Change",
"the",
"current",
"channel",
"group",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L171-L175 | train |
kwikteam/phy | phy/gui/widgets.py | HTMLWidget.build | def build(self):
"""Build the full HTML source."""
if self.is_built(): # pragma: no cover
return
with _wait_signal(self.loadFinished, 20):
self.rebuild()
self._built = True | python | def build(self):
"""Build the full HTML source."""
if self.is_built(): # pragma: no cover
return
with _wait_signal(self.loadFinished, 20):
self.rebuild()
self._built = True | [
"def",
"build",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_built",
"(",
")",
":",
"# pragma: no cover",
"return",
"with",
"_wait_signal",
"(",
"self",
".",
"loadFinished",
",",
"20",
")",
":",
"self",
".",
"rebuild",
"(",
")",
"self",
".",
"_built",
"=",
"True"
]
| Build the full HTML source. | [
"Build",
"the",
"full",
"HTML",
"source",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L171-L177 | train |
kwikteam/phy | phy/gui/widgets.py | HTMLWidget.add_to_js | def add_to_js(self, name, var):
"""Add an object to Javascript."""
frame = self.page().mainFrame()
frame.addToJavaScriptWindowObject(name, var) | python | def add_to_js(self, name, var):
"""Add an object to Javascript."""
frame = self.page().mainFrame()
frame.addToJavaScriptWindowObject(name, var) | [
"def",
"add_to_js",
"(",
"self",
",",
"name",
",",
"var",
")",
":",
"frame",
"=",
"self",
".",
"page",
"(",
")",
".",
"mainFrame",
"(",
")",
"frame",
".",
"addToJavaScriptWindowObject",
"(",
"name",
",",
"var",
")"
]
| Add an object to Javascript. | [
"Add",
"an",
"object",
"to",
"Javascript",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L185-L188 | train |
kwikteam/phy | phy/gui/widgets.py | HTMLWidget.eval_js | def eval_js(self, expr):
"""Evaluate a Javascript expression."""
if not self.is_built():
self._pending_js_eval.append(expr)
return
logger.log(5, "Evaluate Javascript: `%s`.", expr)
out = self.page().mainFrame().evaluateJavaScript(expr)
return _to_py(out) | python | def eval_js(self, expr):
"""Evaluate a Javascript expression."""
if not self.is_built():
self._pending_js_eval.append(expr)
return
logger.log(5, "Evaluate Javascript: `%s`.", expr)
out = self.page().mainFrame().evaluateJavaScript(expr)
return _to_py(out) | [
"def",
"eval_js",
"(",
"self",
",",
"expr",
")",
":",
"if",
"not",
"self",
".",
"is_built",
"(",
")",
":",
"self",
".",
"_pending_js_eval",
".",
"append",
"(",
"expr",
")",
"return",
"logger",
".",
"log",
"(",
"5",
",",
"\"Evaluate Javascript: `%s`.\"",
",",
"expr",
")",
"out",
"=",
"self",
".",
"page",
"(",
")",
".",
"mainFrame",
"(",
")",
".",
"evaluateJavaScript",
"(",
"expr",
")",
"return",
"_to_py",
"(",
"out",
")"
]
| Evaluate a Javascript expression. | [
"Evaluate",
"a",
"Javascript",
"expression",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L190-L197 | train |
kwikteam/phy | phy/gui/widgets.py | Table.add_column | def add_column(self, func, name=None, show=True):
"""Add a column function which takes an id as argument and
returns a value."""
assert func
name = name or func.__name__
if name == '<lambda>':
raise ValueError("Please provide a valid name for " + name)
d = {'func': func,
'show': show,
}
self._columns[name] = d
# Update the headers in the widget.
data = _create_json_dict(cols=self.column_names,
)
self.eval_js('table.setHeaders({});'.format(data))
return func | python | def add_column(self, func, name=None, show=True):
"""Add a column function which takes an id as argument and
returns a value."""
assert func
name = name or func.__name__
if name == '<lambda>':
raise ValueError("Please provide a valid name for " + name)
d = {'func': func,
'show': show,
}
self._columns[name] = d
# Update the headers in the widget.
data = _create_json_dict(cols=self.column_names,
)
self.eval_js('table.setHeaders({});'.format(data))
return func | [
"def",
"add_column",
"(",
"self",
",",
"func",
",",
"name",
"=",
"None",
",",
"show",
"=",
"True",
")",
":",
"assert",
"func",
"name",
"=",
"name",
"or",
"func",
".",
"__name__",
"if",
"name",
"==",
"'<lambda>'",
":",
"raise",
"ValueError",
"(",
"\"Please provide a valid name for \"",
"+",
"name",
")",
"d",
"=",
"{",
"'func'",
":",
"func",
",",
"'show'",
":",
"show",
",",
"}",
"self",
".",
"_columns",
"[",
"name",
"]",
"=",
"d",
"# Update the headers in the widget.",
"data",
"=",
"_create_json_dict",
"(",
"cols",
"=",
"self",
".",
"column_names",
",",
")",
"self",
".",
"eval_js",
"(",
"'table.setHeaders({});'",
".",
"format",
"(",
"data",
")",
")",
"return",
"func"
]
| Add a column function which takes an id as argument and
returns a value. | [
"Add",
"a",
"column",
"function",
"which",
"takes",
"an",
"id",
"as",
"argument",
"and",
"returns",
"a",
"value",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L252-L269 | train |
kwikteam/phy | phy/gui/widgets.py | Table.column_names | def column_names(self):
"""List of column names."""
return [name for (name, d) in self._columns.items()
if d.get('show', True)] | python | def column_names(self):
"""List of column names."""
return [name for (name, d) in self._columns.items()
if d.get('show', True)] | [
"def",
"column_names",
"(",
"self",
")",
":",
"return",
"[",
"name",
"for",
"(",
"name",
",",
"d",
")",
"in",
"self",
".",
"_columns",
".",
"items",
"(",
")",
"if",
"d",
".",
"get",
"(",
"'show'",
",",
"True",
")",
"]"
]
| List of column names. | [
"List",
"of",
"column",
"names",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L272-L275 | train |
kwikteam/phy | phy/gui/widgets.py | Table._get_row | def _get_row(self, id):
"""Create a row dictionary for a given object id."""
return {name: d['func'](id) for (name, d) in self._columns.items()} | python | def _get_row(self, id):
"""Create a row dictionary for a given object id."""
return {name: d['func'](id) for (name, d) in self._columns.items()} | [
"def",
"_get_row",
"(",
"self",
",",
"id",
")",
":",
"return",
"{",
"name",
":",
"d",
"[",
"'func'",
"]",
"(",
"id",
")",
"for",
"(",
"name",
",",
"d",
")",
"in",
"self",
".",
"_columns",
".",
"items",
"(",
")",
"}"
]
| Create a row dictionary for a given object id. | [
"Create",
"a",
"row",
"dictionary",
"for",
"a",
"given",
"object",
"id",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L277-L279 | train |
kwikteam/phy | phy/gui/widgets.py | Table.set_rows | def set_rows(self, ids):
"""Set the rows of the table."""
# NOTE: make sure we have integers and not np.generic objects.
assert all(isinstance(i, int) for i in ids)
# Determine the sort column and dir to set after the rows.
sort_col, sort_dir = self.current_sort
default_sort_col, default_sort_dir = self.default_sort
sort_col = sort_col or default_sort_col
sort_dir = sort_dir or default_sort_dir or 'desc'
# Set the rows.
logger.log(5, "Set %d rows in the table.", len(ids))
items = [self._get_row(id) for id in ids]
# Sort the rows before passing them to the widget.
# if sort_col:
# items = sorted(items, key=itemgetter(sort_col),
# reverse=(sort_dir == 'desc'))
data = _create_json_dict(items=items,
cols=self.column_names,
)
self.eval_js('table.setData({});'.format(data))
# Sort.
if sort_col:
self.sort_by(sort_col, sort_dir) | python | def set_rows(self, ids):
"""Set the rows of the table."""
# NOTE: make sure we have integers and not np.generic objects.
assert all(isinstance(i, int) for i in ids)
# Determine the sort column and dir to set after the rows.
sort_col, sort_dir = self.current_sort
default_sort_col, default_sort_dir = self.default_sort
sort_col = sort_col or default_sort_col
sort_dir = sort_dir or default_sort_dir or 'desc'
# Set the rows.
logger.log(5, "Set %d rows in the table.", len(ids))
items = [self._get_row(id) for id in ids]
# Sort the rows before passing them to the widget.
# if sort_col:
# items = sorted(items, key=itemgetter(sort_col),
# reverse=(sort_dir == 'desc'))
data = _create_json_dict(items=items,
cols=self.column_names,
)
self.eval_js('table.setData({});'.format(data))
# Sort.
if sort_col:
self.sort_by(sort_col, sort_dir) | [
"def",
"set_rows",
"(",
"self",
",",
"ids",
")",
":",
"# NOTE: make sure we have integers and not np.generic objects.",
"assert",
"all",
"(",
"isinstance",
"(",
"i",
",",
"int",
")",
"for",
"i",
"in",
"ids",
")",
"# Determine the sort column and dir to set after the rows.",
"sort_col",
",",
"sort_dir",
"=",
"self",
".",
"current_sort",
"default_sort_col",
",",
"default_sort_dir",
"=",
"self",
".",
"default_sort",
"sort_col",
"=",
"sort_col",
"or",
"default_sort_col",
"sort_dir",
"=",
"sort_dir",
"or",
"default_sort_dir",
"or",
"'desc'",
"# Set the rows.",
"logger",
".",
"log",
"(",
"5",
",",
"\"Set %d rows in the table.\"",
",",
"len",
"(",
"ids",
")",
")",
"items",
"=",
"[",
"self",
".",
"_get_row",
"(",
"id",
")",
"for",
"id",
"in",
"ids",
"]",
"# Sort the rows before passing them to the widget.",
"# if sort_col:",
"# items = sorted(items, key=itemgetter(sort_col),",
"# reverse=(sort_dir == 'desc'))",
"data",
"=",
"_create_json_dict",
"(",
"items",
"=",
"items",
",",
"cols",
"=",
"self",
".",
"column_names",
",",
")",
"self",
".",
"eval_js",
"(",
"'table.setData({});'",
".",
"format",
"(",
"data",
")",
")",
"# Sort.",
"if",
"sort_col",
":",
"self",
".",
"sort_by",
"(",
"sort_col",
",",
"sort_dir",
")"
]
| Set the rows of the table. | [
"Set",
"the",
"rows",
"of",
"the",
"table",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L281-L307 | train |
kwikteam/phy | phy/gui/widgets.py | Table.sort_by | def sort_by(self, name, sort_dir='asc'):
"""Sort by a given variable."""
logger.log(5, "Sort by `%s` %s.", name, sort_dir)
self.eval_js('table.sortBy("{}", "{}");'.format(name, sort_dir)) | python | def sort_by(self, name, sort_dir='asc'):
"""Sort by a given variable."""
logger.log(5, "Sort by `%s` %s.", name, sort_dir)
self.eval_js('table.sortBy("{}", "{}");'.format(name, sort_dir)) | [
"def",
"sort_by",
"(",
"self",
",",
"name",
",",
"sort_dir",
"=",
"'asc'",
")",
":",
"logger",
".",
"log",
"(",
"5",
",",
"\"Sort by `%s` %s.\"",
",",
"name",
",",
"sort_dir",
")",
"self",
".",
"eval_js",
"(",
"'table.sortBy(\"{}\", \"{}\");'",
".",
"format",
"(",
"name",
",",
"sort_dir",
")",
")"
]
| Sort by a given variable. | [
"Sort",
"by",
"a",
"given",
"variable",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L309-L312 | train |
kwikteam/phy | phy/gui/widgets.py | Table.select | def select(self, ids, do_emit=True, **kwargs):
"""Select some rows in the table.
By default, the `select` event is raised, unless `do_emit=False`.
"""
# Select the rows without emiting the event.
self.eval_js('table.select({}, false);'.format(dumps(ids)))
if do_emit:
# Emit the event manually if needed.
self.emit('select', ids, **kwargs) | python | def select(self, ids, do_emit=True, **kwargs):
"""Select some rows in the table.
By default, the `select` event is raised, unless `do_emit=False`.
"""
# Select the rows without emiting the event.
self.eval_js('table.select({}, false);'.format(dumps(ids)))
if do_emit:
# Emit the event manually if needed.
self.emit('select', ids, **kwargs) | [
"def",
"select",
"(",
"self",
",",
"ids",
",",
"do_emit",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Select the rows without emiting the event.",
"self",
".",
"eval_js",
"(",
"'table.select({}, false);'",
".",
"format",
"(",
"dumps",
"(",
"ids",
")",
")",
")",
"if",
"do_emit",
":",
"# Emit the event manually if needed.",
"self",
".",
"emit",
"(",
"'select'",
",",
"ids",
",",
"*",
"*",
"kwargs",
")"
]
| Select some rows in the table.
By default, the `select` event is raised, unless `do_emit=False`. | [
"Select",
"some",
"rows",
"in",
"the",
"table",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/widgets.py#L332-L342 | train |
kwikteam/phy | phy/cluster/views/trace.py | TraceView.set_interval | def set_interval(self, interval=None, change_status=True,
force_update=False):
"""Display the traces and spikes in a given interval."""
if interval is None:
interval = self._interval
interval = self._restrict_interval(interval)
if not force_update and interval == self._interval:
return
self._interval = interval
start, end = interval
self.clear()
# Set the status message.
if change_status:
self.set_status('Interval: {:.3f} s - {:.3f} s'.format(start, end))
# Load the traces.
traces = self.traces(interval)
# Find the data bounds.
ymin, ymax = traces.data.min(), traces.data.max()
data_bounds = (start, ymin, end, ymax)
# Used for spike click.
self._data_bounds = data_bounds
self._waveform_times = []
# Plot the traces.
self._plot_traces(traces.data,
color=traces.get('color', None),
data_bounds=data_bounds,
)
# Plot the spikes.
waveforms = traces.waveforms
assert isinstance(waveforms, list)
for w in waveforms:
self._plot_waveforms(waveforms=w.data,
color=w.color,
channel_ids=w.get('channel_ids', None),
start_time=w.start_time,
data_bounds=data_bounds,
)
self._waveform_times.append((w.start_time,
w.spike_id,
w.spike_cluster,
w.get('channel_ids', None),
))
# Plot the labels.
if self.do_show_labels:
self._plot_labels(traces.data, data_bounds=data_bounds)
self.build()
self.update() | python | def set_interval(self, interval=None, change_status=True,
force_update=False):
"""Display the traces and spikes in a given interval."""
if interval is None:
interval = self._interval
interval = self._restrict_interval(interval)
if not force_update and interval == self._interval:
return
self._interval = interval
start, end = interval
self.clear()
# Set the status message.
if change_status:
self.set_status('Interval: {:.3f} s - {:.3f} s'.format(start, end))
# Load the traces.
traces = self.traces(interval)
# Find the data bounds.
ymin, ymax = traces.data.min(), traces.data.max()
data_bounds = (start, ymin, end, ymax)
# Used for spike click.
self._data_bounds = data_bounds
self._waveform_times = []
# Plot the traces.
self._plot_traces(traces.data,
color=traces.get('color', None),
data_bounds=data_bounds,
)
# Plot the spikes.
waveforms = traces.waveforms
assert isinstance(waveforms, list)
for w in waveforms:
self._plot_waveforms(waveforms=w.data,
color=w.color,
channel_ids=w.get('channel_ids', None),
start_time=w.start_time,
data_bounds=data_bounds,
)
self._waveform_times.append((w.start_time,
w.spike_id,
w.spike_cluster,
w.get('channel_ids', None),
))
# Plot the labels.
if self.do_show_labels:
self._plot_labels(traces.data, data_bounds=data_bounds)
self.build()
self.update() | [
"def",
"set_interval",
"(",
"self",
",",
"interval",
"=",
"None",
",",
"change_status",
"=",
"True",
",",
"force_update",
"=",
"False",
")",
":",
"if",
"interval",
"is",
"None",
":",
"interval",
"=",
"self",
".",
"_interval",
"interval",
"=",
"self",
".",
"_restrict_interval",
"(",
"interval",
")",
"if",
"not",
"force_update",
"and",
"interval",
"==",
"self",
".",
"_interval",
":",
"return",
"self",
".",
"_interval",
"=",
"interval",
"start",
",",
"end",
"=",
"interval",
"self",
".",
"clear",
"(",
")",
"# Set the status message.",
"if",
"change_status",
":",
"self",
".",
"set_status",
"(",
"'Interval: {:.3f} s - {:.3f} s'",
".",
"format",
"(",
"start",
",",
"end",
")",
")",
"# Load the traces.",
"traces",
"=",
"self",
".",
"traces",
"(",
"interval",
")",
"# Find the data bounds.",
"ymin",
",",
"ymax",
"=",
"traces",
".",
"data",
".",
"min",
"(",
")",
",",
"traces",
".",
"data",
".",
"max",
"(",
")",
"data_bounds",
"=",
"(",
"start",
",",
"ymin",
",",
"end",
",",
"ymax",
")",
"# Used for spike click.",
"self",
".",
"_data_bounds",
"=",
"data_bounds",
"self",
".",
"_waveform_times",
"=",
"[",
"]",
"# Plot the traces.",
"self",
".",
"_plot_traces",
"(",
"traces",
".",
"data",
",",
"color",
"=",
"traces",
".",
"get",
"(",
"'color'",
",",
"None",
")",
",",
"data_bounds",
"=",
"data_bounds",
",",
")",
"# Plot the spikes.",
"waveforms",
"=",
"traces",
".",
"waveforms",
"assert",
"isinstance",
"(",
"waveforms",
",",
"list",
")",
"for",
"w",
"in",
"waveforms",
":",
"self",
".",
"_plot_waveforms",
"(",
"waveforms",
"=",
"w",
".",
"data",
",",
"color",
"=",
"w",
".",
"color",
",",
"channel_ids",
"=",
"w",
".",
"get",
"(",
"'channel_ids'",
",",
"None",
")",
",",
"start_time",
"=",
"w",
".",
"start_time",
",",
"data_bounds",
"=",
"data_bounds",
",",
")",
"self",
".",
"_waveform_times",
".",
"append",
"(",
"(",
"w",
".",
"start_time",
",",
"w",
".",
"spike_id",
",",
"w",
".",
"spike_cluster",
",",
"w",
".",
"get",
"(",
"'channel_ids'",
",",
"None",
")",
",",
")",
")",
"# Plot the labels.",
"if",
"self",
".",
"do_show_labels",
":",
"self",
".",
"_plot_labels",
"(",
"traces",
".",
"data",
",",
"data_bounds",
"=",
"data_bounds",
")",
"self",
".",
"build",
"(",
")",
"self",
".",
"update",
"(",
")"
]
| Display the traces and spikes in a given interval. | [
"Display",
"the",
"traces",
"and",
"spikes",
"in",
"a",
"given",
"interval",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L246-L300 | train |
kwikteam/phy | phy/cluster/views/trace.py | TraceView.half_duration | def half_duration(self):
"""Half of the duration of the current interval."""
if self._interval is not None:
a, b = self._interval
return (b - a) * .5
else:
return self.interval_duration * .5 | python | def half_duration(self):
"""Half of the duration of the current interval."""
if self._interval is not None:
a, b = self._interval
return (b - a) * .5
else:
return self.interval_duration * .5 | [
"def",
"half_duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"_interval",
"is",
"not",
"None",
":",
"a",
",",
"b",
"=",
"self",
".",
"_interval",
"return",
"(",
"b",
"-",
"a",
")",
"*",
".5",
"else",
":",
"return",
"self",
".",
"interval_duration",
"*",
".5"
]
| Half of the duration of the current interval. | [
"Half",
"of",
"the",
"duration",
"of",
"the",
"current",
"interval",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L384-L390 | train |
kwikteam/phy | phy/cluster/views/trace.py | TraceView.go_right | def go_right(self):
"""Go to right."""
start, end = self._interval
delay = (end - start) * .2
self.shift(delay) | python | def go_right(self):
"""Go to right."""
start, end = self._interval
delay = (end - start) * .2
self.shift(delay) | [
"def",
"go_right",
"(",
"self",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"_interval",
"delay",
"=",
"(",
"end",
"-",
"start",
")",
"*",
".2",
"self",
".",
"shift",
"(",
"delay",
")"
]
| Go to right. | [
"Go",
"to",
"right",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L401-L405 | train |
kwikteam/phy | phy/cluster/views/trace.py | TraceView.go_left | def go_left(self):
"""Go to left."""
start, end = self._interval
delay = (end - start) * .2
self.shift(-delay) | python | def go_left(self):
"""Go to left."""
start, end = self._interval
delay = (end - start) * .2
self.shift(-delay) | [
"def",
"go_left",
"(",
"self",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"_interval",
"delay",
"=",
"(",
"end",
"-",
"start",
")",
"*",
".2",
"self",
".",
"shift",
"(",
"-",
"delay",
")"
]
| Go to left. | [
"Go",
"to",
"left",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L407-L411 | train |
kwikteam/phy | phy/cluster/views/trace.py | TraceView.widen | def widen(self):
"""Increase the interval size."""
t, h = self.time, self.half_duration
h *= self.scaling_coeff_x
self.set_interval((t - h, t + h)) | python | def widen(self):
"""Increase the interval size."""
t, h = self.time, self.half_duration
h *= self.scaling_coeff_x
self.set_interval((t - h, t + h)) | [
"def",
"widen",
"(",
"self",
")",
":",
"t",
",",
"h",
"=",
"self",
".",
"time",
",",
"self",
".",
"half_duration",
"h",
"*=",
"self",
".",
"scaling_coeff_x",
"self",
".",
"set_interval",
"(",
"(",
"t",
"-",
"h",
",",
"t",
"+",
"h",
")",
")"
]
| Increase the interval size. | [
"Increase",
"the",
"interval",
"size",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L413-L417 | train |
kwikteam/phy | phy/cluster/views/trace.py | TraceView.narrow | def narrow(self):
"""Decrease the interval size."""
t, h = self.time, self.half_duration
h /= self.scaling_coeff_x
self.set_interval((t - h, t + h)) | python | def narrow(self):
"""Decrease the interval size."""
t, h = self.time, self.half_duration
h /= self.scaling_coeff_x
self.set_interval((t - h, t + h)) | [
"def",
"narrow",
"(",
"self",
")",
":",
"t",
",",
"h",
"=",
"self",
".",
"time",
",",
"self",
".",
"half_duration",
"h",
"/=",
"self",
".",
"scaling_coeff_x",
"self",
".",
"set_interval",
"(",
"(",
"t",
"-",
"h",
",",
"t",
"+",
"h",
")",
")"
]
| Decrease the interval size. | [
"Decrease",
"the",
"interval",
"size",
"."
]
| 7e9313dc364304b7d2bd03b92938347343703003 | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/trace.py#L419-L423 | train |
robmarkcole/HASS-data-detective | detective/auth.py | auth_from_hass_config | def auth_from_hass_config(path=None, **kwargs):
"""Initialize auth from HASS config."""
if path is None:
path = config.find_hass_config()
return Auth(os.path.join(path, ".storage/auth"), **kwargs) | python | def auth_from_hass_config(path=None, **kwargs):
"""Initialize auth from HASS config."""
if path is None:
path = config.find_hass_config()
return Auth(os.path.join(path, ".storage/auth"), **kwargs) | [
"def",
"auth_from_hass_config",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"config",
".",
"find_hass_config",
"(",
")",
"return",
"Auth",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\".storage/auth\"",
")",
",",
"*",
"*",
"kwargs",
")"
]
| Initialize auth from HASS config. | [
"Initialize",
"auth",
"from",
"HASS",
"config",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/auth.py#L8-L13 | train |
robmarkcole/HASS-data-detective | detective/auth.py | Auth.user_name | def user_name(self, user_id):
"""Return name for user."""
user = self.users.get(user_id)
if user is None:
return "Unknown user ({})".format(user_id)
return user["name"] | python | def user_name(self, user_id):
"""Return name for user."""
user = self.users.get(user_id)
if user is None:
return "Unknown user ({})".format(user_id)
return user["name"] | [
"def",
"user_name",
"(",
"self",
",",
"user_id",
")",
":",
"user",
"=",
"self",
".",
"users",
".",
"get",
"(",
"user_id",
")",
"if",
"user",
"is",
"None",
":",
"return",
"\"Unknown user ({})\"",
".",
"format",
"(",
"user_id",
")",
"return",
"user",
"[",
"\"name\"",
"]"
]
| Return name for user. | [
"Return",
"name",
"for",
"user",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/auth.py#L35-L42 | train |
robmarkcole/HASS-data-detective | detective/config.py | default_hass_config_dir | def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant") | python | def default_hass_config_dir():
"""Put together the default configuration directory based on the OS."""
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant") | [
"def",
"default_hass_config_dir",
"(",
")",
":",
"data_dir",
"=",
"os",
".",
"getenv",
"(",
"\"APPDATA\"",
")",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
"else",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"\".homeassistant\"",
")"
]
| Put together the default configuration directory based on the OS. | [
"Put",
"together",
"the",
"default",
"configuration",
"directory",
"based",
"on",
"the",
"OS",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L10-L13 | train |
robmarkcole/HASS-data-detective | detective/config.py | find_hass_config | def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
) | python | def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
"config. Please pass it in."
) | [
"def",
"find_hass_config",
"(",
")",
":",
"if",
"\"HASSIO_TOKEN\"",
"in",
"os",
".",
"environ",
":",
"return",
"\"/config\"",
"config_dir",
"=",
"default_hass_config_dir",
"(",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"config_dir",
")",
":",
"return",
"config_dir",
"raise",
"ValueError",
"(",
"\"Unable to automatically find the location of Home Assistant \"",
"\"config. Please pass it in.\"",
")"
]
| Try to find HASS config. | [
"Try",
"to",
"find",
"HASS",
"config",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L16-L29 | train |
robmarkcole/HASS-data-detective | detective/config.py | _secret_yaml | def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None | python | def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundError:
raise ValueError("Secrets file {} not found".format(fname)) from None
try:
return secrets[node.value]
except KeyError:
raise ValueError("Secret {} not found".format(node.value)) from None | [
"def",
"_secret_yaml",
"(",
"loader",
",",
"node",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"loader",
".",
"name",
")",
",",
"\"secrets.yaml\"",
")",
"try",
":",
"with",
"open",
"(",
"fname",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"secret_file",
":",
"secrets",
"=",
"YAML",
"(",
"typ",
"=",
"\"safe\"",
")",
".",
"load",
"(",
"secret_file",
")",
"except",
"FileNotFoundError",
":",
"raise",
"ValueError",
"(",
"\"Secrets file {} not found\"",
".",
"format",
"(",
"fname",
")",
")",
"from",
"None",
"try",
":",
"return",
"secrets",
"[",
"node",
".",
"value",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Secret {} not found\"",
".",
"format",
"(",
"node",
".",
"value",
")",
")",
"from",
"None"
]
| Load secrets and embed it into the configuration YAML. | [
"Load",
"secrets",
"and",
"embed",
"it",
"into",
"the",
"configuration",
"YAML",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L36-L49 | train |
robmarkcole/HASS-data-detective | detective/config.py | _include_yaml | def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value)) | python | def _include_yaml(loader, node):
"""Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
return load_yaml(os.path.join(os.path.dirname(loader.name), node.value)) | [
"def",
"_include_yaml",
"(",
"loader",
",",
"node",
")",
":",
"return",
"load_yaml",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"loader",
".",
"name",
")",
",",
"node",
".",
"value",
")",
")"
]
| Load another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml | [
"Load",
"another",
"YAML",
"file",
"and",
"embeds",
"it",
"using",
"the",
"!include",
"tag",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L52-L58 | train |
robmarkcole/HASS-data-detective | detective/config.py | _stub_tag | def _stub_tag(constructor, node):
"""Stub a constructor with a dictionary."""
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {} | python | def _stub_tag(constructor, node):
"""Stub a constructor with a dictionary."""
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {} | [
"def",
"_stub_tag",
"(",
"constructor",
",",
"node",
")",
":",
"seen",
"=",
"getattr",
"(",
"constructor",
",",
"\"_stub_seen\"",
",",
"None",
")",
"if",
"seen",
"is",
"None",
":",
"seen",
"=",
"constructor",
".",
"_stub_seen",
"=",
"set",
"(",
")",
"if",
"node",
".",
"tag",
"not",
"in",
"seen",
":",
"print",
"(",
"\"YAML tag {} is not supported\"",
".",
"format",
"(",
"node",
".",
"tag",
")",
")",
"seen",
".",
"add",
"(",
"node",
".",
"tag",
")",
"return",
"{",
"}"
]
| Stub a constructor with a dictionary. | [
"Stub",
"a",
"constructor",
"with",
"a",
"dictionary",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L61-L72 | train |
robmarkcole/HASS-data-detective | detective/config.py | load_yaml | def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {} | python | def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {} | [
"def",
"load_yaml",
"(",
"fname",
")",
":",
"yaml",
"=",
"YAML",
"(",
"typ",
"=",
"\"safe\"",
")",
"# Compat with HASS",
"yaml",
".",
"allow_duplicate_keys",
"=",
"True",
"# Stub HASS constructors",
"HassSafeConstructor",
".",
"name",
"=",
"fname",
"yaml",
".",
"Constructor",
"=",
"HassSafeConstructor",
"with",
"open",
"(",
"fname",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"conf_file",
":",
"# If configuration file is empty YAML returns None",
"# We convert that to an empty dict",
"return",
"yaml",
".",
"load",
"(",
"conf_file",
")",
"or",
"{",
"}"
]
| Load a YAML file. | [
"Load",
"a",
"YAML",
"file",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L89-L101 | train |
robmarkcole/HASS-data-detective | detective/config.py | db_url_from_hass_config | def db_url_from_hass_config(path):
"""Find the recorder database url from a HASS config dir."""
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url | python | def db_url_from_hass_config(path):
"""Find the recorder database url from a HASS config dir."""
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url | [
"def",
"db_url_from_hass_config",
"(",
"path",
")",
":",
"config",
"=",
"load_hass_config",
"(",
"path",
")",
"default_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"home-assistant_v2.db\"",
")",
"default_url",
"=",
"\"sqlite:///{}\"",
".",
"format",
"(",
"default_path",
")",
"recorder",
"=",
"config",
".",
"get",
"(",
"\"recorder\"",
")",
"if",
"recorder",
":",
"db_url",
"=",
"recorder",
".",
"get",
"(",
"\"db_url\"",
")",
"if",
"db_url",
"is",
"not",
"None",
":",
"return",
"db_url",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"default_path",
")",
":",
"raise",
"ValueError",
"(",
"\"Unable to determine DB url from hass config at {}\"",
".",
"format",
"(",
"path",
")",
")",
"return",
"default_url"
]
| Find the recorder database url from a HASS config dir. | [
"Find",
"the",
"recorder",
"database",
"url",
"from",
"a",
"HASS",
"config",
"dir",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L104-L122 | train |
robmarkcole/HASS-data-detective | detective/time.py | localize | def localize(dt):
"""Localize a datetime object to local time."""
if dt.tzinfo is UTC:
return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)
# No TZ info so not going to assume anything, return as-is.
return dt | python | def localize(dt):
"""Localize a datetime object to local time."""
if dt.tzinfo is UTC:
return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)
# No TZ info so not going to assume anything, return as-is.
return dt | [
"def",
"localize",
"(",
"dt",
")",
":",
"if",
"dt",
".",
"tzinfo",
"is",
"UTC",
":",
"return",
"(",
"dt",
"+",
"LOCAL_UTC_OFFSET",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"# No TZ info so not going to assume anything, return as-is.",
"return",
"dt"
]
| Localize a datetime object to local time. | [
"Localize",
"a",
"datetime",
"object",
"to",
"local",
"time",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/time.py#L19-L24 | train |
robmarkcole/HASS-data-detective | detective/time.py | sqlalch_datetime | def sqlalch_datetime(dt):
"""Convert a SQLAlchemy datetime string to a datetime object."""
if isinstance(dt, str):
return datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo=UTC)
if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None:
return dt.astimezone(UTC)
return dt.replace(tzinfo=UTC) | python | def sqlalch_datetime(dt):
"""Convert a SQLAlchemy datetime string to a datetime object."""
if isinstance(dt, str):
return datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo=UTC)
if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None:
return dt.astimezone(UTC)
return dt.replace(tzinfo=UTC) | [
"def",
"sqlalch_datetime",
"(",
"dt",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"str",
")",
":",
"return",
"datetime",
".",
"strptime",
"(",
"dt",
",",
"\"%Y-%m-%d %H:%M:%S.%f\"",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"UTC",
")",
"if",
"dt",
".",
"tzinfo",
"is",
"not",
"None",
"and",
"dt",
".",
"tzinfo",
".",
"utcoffset",
"(",
"dt",
")",
"is",
"not",
"None",
":",
"return",
"dt",
".",
"astimezone",
"(",
"UTC",
")",
"return",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"UTC",
")"
]
| Convert a SQLAlchemy datetime string to a datetime object. | [
"Convert",
"a",
"SQLAlchemy",
"datetime",
"string",
"to",
"a",
"datetime",
"object",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/time.py#L44-L50 | train |
robmarkcole/HASS-data-detective | detective/core.py | db_from_hass_config | def db_from_hass_config(path=None, **kwargs):
"""Initialize a database from HASS config."""
if path is None:
path = config.find_hass_config()
url = config.db_url_from_hass_config(path)
return HassDatabase(url, **kwargs) | python | def db_from_hass_config(path=None, **kwargs):
"""Initialize a database from HASS config."""
if path is None:
path = config.find_hass_config()
url = config.db_url_from_hass_config(path)
return HassDatabase(url, **kwargs) | [
"def",
"db_from_hass_config",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"config",
".",
"find_hass_config",
"(",
")",
"url",
"=",
"config",
".",
"db_url_from_hass_config",
"(",
"path",
")",
"return",
"HassDatabase",
"(",
"url",
",",
"*",
"*",
"kwargs",
")"
]
| Initialize a database from HASS config. | [
"Initialize",
"a",
"database",
"from",
"HASS",
"config",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L14-L20 | train |
robmarkcole/HASS-data-detective | detective/core.py | stripped_db_url | def stripped_db_url(url):
"""Return a version of the DB url with the password stripped out."""
parsed = urlparse(url)
if parsed.password is None:
return url
return parsed._replace(
netloc="{}:***@{}".format(parsed.username, parsed.hostname)
).geturl() | python | def stripped_db_url(url):
"""Return a version of the DB url with the password stripped out."""
parsed = urlparse(url)
if parsed.password is None:
return url
return parsed._replace(
netloc="{}:***@{}".format(parsed.username, parsed.hostname)
).geturl() | [
"def",
"stripped_db_url",
"(",
"url",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"if",
"parsed",
".",
"password",
"is",
"None",
":",
"return",
"url",
"return",
"parsed",
".",
"_replace",
"(",
"netloc",
"=",
"\"{}:***@{}\"",
".",
"format",
"(",
"parsed",
".",
"username",
",",
"parsed",
".",
"hostname",
")",
")",
".",
"geturl",
"(",
")"
]
| Return a version of the DB url with the password stripped out. | [
"Return",
"a",
"version",
"of",
"the",
"DB",
"url",
"with",
"the",
"password",
"stripped",
"out",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L27-L36 | train |
robmarkcole/HASS-data-detective | detective/core.py | HassDatabase.perform_query | def perform_query(self, query, **params):
"""Perform a query, where query is a string."""
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise | python | def perform_query(self, query, **params):
"""Perform a query, where query is a string."""
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise | [
"def",
"perform_query",
"(",
"self",
",",
"query",
",",
"*",
"*",
"params",
")",
":",
"try",
":",
"return",
"self",
".",
"engine",
".",
"execute",
"(",
"query",
",",
"params",
")",
"except",
":",
"print",
"(",
"\"Error with query: {}\"",
".",
"format",
"(",
"query",
")",
")",
"raise"
]
| Perform a query, where query is a string. | [
"Perform",
"a",
"query",
"where",
"query",
"is",
"a",
"string",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L74-L80 | train |
robmarkcole/HASS-data-detective | detective/core.py | HassDatabase.fetch_entities | def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
entities = {}
domains = set()
for [entity] in response:
domain = entity.split(".")[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities))) | python | def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
entities = {}
domains = set()
for [entity] in response:
domain = entity.split(".")[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities))) | [
"def",
"fetch_entities",
"(",
"self",
")",
":",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT entity_id\n FROM states\n GROUP BY entity_id\n \"\"\"",
")",
"response",
"=",
"self",
".",
"perform_query",
"(",
"query",
")",
"# Parse the domains from the entities.",
"entities",
"=",
"{",
"}",
"domains",
"=",
"set",
"(",
")",
"for",
"[",
"entity",
"]",
"in",
"response",
":",
"domain",
"=",
"entity",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"domains",
".",
"add",
"(",
"domain",
")",
"entities",
".",
"setdefault",
"(",
"domain",
",",
"[",
"]",
")",
".",
"append",
"(",
"entity",
")",
"self",
".",
"_domains",
"=",
"list",
"(",
"domains",
")",
"self",
".",
"_entities",
"=",
"entities",
"print",
"(",
"\"There are {} entities with data\"",
".",
"format",
"(",
"len",
"(",
"entities",
")",
")",
")"
]
| Fetch entities for which we have data. | [
"Fetch",
"entities",
"for",
"which",
"we",
"have",
"data",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L82-L104 | train |
robmarkcole/HASS-data-detective | detective/core.py | HassDatabase.fetch_all_data | def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT :limit
"""
)
try:
print("Querying the database, this could take a while")
response = self.perform_query(query, limit=limit)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
self.parse_all_data()
except:
raise ValueError("Error querying the database.") | python | def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT :limit
"""
)
try:
print("Querying the database, this could take a while")
response = self.perform_query(query, limit=limit)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
self.parse_all_data()
except:
raise ValueError("Error querying the database.") | [
"def",
"fetch_all_data",
"(",
"self",
",",
"limit",
"=",
"50000",
")",
":",
"# Query text",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT domain, entity_id, state, last_changed\n FROM states\n WHERE\n state NOT IN ('unknown', 'unavailable')\n ORDER BY last_changed DESC\n LIMIT :limit\n \"\"\"",
")",
"try",
":",
"print",
"(",
"\"Querying the database, this could take a while\"",
")",
"response",
"=",
"self",
".",
"perform_query",
"(",
"query",
",",
"limit",
"=",
"limit",
")",
"master_df",
"=",
"pd",
".",
"DataFrame",
"(",
"response",
".",
"fetchall",
"(",
")",
")",
"print",
"(",
"\"master_df created successfully.\"",
")",
"self",
".",
"_master_df",
"=",
"master_df",
".",
"copy",
"(",
")",
"self",
".",
"parse_all_data",
"(",
")",
"except",
":",
"raise",
"ValueError",
"(",
"\"Error querying the database.\"",
")"
]
| Fetch data for all entities. | [
"Fetch",
"data",
"for",
"all",
"entities",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L155-L179 | train |
robmarkcole/HASS-data-detective | detective/core.py | HassDatabase.parse_all_data | def parse_all_data(self):
"""Parses the master df."""
self._master_df.columns = ["domain", "entity", "state", "last_changed"]
# Check if state is float and store in numericals category.
self._master_df["numerical"] = self._master_df["state"].apply(
lambda x: functions.isfloat(x)
)
# Multiindexing
self._master_df.set_index(
["domain", "entity", "numerical", "last_changed"], inplace=True
) | python | def parse_all_data(self):
"""Parses the master df."""
self._master_df.columns = ["domain", "entity", "state", "last_changed"]
# Check if state is float and store in numericals category.
self._master_df["numerical"] = self._master_df["state"].apply(
lambda x: functions.isfloat(x)
)
# Multiindexing
self._master_df.set_index(
["domain", "entity", "numerical", "last_changed"], inplace=True
) | [
"def",
"parse_all_data",
"(",
"self",
")",
":",
"self",
".",
"_master_df",
".",
"columns",
"=",
"[",
"\"domain\"",
",",
"\"entity\"",
",",
"\"state\"",
",",
"\"last_changed\"",
"]",
"# Check if state is float and store in numericals category.",
"self",
".",
"_master_df",
"[",
"\"numerical\"",
"]",
"=",
"self",
".",
"_master_df",
"[",
"\"state\"",
"]",
".",
"apply",
"(",
"lambda",
"x",
":",
"functions",
".",
"isfloat",
"(",
"x",
")",
")",
"# Multiindexing",
"self",
".",
"_master_df",
".",
"set_index",
"(",
"[",
"\"domain\"",
",",
"\"entity\"",
",",
"\"numerical\"",
",",
"\"last_changed\"",
"]",
",",
"inplace",
"=",
"True",
")"
]
| Parses the master df. | [
"Parses",
"the",
"master",
"df",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L181-L193 | train |
robmarkcole/HASS-data-detective | detective/core.py | NumericalSensors.correlations | def correlations(self):
"""
Calculate the correlation coefficients.
"""
corr_df = self._sensors_num_df.corr()
corr_names = []
corrs = []
for i in range(len(corr_df.index)):
for j in range(len(corr_df.index)):
c_name = corr_df.index[i]
r_name = corr_df.columns[j]
corr_names.append("%s-%s" % (c_name, r_name))
corrs.append(corr_df.ix[i, j])
corrs_all = pd.DataFrame(index=corr_names)
corrs_all["value"] = corrs
corrs_all = corrs_all.dropna().drop(
corrs_all[(corrs_all["value"] == float(1))].index
)
corrs_all = corrs_all.drop(corrs_all[corrs_all["value"] == float(-1)].index)
corrs_all = corrs_all.sort_values("value", ascending=False)
corrs_all = corrs_all.drop_duplicates()
return corrs_all | python | def correlations(self):
"""
Calculate the correlation coefficients.
"""
corr_df = self._sensors_num_df.corr()
corr_names = []
corrs = []
for i in range(len(corr_df.index)):
for j in range(len(corr_df.index)):
c_name = corr_df.index[i]
r_name = corr_df.columns[j]
corr_names.append("%s-%s" % (c_name, r_name))
corrs.append(corr_df.ix[i, j])
corrs_all = pd.DataFrame(index=corr_names)
corrs_all["value"] = corrs
corrs_all = corrs_all.dropna().drop(
corrs_all[(corrs_all["value"] == float(1))].index
)
corrs_all = corrs_all.drop(corrs_all[corrs_all["value"] == float(-1)].index)
corrs_all = corrs_all.sort_values("value", ascending=False)
corrs_all = corrs_all.drop_duplicates()
return corrs_all | [
"def",
"correlations",
"(",
"self",
")",
":",
"corr_df",
"=",
"self",
".",
"_sensors_num_df",
".",
"corr",
"(",
")",
"corr_names",
"=",
"[",
"]",
"corrs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"corr_df",
".",
"index",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"corr_df",
".",
"index",
")",
")",
":",
"c_name",
"=",
"corr_df",
".",
"index",
"[",
"i",
"]",
"r_name",
"=",
"corr_df",
".",
"columns",
"[",
"j",
"]",
"corr_names",
".",
"append",
"(",
"\"%s-%s\"",
"%",
"(",
"c_name",
",",
"r_name",
")",
")",
"corrs",
".",
"append",
"(",
"corr_df",
".",
"ix",
"[",
"i",
",",
"j",
"]",
")",
"corrs_all",
"=",
"pd",
".",
"DataFrame",
"(",
"index",
"=",
"corr_names",
")",
"corrs_all",
"[",
"\"value\"",
"]",
"=",
"corrs",
"corrs_all",
"=",
"corrs_all",
".",
"dropna",
"(",
")",
".",
"drop",
"(",
"corrs_all",
"[",
"(",
"corrs_all",
"[",
"\"value\"",
"]",
"==",
"float",
"(",
"1",
")",
")",
"]",
".",
"index",
")",
"corrs_all",
"=",
"corrs_all",
".",
"drop",
"(",
"corrs_all",
"[",
"corrs_all",
"[",
"\"value\"",
"]",
"==",
"float",
"(",
"-",
"1",
")",
"]",
".",
"index",
")",
"corrs_all",
"=",
"corrs_all",
".",
"sort_values",
"(",
"\"value\"",
",",
"ascending",
"=",
"False",
")",
"corrs_all",
"=",
"corrs_all",
".",
"drop_duplicates",
"(",
")",
"return",
"corrs_all"
]
| Calculate the correlation coefficients. | [
"Calculate",
"the",
"correlation",
"coefficients",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L248-L272 | train |
robmarkcole/HASS-data-detective | detective/core.py | NumericalSensors.plot | def plot(self, entities: List[str]):
"""
Basic plot of a numerical sensor data.
Parameters
----------
entities : a list of entities
"""
ax = self._sensors_num_df[entities].plot(figsize=[12, 6])
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
ax.set_xlabel("Date")
ax.set_ylabel("Reading")
return | python | def plot(self, entities: List[str]):
"""
Basic plot of a numerical sensor data.
Parameters
----------
entities : a list of entities
"""
ax = self._sensors_num_df[entities].plot(figsize=[12, 6])
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
ax.set_xlabel("Date")
ax.set_ylabel("Reading")
return | [
"def",
"plot",
"(",
"self",
",",
"entities",
":",
"List",
"[",
"str",
"]",
")",
":",
"ax",
"=",
"self",
".",
"_sensors_num_df",
"[",
"entities",
"]",
".",
"plot",
"(",
"figsize",
"=",
"[",
"12",
",",
"6",
"]",
")",
"ax",
".",
"legend",
"(",
"loc",
"=",
"\"center left\"",
",",
"bbox_to_anchor",
"=",
"(",
"1",
",",
"0.5",
")",
")",
"ax",
".",
"set_xlabel",
"(",
"\"Date\"",
")",
"ax",
".",
"set_ylabel",
"(",
"\"Reading\"",
")",
"return"
]
| Basic plot of a numerical sensor data.
Parameters
----------
entities : a list of entities | [
"Basic",
"plot",
"of",
"a",
"numerical",
"sensor",
"data",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L292-L305 | train |
robmarkcole/HASS-data-detective | detective/core.py | BinarySensors.plot | def plot(self, entity):
"""
Basic plot of a single binary sensor data.
Parameters
----------
entity : string
The entity to plot
"""
df = self._binary_df[[entity]]
resampled = df.resample("s").ffill() # Sample at seconds and ffill
resampled.columns = ["value"]
fig, ax = plt.subplots(1, 1, figsize=(16, 2))
ax.fill_between(resampled.index, y1=0, y2=1, facecolor="royalblue", label="off")
ax.fill_between(
resampled.index,
y1=0,
y2=1,
where=(resampled["value"] > 0),
facecolor="red",
label="on",
)
ax.set_title(entity)
ax.set_xlabel("Date")
ax.set_frame_on(False)
ax.set_yticks([])
plt.legend(loc=(1.01, 0.7))
plt.show()
return | python | def plot(self, entity):
"""
Basic plot of a single binary sensor data.
Parameters
----------
entity : string
The entity to plot
"""
df = self._binary_df[[entity]]
resampled = df.resample("s").ffill() # Sample at seconds and ffill
resampled.columns = ["value"]
fig, ax = plt.subplots(1, 1, figsize=(16, 2))
ax.fill_between(resampled.index, y1=0, y2=1, facecolor="royalblue", label="off")
ax.fill_between(
resampled.index,
y1=0,
y2=1,
where=(resampled["value"] > 0),
facecolor="red",
label="on",
)
ax.set_title(entity)
ax.set_xlabel("Date")
ax.set_frame_on(False)
ax.set_yticks([])
plt.legend(loc=(1.01, 0.7))
plt.show()
return | [
"def",
"plot",
"(",
"self",
",",
"entity",
")",
":",
"df",
"=",
"self",
".",
"_binary_df",
"[",
"[",
"entity",
"]",
"]",
"resampled",
"=",
"df",
".",
"resample",
"(",
"\"s\"",
")",
".",
"ffill",
"(",
")",
"# Sample at seconds and ffill",
"resampled",
".",
"columns",
"=",
"[",
"\"value\"",
"]",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
"(",
"16",
",",
"2",
")",
")",
"ax",
".",
"fill_between",
"(",
"resampled",
".",
"index",
",",
"y1",
"=",
"0",
",",
"y2",
"=",
"1",
",",
"facecolor",
"=",
"\"royalblue\"",
",",
"label",
"=",
"\"off\"",
")",
"ax",
".",
"fill_between",
"(",
"resampled",
".",
"index",
",",
"y1",
"=",
"0",
",",
"y2",
"=",
"1",
",",
"where",
"=",
"(",
"resampled",
"[",
"\"value\"",
"]",
">",
"0",
")",
",",
"facecolor",
"=",
"\"red\"",
",",
"label",
"=",
"\"on\"",
",",
")",
"ax",
".",
"set_title",
"(",
"entity",
")",
"ax",
".",
"set_xlabel",
"(",
"\"Date\"",
")",
"ax",
".",
"set_frame_on",
"(",
"False",
")",
"ax",
".",
"set_yticks",
"(",
"[",
"]",
")",
"plt",
".",
"legend",
"(",
"loc",
"=",
"(",
"1.01",
",",
"0.7",
")",
")",
"plt",
".",
"show",
"(",
")",
"return"
]
| Basic plot of a single binary sensor data.
Parameters
----------
entity : string
The entity to plot | [
"Basic",
"plot",
"of",
"a",
"single",
"binary",
"sensor",
"data",
"."
]
| f67dfde9dd63a3af411944d1857b0835632617c5 | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/core.py#L353-L381 | train |
django-salesforce/django-salesforce | salesforce/router.py | is_sf_database | def is_sf_database(db, model=None):
"""The alias is a Salesforce database."""
from django.db import connections
if db is None:
return getattr(model, '_salesforce_object', False)
engine = connections[db].settings_dict['ENGINE']
return engine == 'salesforce.backend' or connections[db].vendor == 'salesforce' | python | def is_sf_database(db, model=None):
"""The alias is a Salesforce database."""
from django.db import connections
if db is None:
return getattr(model, '_salesforce_object', False)
engine = connections[db].settings_dict['ENGINE']
return engine == 'salesforce.backend' or connections[db].vendor == 'salesforce' | [
"def",
"is_sf_database",
"(",
"db",
",",
"model",
"=",
"None",
")",
":",
"from",
"django",
".",
"db",
"import",
"connections",
"if",
"db",
"is",
"None",
":",
"return",
"getattr",
"(",
"model",
",",
"'_salesforce_object'",
",",
"False",
")",
"engine",
"=",
"connections",
"[",
"db",
"]",
".",
"settings_dict",
"[",
"'ENGINE'",
"]",
"return",
"engine",
"==",
"'salesforce.backend'",
"or",
"connections",
"[",
"db",
"]",
".",
"vendor",
"==",
"'salesforce'"
]
| The alias is a Salesforce database. | [
"The",
"alias",
"is",
"a",
"Salesforce",
"database",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/router.py#L16-L22 | train |
django-salesforce/django-salesforce | salesforce/router.py | ModelRouter.allow_migrate | def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Don't attempt to sync SF models to non SF databases and vice versa.
"""
if model_name:
model = apps.get_model(app_label, model_name)
else:
# hints are used with less priority, because many hints are dynamic
# models made by migrations on a '__fake__' module which are not
# SalesforceModels
model = hints.get('model')
if hasattr(model, '_salesforce_object'):
# SF models can be migrated if SALESFORCE_DB_ALIAS is e.g.
# a sqlite3 database or any non-SF database.
if not (is_sf_database(db) or db == self.sf_alias):
return False
else:
if is_sf_database(db) or self.sf_alias != 'default' and db == self.sf_alias:
return False
# TODO: It is usual that "migrate" is currently disallowed for SF.
# In the future it can be implemented to do a deep check by
# introspection of compatibily between Django models and SF database.
if hasattr(model, '_salesforce_object'):
# return False
pass | python | def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Don't attempt to sync SF models to non SF databases and vice versa.
"""
if model_name:
model = apps.get_model(app_label, model_name)
else:
# hints are used with less priority, because many hints are dynamic
# models made by migrations on a '__fake__' module which are not
# SalesforceModels
model = hints.get('model')
if hasattr(model, '_salesforce_object'):
# SF models can be migrated if SALESFORCE_DB_ALIAS is e.g.
# a sqlite3 database or any non-SF database.
if not (is_sf_database(db) or db == self.sf_alias):
return False
else:
if is_sf_database(db) or self.sf_alias != 'default' and db == self.sf_alias:
return False
# TODO: It is usual that "migrate" is currently disallowed for SF.
# In the future it can be implemented to do a deep check by
# introspection of compatibily between Django models and SF database.
if hasattr(model, '_salesforce_object'):
# return False
pass | [
"def",
"allow_migrate",
"(",
"self",
",",
"db",
",",
"app_label",
",",
"model_name",
"=",
"None",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model_name",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"app_label",
",",
"model_name",
")",
"else",
":",
"# hints are used with less priority, because many hints are dynamic",
"# models made by migrations on a '__fake__' module which are not",
"# SalesforceModels",
"model",
"=",
"hints",
".",
"get",
"(",
"'model'",
")",
"if",
"hasattr",
"(",
"model",
",",
"'_salesforce_object'",
")",
":",
"# SF models can be migrated if SALESFORCE_DB_ALIAS is e.g.",
"# a sqlite3 database or any non-SF database.",
"if",
"not",
"(",
"is_sf_database",
"(",
"db",
")",
"or",
"db",
"==",
"self",
".",
"sf_alias",
")",
":",
"return",
"False",
"else",
":",
"if",
"is_sf_database",
"(",
"db",
")",
"or",
"self",
".",
"sf_alias",
"!=",
"'default'",
"and",
"db",
"==",
"self",
".",
"sf_alias",
":",
"return",
"False",
"# TODO: It is usual that \"migrate\" is currently disallowed for SF.",
"# In the future it can be implemented to do a deep check by",
"# introspection of compatibily between Django models and SF database.",
"if",
"hasattr",
"(",
"model",
",",
"'_salesforce_object'",
")",
":",
"# return False",
"pass"
]
| Don't attempt to sync SF models to non SF databases and vice versa. | [
"Don",
"t",
"attempt",
"to",
"sync",
"SF",
"models",
"to",
"non",
"SF",
"databases",
"and",
"vice",
"versa",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/router.py#L60-L85 | train |
django-salesforce/django-salesforce | salesforce/backend/indep.py | LazyField.update | def update(self, **kwargs):
"""Customize the lazy field"""
assert not self.called
self.kw.update(kwargs)
return self | python | def update(self, **kwargs):
"""Customize the lazy field"""
assert not self.called
self.kw.update(kwargs)
return self | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"not",
"self",
".",
"called",
"self",
".",
"kw",
".",
"update",
"(",
"kwargs",
")",
"return",
"self"
]
| Customize the lazy field | [
"Customize",
"the",
"lazy",
"field"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/indep.py#L32-L36 | train |
django-salesforce/django-salesforce | salesforce/backend/indep.py | LazyField.create | def create(self):
"""Create a normal field from the lazy field"""
assert not self.called
return self.klass(*self.args, **self.kw) | python | def create(self):
"""Create a normal field from the lazy field"""
assert not self.called
return self.klass(*self.args, **self.kw) | [
"def",
"create",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"called",
"return",
"self",
".",
"klass",
"(",
"*",
"self",
".",
"args",
",",
"*",
"*",
"self",
".",
"kw",
")"
]
| Create a normal field from the lazy field | [
"Create",
"a",
"normal",
"field",
"from",
"the",
"lazy",
"field"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/indep.py#L38-L41 | train |
django-salesforce/django-salesforce | salesforce/backend/manager.py | SalesforceManager.get_queryset | def get_queryset(self):
"""
Returns a QuerySet which access remote SF objects.
"""
if router.is_sf_database(self.db):
q = models_sql_query.SalesforceQuery(self.model, where=compiler.SalesforceWhereNode)
return query.SalesforceQuerySet(self.model, query=q, using=self.db)
return super(SalesforceManager, self).get_queryset() | python | def get_queryset(self):
"""
Returns a QuerySet which access remote SF objects.
"""
if router.is_sf_database(self.db):
q = models_sql_query.SalesforceQuery(self.model, where=compiler.SalesforceWhereNode)
return query.SalesforceQuerySet(self.model, query=q, using=self.db)
return super(SalesforceManager, self).get_queryset() | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"if",
"router",
".",
"is_sf_database",
"(",
"self",
".",
"db",
")",
":",
"q",
"=",
"models_sql_query",
".",
"SalesforceQuery",
"(",
"self",
".",
"model",
",",
"where",
"=",
"compiler",
".",
"SalesforceWhereNode",
")",
"return",
"query",
".",
"SalesforceQuerySet",
"(",
"self",
".",
"model",
",",
"query",
"=",
"q",
",",
"using",
"=",
"self",
".",
"db",
")",
"return",
"super",
"(",
"SalesforceManager",
",",
"self",
")",
".",
"get_queryset",
"(",
")"
]
| Returns a QuerySet which access remote SF objects. | [
"Returns",
"a",
"QuerySet",
"which",
"access",
"remote",
"SF",
"objects",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/manager.py#L27-L34 | train |
django-salesforce/django-salesforce | salesforce/fields.py | SfField.get_attname_column | def get_attname_column(self):
"""
Get the database column name automatically in most cases.
"""
# See "A guide to Field parameters": django/db/models/fields/__init__.py
# * attname: The attribute to use on the model object. This is the same as
# "name", except in the case of ForeignKeys, where "_id" is
# appended.
# * column: The database column for this field. This is the same as
# "attname", except if db_column is specified.
attname = self.get_attname()
if self.db_column is not None:
# explicit name
column = self.db_column
else:
if not self.name.islower():
# a Salesforce style name e.g. 'LastName' or 'MyCustomField'
column = self.name
else:
# a Django style name like 'last_name' or 'my_custom_field'
column = self.name.title().replace('_', '')
# Fix custom fields
if self.sf_custom:
column = self.sf_namespace + column + '__c'
return attname, column | python | def get_attname_column(self):
"""
Get the database column name automatically in most cases.
"""
# See "A guide to Field parameters": django/db/models/fields/__init__.py
# * attname: The attribute to use on the model object. This is the same as
# "name", except in the case of ForeignKeys, where "_id" is
# appended.
# * column: The database column for this field. This is the same as
# "attname", except if db_column is specified.
attname = self.get_attname()
if self.db_column is not None:
# explicit name
column = self.db_column
else:
if not self.name.islower():
# a Salesforce style name e.g. 'LastName' or 'MyCustomField'
column = self.name
else:
# a Django style name like 'last_name' or 'my_custom_field'
column = self.name.title().replace('_', '')
# Fix custom fields
if self.sf_custom:
column = self.sf_namespace + column + '__c'
return attname, column | [
"def",
"get_attname_column",
"(",
"self",
")",
":",
"# See \"A guide to Field parameters\": django/db/models/fields/__init__.py",
"# * attname: The attribute to use on the model object. This is the same as",
"# \"name\", except in the case of ForeignKeys, where \"_id\" is",
"# appended.",
"# * column: The database column for this field. This is the same as",
"# \"attname\", except if db_column is specified.",
"attname",
"=",
"self",
".",
"get_attname",
"(",
")",
"if",
"self",
".",
"db_column",
"is",
"not",
"None",
":",
"# explicit name",
"column",
"=",
"self",
".",
"db_column",
"else",
":",
"if",
"not",
"self",
".",
"name",
".",
"islower",
"(",
")",
":",
"# a Salesforce style name e.g. 'LastName' or 'MyCustomField'",
"column",
"=",
"self",
".",
"name",
"else",
":",
"# a Django style name like 'last_name' or 'my_custom_field'",
"column",
"=",
"self",
".",
"name",
".",
"title",
"(",
")",
".",
"replace",
"(",
"'_'",
",",
"''",
")",
"# Fix custom fields",
"if",
"self",
".",
"sf_custom",
":",
"column",
"=",
"self",
".",
"sf_namespace",
"+",
"column",
"+",
"'__c'",
"return",
"attname",
",",
"column"
]
| Get the database column name automatically in most cases. | [
"Get",
"the",
"database",
"column",
"name",
"automatically",
"in",
"most",
"cases",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/fields.py#L109-L133 | train |
django-salesforce/django-salesforce | salesforce/backend/utils.py | extract_values | def extract_values(query):
"""
Extract values from insert or update query.
Supports bulk_create
"""
# pylint
if isinstance(query, subqueries.UpdateQuery):
row = query.values
return extract_values_inner(row, query)
if isinstance(query, subqueries.InsertQuery):
ret = []
for row in query.objs:
ret.append(extract_values_inner(row, query))
return ret
raise NotSupportedError | python | def extract_values(query):
"""
Extract values from insert or update query.
Supports bulk_create
"""
# pylint
if isinstance(query, subqueries.UpdateQuery):
row = query.values
return extract_values_inner(row, query)
if isinstance(query, subqueries.InsertQuery):
ret = []
for row in query.objs:
ret.append(extract_values_inner(row, query))
return ret
raise NotSupportedError | [
"def",
"extract_values",
"(",
"query",
")",
":",
"# pylint",
"if",
"isinstance",
"(",
"query",
",",
"subqueries",
".",
"UpdateQuery",
")",
":",
"row",
"=",
"query",
".",
"values",
"return",
"extract_values_inner",
"(",
"row",
",",
"query",
")",
"if",
"isinstance",
"(",
"query",
",",
"subqueries",
".",
"InsertQuery",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"row",
"in",
"query",
".",
"objs",
":",
"ret",
".",
"append",
"(",
"extract_values_inner",
"(",
"row",
",",
"query",
")",
")",
"return",
"ret",
"raise",
"NotSupportedError"
]
| Extract values from insert or update query.
Supports bulk_create | [
"Extract",
"values",
"from",
"insert",
"or",
"update",
"query",
".",
"Supports",
"bulk_create"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/utils.py#L94-L108 | train |
django-salesforce/django-salesforce | salesforce/backend/utils.py | CursorWrapper.execute | def execute(self, q, args=()):
"""
Send a query to the Salesforce API.
"""
# pylint:disable=too-many-branches
self.rowcount = None
response = None
if self.query is None:
self.execute_select(q, args)
else:
response = self.execute_django(q, args)
if isinstance(response, list):
return
# the encoding is detected automatically, e.g. from headers
if response and response.text:
# parse_float set to decimal.Decimal to avoid precision errors when
# converting from the json number to a float and then to a Decimal object
# on a model's DecimalField. This converts from json number directly
# to a Decimal object
data = response.json(parse_float=decimal.Decimal)
# a SELECT query
if 'totalSize' in data:
# SELECT
self.rowcount = data['totalSize']
# a successful INSERT query, return after getting PK
elif('success' in data and 'id' in data):
self.lastrowid = data['id']
return
elif 'compositeResponse' in data:
# TODO treat error reporting for composite requests
self.lastrowid = [x['body']['id'] if x['body'] is not None else x['referenceId']
for x in data['compositeResponse']]
return
elif data['hasErrors'] is False:
# it is from Composite Batch request
# save id from bulk_create even if Django don't use it
if data['results'] and data['results'][0]['result']:
self.lastrowid = [item['result']['id'] for item in data['results']]
return
# something we don't recognize
else:
raise DatabaseError(data)
if not q.upper().startswith('SELECT COUNT() FROM'):
self.first_row = data['records'][0] if data['records'] else None | python | def execute(self, q, args=()):
"""
Send a query to the Salesforce API.
"""
# pylint:disable=too-many-branches
self.rowcount = None
response = None
if self.query is None:
self.execute_select(q, args)
else:
response = self.execute_django(q, args)
if isinstance(response, list):
return
# the encoding is detected automatically, e.g. from headers
if response and response.text:
# parse_float set to decimal.Decimal to avoid precision errors when
# converting from the json number to a float and then to a Decimal object
# on a model's DecimalField. This converts from json number directly
# to a Decimal object
data = response.json(parse_float=decimal.Decimal)
# a SELECT query
if 'totalSize' in data:
# SELECT
self.rowcount = data['totalSize']
# a successful INSERT query, return after getting PK
elif('success' in data and 'id' in data):
self.lastrowid = data['id']
return
elif 'compositeResponse' in data:
# TODO treat error reporting for composite requests
self.lastrowid = [x['body']['id'] if x['body'] is not None else x['referenceId']
for x in data['compositeResponse']]
return
elif data['hasErrors'] is False:
# it is from Composite Batch request
# save id from bulk_create even if Django don't use it
if data['results'] and data['results'][0]['result']:
self.lastrowid = [item['result']['id'] for item in data['results']]
return
# something we don't recognize
else:
raise DatabaseError(data)
if not q.upper().startswith('SELECT COUNT() FROM'):
self.first_row = data['records'][0] if data['records'] else None | [
"def",
"execute",
"(",
"self",
",",
"q",
",",
"args",
"=",
"(",
")",
")",
":",
"# pylint:disable=too-many-branches",
"self",
".",
"rowcount",
"=",
"None",
"response",
"=",
"None",
"if",
"self",
".",
"query",
"is",
"None",
":",
"self",
".",
"execute_select",
"(",
"q",
",",
"args",
")",
"else",
":",
"response",
"=",
"self",
".",
"execute_django",
"(",
"q",
",",
"args",
")",
"if",
"isinstance",
"(",
"response",
",",
"list",
")",
":",
"return",
"# the encoding is detected automatically, e.g. from headers",
"if",
"response",
"and",
"response",
".",
"text",
":",
"# parse_float set to decimal.Decimal to avoid precision errors when",
"# converting from the json number to a float and then to a Decimal object",
"# on a model's DecimalField. This converts from json number directly",
"# to a Decimal object",
"data",
"=",
"response",
".",
"json",
"(",
"parse_float",
"=",
"decimal",
".",
"Decimal",
")",
"# a SELECT query",
"if",
"'totalSize'",
"in",
"data",
":",
"# SELECT",
"self",
".",
"rowcount",
"=",
"data",
"[",
"'totalSize'",
"]",
"# a successful INSERT query, return after getting PK",
"elif",
"(",
"'success'",
"in",
"data",
"and",
"'id'",
"in",
"data",
")",
":",
"self",
".",
"lastrowid",
"=",
"data",
"[",
"'id'",
"]",
"return",
"elif",
"'compositeResponse'",
"in",
"data",
":",
"# TODO treat error reporting for composite requests",
"self",
".",
"lastrowid",
"=",
"[",
"x",
"[",
"'body'",
"]",
"[",
"'id'",
"]",
"if",
"x",
"[",
"'body'",
"]",
"is",
"not",
"None",
"else",
"x",
"[",
"'referenceId'",
"]",
"for",
"x",
"in",
"data",
"[",
"'compositeResponse'",
"]",
"]",
"return",
"elif",
"data",
"[",
"'hasErrors'",
"]",
"is",
"False",
":",
"# it is from Composite Batch request",
"# save id from bulk_create even if Django don't use it",
"if",
"data",
"[",
"'results'",
"]",
"and",
"data",
"[",
"'results'",
"]",
"[",
"0",
"]",
"[",
"'result'",
"]",
":",
"self",
".",
"lastrowid",
"=",
"[",
"item",
"[",
"'result'",
"]",
"[",
"'id'",
"]",
"for",
"item",
"in",
"data",
"[",
"'results'",
"]",
"]",
"return",
"# something we don't recognize",
"else",
":",
"raise",
"DatabaseError",
"(",
"data",
")",
"if",
"not",
"q",
".",
"upper",
"(",
")",
".",
"startswith",
"(",
"'SELECT COUNT() FROM'",
")",
":",
"self",
".",
"first_row",
"=",
"data",
"[",
"'records'",
"]",
"[",
"0",
"]",
"if",
"data",
"[",
"'records'",
"]",
"else",
"None"
]
| Send a query to the Salesforce API. | [
"Send",
"a",
"query",
"to",
"the",
"Salesforce",
"API",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/utils.py#L173-L218 | train |
django-salesforce/django-salesforce | salesforce/backend/utils.py | CursorWrapper.execute_django | def execute_django(self, soql, args=()):
"""
Fixed execute for queries coming from Django query compilers
"""
response = None
sqltype = soql.split(None, 1)[0].upper()
if isinstance(self.query, subqueries.InsertQuery):
response = self.execute_insert(self.query)
elif isinstance(self.query, subqueries.UpdateQuery):
response = self.execute_update(self.query)
elif isinstance(self.query, subqueries.DeleteQuery):
response = self.execute_delete(self.query)
elif isinstance(self.query, RawQuery):
self.execute_select(soql, args)
elif sqltype in ('SAVEPOINT', 'ROLLBACK', 'RELEASE'):
log.info("Ignored SQL command '%s'", sqltype)
return
elif isinstance(self.query, Query):
self.execute_select(soql, args)
else:
raise DatabaseError("Unsupported query: type %s: %s" % (type(self.query), self.query))
return response | python | def execute_django(self, soql, args=()):
"""
Fixed execute for queries coming from Django query compilers
"""
response = None
sqltype = soql.split(None, 1)[0].upper()
if isinstance(self.query, subqueries.InsertQuery):
response = self.execute_insert(self.query)
elif isinstance(self.query, subqueries.UpdateQuery):
response = self.execute_update(self.query)
elif isinstance(self.query, subqueries.DeleteQuery):
response = self.execute_delete(self.query)
elif isinstance(self.query, RawQuery):
self.execute_select(soql, args)
elif sqltype in ('SAVEPOINT', 'ROLLBACK', 'RELEASE'):
log.info("Ignored SQL command '%s'", sqltype)
return
elif isinstance(self.query, Query):
self.execute_select(soql, args)
else:
raise DatabaseError("Unsupported query: type %s: %s" % (type(self.query), self.query))
return response | [
"def",
"execute_django",
"(",
"self",
",",
"soql",
",",
"args",
"=",
"(",
")",
")",
":",
"response",
"=",
"None",
"sqltype",
"=",
"soql",
".",
"split",
"(",
"None",
",",
"1",
")",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"if",
"isinstance",
"(",
"self",
".",
"query",
",",
"subqueries",
".",
"InsertQuery",
")",
":",
"response",
"=",
"self",
".",
"execute_insert",
"(",
"self",
".",
"query",
")",
"elif",
"isinstance",
"(",
"self",
".",
"query",
",",
"subqueries",
".",
"UpdateQuery",
")",
":",
"response",
"=",
"self",
".",
"execute_update",
"(",
"self",
".",
"query",
")",
"elif",
"isinstance",
"(",
"self",
".",
"query",
",",
"subqueries",
".",
"DeleteQuery",
")",
":",
"response",
"=",
"self",
".",
"execute_delete",
"(",
"self",
".",
"query",
")",
"elif",
"isinstance",
"(",
"self",
".",
"query",
",",
"RawQuery",
")",
":",
"self",
".",
"execute_select",
"(",
"soql",
",",
"args",
")",
"elif",
"sqltype",
"in",
"(",
"'SAVEPOINT'",
",",
"'ROLLBACK'",
",",
"'RELEASE'",
")",
":",
"log",
".",
"info",
"(",
"\"Ignored SQL command '%s'\"",
",",
"sqltype",
")",
"return",
"elif",
"isinstance",
"(",
"self",
".",
"query",
",",
"Query",
")",
":",
"self",
".",
"execute_select",
"(",
"soql",
",",
"args",
")",
"else",
":",
"raise",
"DatabaseError",
"(",
"\"Unsupported query: type %s: %s\"",
"%",
"(",
"type",
"(",
"self",
".",
"query",
")",
",",
"self",
".",
"query",
")",
")",
"return",
"response"
]
| Fixed execute for queries coming from Django query compilers | [
"Fixed",
"execute",
"for",
"queries",
"coming",
"from",
"Django",
"query",
"compilers"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/utils.py#L223-L244 | train |
django-salesforce/django-salesforce | salesforce/backend/utils.py | CursorWrapper.get_pks_from_query | def get_pks_from_query(self, query):
"""Prepare primary keys for update and delete queries"""
where = query.where
sql = None
if where.connector == 'AND' and not where.negated and len(where.children) == 1:
# simple cases are optimized, especially because a suboptimal
# nested query based on the same table is not allowed by SF
child = where.children[0]
if (child.lookup_name in ('exact', 'in') and child.lhs.target.column == 'Id'
and not child.bilateral_transforms and child.lhs.target.model is self.query.model):
pks = child.rhs
if child.lookup_name == 'exact':
assert isinstance(pks, text_type)
return [pks]
# lookup_name 'in'
assert not child.bilateral_transforms
if isinstance(pks, (tuple, list)):
return pks
if DJANGO_111_PLUS:
assert isinstance(pks, Query) and type(pks).__name__ == 'SalesforceQuery'
# # alternative solution:
# return list(salesforce.backend.query.SalesforceQuerySet(pk.model, query=pk, using=pk._db))
sql, params = pks.get_compiler('salesforce').as_sql()
else:
assert isinstance(pks, salesforce.backend.query.SalesforceQuerySet)
return [x.pk for x in pks]
if not sql:
# a subquery is necessary in this case
where_sql, params = where.as_sql(query.get_compiler('salesforce'), self.db.connection)
sql = "SELECT Id FROM {} WHERE {}".format(query.model._meta.db_table, where_sql)
with self.db.cursor() as cur:
cur.execute(sql, params)
assert len(cur.description) == 1 and cur.description[0][0] == 'Id'
return [x[0] for x in cur] | python | def get_pks_from_query(self, query):
"""Prepare primary keys for update and delete queries"""
where = query.where
sql = None
if where.connector == 'AND' and not where.negated and len(where.children) == 1:
# simple cases are optimized, especially because a suboptimal
# nested query based on the same table is not allowed by SF
child = where.children[0]
if (child.lookup_name in ('exact', 'in') and child.lhs.target.column == 'Id'
and not child.bilateral_transforms and child.lhs.target.model is self.query.model):
pks = child.rhs
if child.lookup_name == 'exact':
assert isinstance(pks, text_type)
return [pks]
# lookup_name 'in'
assert not child.bilateral_transforms
if isinstance(pks, (tuple, list)):
return pks
if DJANGO_111_PLUS:
assert isinstance(pks, Query) and type(pks).__name__ == 'SalesforceQuery'
# # alternative solution:
# return list(salesforce.backend.query.SalesforceQuerySet(pk.model, query=pk, using=pk._db))
sql, params = pks.get_compiler('salesforce').as_sql()
else:
assert isinstance(pks, salesforce.backend.query.SalesforceQuerySet)
return [x.pk for x in pks]
if not sql:
# a subquery is necessary in this case
where_sql, params = where.as_sql(query.get_compiler('salesforce'), self.db.connection)
sql = "SELECT Id FROM {} WHERE {}".format(query.model._meta.db_table, where_sql)
with self.db.cursor() as cur:
cur.execute(sql, params)
assert len(cur.description) == 1 and cur.description[0][0] == 'Id'
return [x[0] for x in cur] | [
"def",
"get_pks_from_query",
"(",
"self",
",",
"query",
")",
":",
"where",
"=",
"query",
".",
"where",
"sql",
"=",
"None",
"if",
"where",
".",
"connector",
"==",
"'AND'",
"and",
"not",
"where",
".",
"negated",
"and",
"len",
"(",
"where",
".",
"children",
")",
"==",
"1",
":",
"# simple cases are optimized, especially because a suboptimal",
"# nested query based on the same table is not allowed by SF",
"child",
"=",
"where",
".",
"children",
"[",
"0",
"]",
"if",
"(",
"child",
".",
"lookup_name",
"in",
"(",
"'exact'",
",",
"'in'",
")",
"and",
"child",
".",
"lhs",
".",
"target",
".",
"column",
"==",
"'Id'",
"and",
"not",
"child",
".",
"bilateral_transforms",
"and",
"child",
".",
"lhs",
".",
"target",
".",
"model",
"is",
"self",
".",
"query",
".",
"model",
")",
":",
"pks",
"=",
"child",
".",
"rhs",
"if",
"child",
".",
"lookup_name",
"==",
"'exact'",
":",
"assert",
"isinstance",
"(",
"pks",
",",
"text_type",
")",
"return",
"[",
"pks",
"]",
"# lookup_name 'in'",
"assert",
"not",
"child",
".",
"bilateral_transforms",
"if",
"isinstance",
"(",
"pks",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"pks",
"if",
"DJANGO_111_PLUS",
":",
"assert",
"isinstance",
"(",
"pks",
",",
"Query",
")",
"and",
"type",
"(",
"pks",
")",
".",
"__name__",
"==",
"'SalesforceQuery'",
"# # alternative solution:",
"# return list(salesforce.backend.query.SalesforceQuerySet(pk.model, query=pk, using=pk._db))",
"sql",
",",
"params",
"=",
"pks",
".",
"get_compiler",
"(",
"'salesforce'",
")",
".",
"as_sql",
"(",
")",
"else",
":",
"assert",
"isinstance",
"(",
"pks",
",",
"salesforce",
".",
"backend",
".",
"query",
".",
"SalesforceQuerySet",
")",
"return",
"[",
"x",
".",
"pk",
"for",
"x",
"in",
"pks",
"]",
"if",
"not",
"sql",
":",
"# a subquery is necessary in this case",
"where_sql",
",",
"params",
"=",
"where",
".",
"as_sql",
"(",
"query",
".",
"get_compiler",
"(",
"'salesforce'",
")",
",",
"self",
".",
"db",
".",
"connection",
")",
"sql",
"=",
"\"SELECT Id FROM {} WHERE {}\"",
".",
"format",
"(",
"query",
".",
"model",
".",
"_meta",
".",
"db_table",
",",
"where_sql",
")",
"with",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"as",
"cur",
":",
"cur",
".",
"execute",
"(",
"sql",
",",
"params",
")",
"assert",
"len",
"(",
"cur",
".",
"description",
")",
"==",
"1",
"and",
"cur",
".",
"description",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"'Id'",
"return",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"cur",
"]"
]
| Prepare primary keys for update and delete queries | [
"Prepare",
"primary",
"keys",
"for",
"update",
"and",
"delete",
"queries"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/utils.py#L286-L320 | train |
django-salesforce/django-salesforce | salesforce/backend/utils.py | CursorWrapper.versions_request | def versions_request(self):
"""List Available REST API Versions"""
ret = self.handle_api_exceptions('GET', '', api_ver='')
return [str_dict(x) for x in ret.json()] | python | def versions_request(self):
"""List Available REST API Versions"""
ret = self.handle_api_exceptions('GET', '', api_ver='')
return [str_dict(x) for x in ret.json()] | [
"def",
"versions_request",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"handle_api_exceptions",
"(",
"'GET'",
",",
"''",
",",
"api_ver",
"=",
"''",
")",
"return",
"[",
"str_dict",
"(",
"x",
")",
"for",
"x",
"in",
"ret",
".",
"json",
"(",
")",
"]"
]
| List Available REST API Versions | [
"List",
"Available",
"REST",
"API",
"Versions"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/utils.py#L401-L404 | train |
django-salesforce/django-salesforce | salesforce/management/commands/inspectdb.py | fix_international | def fix_international(text):
"Fix excaped international characters back to utf-8"
class SmartInternational(str):
def __new__(cls, text):
return str.__new__(cls, text)
def endswith(self, string):
return super(SmartInternational, self).endswith(str(string))
if PY3:
return text
out = []
last = 0
for match in re.finditer(r'(?<=[^\\])(?:\\x[0-9a-f]{2}|\\u[0-9a-f]{4})', text):
start, end, group = match.start(), match.end(), match.group()
out.append(text[last:start])
c = group.decode('unicode_escape')
out.append(c if ord(c) > 160 and ord(c) != 173 else group)
last = end
out.append(text[last:])
return SmartInternational(''.join(out).encode('utf-8')) | python | def fix_international(text):
"Fix excaped international characters back to utf-8"
class SmartInternational(str):
def __new__(cls, text):
return str.__new__(cls, text)
def endswith(self, string):
return super(SmartInternational, self).endswith(str(string))
if PY3:
return text
out = []
last = 0
for match in re.finditer(r'(?<=[^\\])(?:\\x[0-9a-f]{2}|\\u[0-9a-f]{4})', text):
start, end, group = match.start(), match.end(), match.group()
out.append(text[last:start])
c = group.decode('unicode_escape')
out.append(c if ord(c) > 160 and ord(c) != 173 else group)
last = end
out.append(text[last:])
return SmartInternational(''.join(out).encode('utf-8')) | [
"def",
"fix_international",
"(",
"text",
")",
":",
"class",
"SmartInternational",
"(",
"str",
")",
":",
"def",
"__new__",
"(",
"cls",
",",
"text",
")",
":",
"return",
"str",
".",
"__new__",
"(",
"cls",
",",
"text",
")",
"def",
"endswith",
"(",
"self",
",",
"string",
")",
":",
"return",
"super",
"(",
"SmartInternational",
",",
"self",
")",
".",
"endswith",
"(",
"str",
"(",
"string",
")",
")",
"if",
"PY3",
":",
"return",
"text",
"out",
"=",
"[",
"]",
"last",
"=",
"0",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r'(?<=[^\\\\])(?:\\\\x[0-9a-f]{2}|\\\\u[0-9a-f]{4})'",
",",
"text",
")",
":",
"start",
",",
"end",
",",
"group",
"=",
"match",
".",
"start",
"(",
")",
",",
"match",
".",
"end",
"(",
")",
",",
"match",
".",
"group",
"(",
")",
"out",
".",
"append",
"(",
"text",
"[",
"last",
":",
"start",
"]",
")",
"c",
"=",
"group",
".",
"decode",
"(",
"'unicode_escape'",
")",
"out",
".",
"append",
"(",
"c",
"if",
"ord",
"(",
"c",
")",
">",
"160",
"and",
"ord",
"(",
"c",
")",
"!=",
"173",
"else",
"group",
")",
"last",
"=",
"end",
"out",
".",
"append",
"(",
"text",
"[",
"last",
":",
"]",
")",
"return",
"SmartInternational",
"(",
"''",
".",
"join",
"(",
"out",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")"
]
| Fix excaped international characters back to utf-8 | [
"Fix",
"excaped",
"international",
"characters",
"back",
"to",
"utf",
"-",
"8"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/management/commands/inspectdb.py#L46-L65 | train |
django-salesforce/django-salesforce | salesforce/management/commands/inspectdb.py | Command.get_meta | def get_meta(self, table_name, constraints=None, column_to_field_name=None, is_view=False, is_partition=None):
"""
Return a sequence comprising the lines of code necessary
to construct the inner Meta class for the model corresponding
to the given database table name.
"""
# pylint:disable=arguments-differ,too-many-arguments,unused-argument
meta = [" class Meta(models.Model.Meta):",
" db_table = '%s'" % table_name]
if self.connection.vendor == 'salesforce':
for line in self.connection.introspection.get_additional_meta(table_name):
meta.append(" " + line)
meta.append("")
return meta | python | def get_meta(self, table_name, constraints=None, column_to_field_name=None, is_view=False, is_partition=None):
"""
Return a sequence comprising the lines of code necessary
to construct the inner Meta class for the model corresponding
to the given database table name.
"""
# pylint:disable=arguments-differ,too-many-arguments,unused-argument
meta = [" class Meta(models.Model.Meta):",
" db_table = '%s'" % table_name]
if self.connection.vendor == 'salesforce':
for line in self.connection.introspection.get_additional_meta(table_name):
meta.append(" " + line)
meta.append("")
return meta | [
"def",
"get_meta",
"(",
"self",
",",
"table_name",
",",
"constraints",
"=",
"None",
",",
"column_to_field_name",
"=",
"None",
",",
"is_view",
"=",
"False",
",",
"is_partition",
"=",
"None",
")",
":",
"# pylint:disable=arguments-differ,too-many-arguments,unused-argument",
"meta",
"=",
"[",
"\" class Meta(models.Model.Meta):\"",
",",
"\" db_table = '%s'\"",
"%",
"table_name",
"]",
"if",
"self",
".",
"connection",
".",
"vendor",
"==",
"'salesforce'",
":",
"for",
"line",
"in",
"self",
".",
"connection",
".",
"introspection",
".",
"get_additional_meta",
"(",
"table_name",
")",
":",
"meta",
".",
"append",
"(",
"\" \"",
"+",
"line",
")",
"meta",
".",
"append",
"(",
"\"\"",
")",
"return",
"meta"
]
| Return a sequence comprising the lines of code necessary
to construct the inner Meta class for the model corresponding
to the given database table name. | [
"Return",
"a",
"sequence",
"comprising",
"the",
"lines",
"of",
"code",
"necessary",
"to",
"construct",
"the",
"inner",
"Meta",
"class",
"for",
"the",
"model",
"corresponding",
"to",
"the",
"given",
"database",
"table",
"name",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/management/commands/inspectdb.py#L141-L154 | train |
django-salesforce/django-salesforce | setup.py | relative_path | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | [
"def",
"relative_path",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"path",
")"
]
| Return the given path relative to this file. | [
"Return",
"the",
"given",
"path",
"relative",
"to",
"this",
"file",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/setup.py#L16-L20 | train |
django-salesforce/django-salesforce | setup.py | get_tagged_version | def get_tagged_version():
"""
Determine the current version of this package.
Precise long version numbers are used if the Git repository is found.
They contain: the Git tag, the commit serial and a short commit id.
otherwise a short version number is used if installed from Pypi.
"""
with open(relative_path('salesforce/__init__.py'), 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
return version | python | def get_tagged_version():
"""
Determine the current version of this package.
Precise long version numbers are used if the Git repository is found.
They contain: the Git tag, the commit serial and a short commit id.
otherwise a short version number is used if installed from Pypi.
"""
with open(relative_path('salesforce/__init__.py'), 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
return version | [
"def",
"get_tagged_version",
"(",
")",
":",
"with",
"open",
"(",
"relative_path",
"(",
"'salesforce/__init__.py'",
")",
",",
"'r'",
")",
"as",
"fd",
":",
"version",
"=",
"re",
".",
"search",
"(",
"r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]'",
",",
"fd",
".",
"read",
"(",
")",
",",
"re",
".",
"MULTILINE",
")",
".",
"group",
"(",
"1",
")",
"return",
"version"
]
| Determine the current version of this package.
Precise long version numbers are used if the Git repository is found.
They contain: the Git tag, the commit serial and a short commit id.
otherwise a short version number is used if installed from Pypi. | [
"Determine",
"the",
"current",
"version",
"of",
"this",
"package",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/setup.py#L23-L34 | train |
django-salesforce/django-salesforce | salesforce/auth.py | SalesforceAuth.dynamic_start | def dynamic_start(self, access_token, instance_url=None, **kw):
"""
Set the access token dynamically according to the current user.
More parameters can be set.
"""
self.dynamic = {'access_token': str(access_token), 'instance_url': str(instance_url)}
self.dynamic.update(kw) | python | def dynamic_start(self, access_token, instance_url=None, **kw):
"""
Set the access token dynamically according to the current user.
More parameters can be set.
"""
self.dynamic = {'access_token': str(access_token), 'instance_url': str(instance_url)}
self.dynamic.update(kw) | [
"def",
"dynamic_start",
"(",
"self",
",",
"access_token",
",",
"instance_url",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"dynamic",
"=",
"{",
"'access_token'",
":",
"str",
"(",
"access_token",
")",
",",
"'instance_url'",
":",
"str",
"(",
"instance_url",
")",
"}",
"self",
".",
"dynamic",
".",
"update",
"(",
"kw",
")"
]
| Set the access token dynamically according to the current user.
More parameters can be set. | [
"Set",
"the",
"access",
"token",
"dynamically",
"according",
"to",
"the",
"current",
"user",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/auth.py#L144-L151 | train |
django-salesforce/django-salesforce | salesforce/dbapi/subselect.py | mark_quoted_strings | def mark_quoted_strings(sql):
"""Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes.
"""
# pattern of a string parameter (pm), a char escaped by backslash (bs)
# out_pattern: characters valid in SOQL
pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
bs_pattern = re.compile(r"\\([\\'])")
out_pattern = re.compile(r"^(?:[-!()*+,.:<=>\w\s|%s])*$")
missing_apostrophe = "invalid character in SOQL or a missing apostrophe"
start = 0
out = []
params = []
for match in pm_pattern.finditer(sql):
out.append(sql[start:match.start()])
assert out_pattern.match(sql[start:match.start()]), missing_apostrophe
params.append(bs_pattern.sub('\\1', sql[match.start() + 1:match.end() - 1]))
start = match.end()
out.append(sql[start:])
assert out_pattern.match(sql[start:]), missing_apostrophe
return '@'.join(out), params | python | def mark_quoted_strings(sql):
"""Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes.
"""
# pattern of a string parameter (pm), a char escaped by backslash (bs)
# out_pattern: characters valid in SOQL
pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
bs_pattern = re.compile(r"\\([\\'])")
out_pattern = re.compile(r"^(?:[-!()*+,.:<=>\w\s|%s])*$")
missing_apostrophe = "invalid character in SOQL or a missing apostrophe"
start = 0
out = []
params = []
for match in pm_pattern.finditer(sql):
out.append(sql[start:match.start()])
assert out_pattern.match(sql[start:match.start()]), missing_apostrophe
params.append(bs_pattern.sub('\\1', sql[match.start() + 1:match.end() - 1]))
start = match.end()
out.append(sql[start:])
assert out_pattern.match(sql[start:]), missing_apostrophe
return '@'.join(out), params | [
"def",
"mark_quoted_strings",
"(",
"sql",
")",
":",
"# pattern of a string parameter (pm), a char escaped by backslash (bs)",
"# out_pattern: characters valid in SOQL",
"pm_pattern",
"=",
"re",
".",
"compile",
"(",
"r\"'[^\\\\']*(?:\\\\[\\\\'][^\\\\']*)*'\"",
")",
"bs_pattern",
"=",
"re",
".",
"compile",
"(",
"r\"\\\\([\\\\'])\"",
")",
"out_pattern",
"=",
"re",
".",
"compile",
"(",
"r\"^(?:[-!()*+,.:<=>\\w\\s|%s])*$\"",
")",
"missing_apostrophe",
"=",
"\"invalid character in SOQL or a missing apostrophe\"",
"start",
"=",
"0",
"out",
"=",
"[",
"]",
"params",
"=",
"[",
"]",
"for",
"match",
"in",
"pm_pattern",
".",
"finditer",
"(",
"sql",
")",
":",
"out",
".",
"append",
"(",
"sql",
"[",
"start",
":",
"match",
".",
"start",
"(",
")",
"]",
")",
"assert",
"out_pattern",
".",
"match",
"(",
"sql",
"[",
"start",
":",
"match",
".",
"start",
"(",
")",
"]",
")",
",",
"missing_apostrophe",
"params",
".",
"append",
"(",
"bs_pattern",
".",
"sub",
"(",
"'\\\\1'",
",",
"sql",
"[",
"match",
".",
"start",
"(",
")",
"+",
"1",
":",
"match",
".",
"end",
"(",
")",
"-",
"1",
"]",
")",
")",
"start",
"=",
"match",
".",
"end",
"(",
")",
"out",
".",
"append",
"(",
"sql",
"[",
"start",
":",
"]",
")",
"assert",
"out_pattern",
".",
"match",
"(",
"sql",
"[",
"start",
":",
"]",
")",
",",
"missing_apostrophe",
"return",
"'@'",
".",
"join",
"(",
"out",
")",
",",
"params"
]
| Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes. | [
"Mark",
"all",
"quoted",
"strings",
"in",
"the",
"SOQL",
"by"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/subselect.py#L194-L214 | train |
django-salesforce/django-salesforce | salesforce/dbapi/subselect.py | subst_quoted_strings | def subst_quoted_strings(sql, params):
"""Reverse operation to mark_quoted_strings - substitutes '@' by params.
"""
parts = sql.split('@')
params_dont_match = "number of parameters doesn' match the transformed query"
assert len(parts) == len(params) + 1, params_dont_match # would be internal error
out = []
for i, param in enumerate(params):
out.append(parts[i])
out.append("'%s'" % param.replace('\\', '\\\\').replace("\'", "\\\'"))
out.append(parts[-1])
return ''.join(out) | python | def subst_quoted_strings(sql, params):
"""Reverse operation to mark_quoted_strings - substitutes '@' by params.
"""
parts = sql.split('@')
params_dont_match = "number of parameters doesn' match the transformed query"
assert len(parts) == len(params) + 1, params_dont_match # would be internal error
out = []
for i, param in enumerate(params):
out.append(parts[i])
out.append("'%s'" % param.replace('\\', '\\\\').replace("\'", "\\\'"))
out.append(parts[-1])
return ''.join(out) | [
"def",
"subst_quoted_strings",
"(",
"sql",
",",
"params",
")",
":",
"parts",
"=",
"sql",
".",
"split",
"(",
"'@'",
")",
"params_dont_match",
"=",
"\"number of parameters doesn' match the transformed query\"",
"assert",
"len",
"(",
"parts",
")",
"==",
"len",
"(",
"params",
")",
"+",
"1",
",",
"params_dont_match",
"# would be internal error",
"out",
"=",
"[",
"]",
"for",
"i",
",",
"param",
"in",
"enumerate",
"(",
"params",
")",
":",
"out",
".",
"append",
"(",
"parts",
"[",
"i",
"]",
")",
"out",
".",
"append",
"(",
"\"'%s'\"",
"%",
"param",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
".",
"replace",
"(",
"\"\\'\"",
",",
"\"\\\\\\'\"",
")",
")",
"out",
".",
"append",
"(",
"parts",
"[",
"-",
"1",
"]",
")",
"return",
"''",
".",
"join",
"(",
"out",
")"
]
| Reverse operation to mark_quoted_strings - substitutes '@' by params. | [
"Reverse",
"operation",
"to",
"mark_quoted_strings",
"-",
"substitutes"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/subselect.py#L217-L228 | train |
django-salesforce/django-salesforce | salesforce/dbapi/subselect.py | find_closing_parenthesis | def find_closing_parenthesis(sql, startpos):
"""Find the pair of opening and closing parentheses.
Starts search at the position startpos.
Returns tuple of positions (opening, closing) if search succeeds, otherwise None.
"""
pattern = re.compile(r'[()]')
level = 0
opening = []
for match in pattern.finditer(sql, startpos):
par = match.group()
if par == '(':
if level == 0:
opening = match.start()
level += 1
if par == ')':
assert level > 0, "missing '(' before ')'"
level -= 1
if level == 0:
closing = match.end()
return opening, closing | python | def find_closing_parenthesis(sql, startpos):
"""Find the pair of opening and closing parentheses.
Starts search at the position startpos.
Returns tuple of positions (opening, closing) if search succeeds, otherwise None.
"""
pattern = re.compile(r'[()]')
level = 0
opening = []
for match in pattern.finditer(sql, startpos):
par = match.group()
if par == '(':
if level == 0:
opening = match.start()
level += 1
if par == ')':
assert level > 0, "missing '(' before ')'"
level -= 1
if level == 0:
closing = match.end()
return opening, closing | [
"def",
"find_closing_parenthesis",
"(",
"sql",
",",
"startpos",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'[()]'",
")",
"level",
"=",
"0",
"opening",
"=",
"[",
"]",
"for",
"match",
"in",
"pattern",
".",
"finditer",
"(",
"sql",
",",
"startpos",
")",
":",
"par",
"=",
"match",
".",
"group",
"(",
")",
"if",
"par",
"==",
"'('",
":",
"if",
"level",
"==",
"0",
":",
"opening",
"=",
"match",
".",
"start",
"(",
")",
"level",
"+=",
"1",
"if",
"par",
"==",
"')'",
":",
"assert",
"level",
">",
"0",
",",
"\"missing '(' before ')'\"",
"level",
"-=",
"1",
"if",
"level",
"==",
"0",
":",
"closing",
"=",
"match",
".",
"end",
"(",
")",
"return",
"opening",
",",
"closing"
]
| Find the pair of opening and closing parentheses.
Starts search at the position startpos.
Returns tuple of positions (opening, closing) if search succeeds, otherwise None. | [
"Find",
"the",
"pair",
"of",
"opening",
"and",
"closing",
"parentheses",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/subselect.py#L231-L251 | train |
django-salesforce/django-salesforce | salesforce/dbapi/subselect.py | split_subquery | def split_subquery(sql):
"""Split on subqueries and replace them by '&'."""
sql, params = mark_quoted_strings(sql)
sql = simplify_expression(sql)
_ = params # NOQA
start = 0
out = []
subqueries = []
pattern = re.compile(r'\(SELECT\b', re.I)
match = pattern.search(sql, start)
while match:
out.append(sql[start:match.start() + 1] + '&')
start, pos = find_closing_parenthesis(sql, match.start())
start, pos = start + 1, pos - 1
subqueries.append(split_subquery(sql[start:pos]))
start = pos
match = pattern.search(sql, start)
out.append(sql[start:len(sql)])
return ''.join(out), subqueries | python | def split_subquery(sql):
"""Split on subqueries and replace them by '&'."""
sql, params = mark_quoted_strings(sql)
sql = simplify_expression(sql)
_ = params # NOQA
start = 0
out = []
subqueries = []
pattern = re.compile(r'\(SELECT\b', re.I)
match = pattern.search(sql, start)
while match:
out.append(sql[start:match.start() + 1] + '&')
start, pos = find_closing_parenthesis(sql, match.start())
start, pos = start + 1, pos - 1
subqueries.append(split_subquery(sql[start:pos]))
start = pos
match = pattern.search(sql, start)
out.append(sql[start:len(sql)])
return ''.join(out), subqueries | [
"def",
"split_subquery",
"(",
"sql",
")",
":",
"sql",
",",
"params",
"=",
"mark_quoted_strings",
"(",
"sql",
")",
"sql",
"=",
"simplify_expression",
"(",
"sql",
")",
"_",
"=",
"params",
"# NOQA",
"start",
"=",
"0",
"out",
"=",
"[",
"]",
"subqueries",
"=",
"[",
"]",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'\\(SELECT\\b'",
",",
"re",
".",
"I",
")",
"match",
"=",
"pattern",
".",
"search",
"(",
"sql",
",",
"start",
")",
"while",
"match",
":",
"out",
".",
"append",
"(",
"sql",
"[",
"start",
":",
"match",
".",
"start",
"(",
")",
"+",
"1",
"]",
"+",
"'&'",
")",
"start",
",",
"pos",
"=",
"find_closing_parenthesis",
"(",
"sql",
",",
"match",
".",
"start",
"(",
")",
")",
"start",
",",
"pos",
"=",
"start",
"+",
"1",
",",
"pos",
"-",
"1",
"subqueries",
".",
"append",
"(",
"split_subquery",
"(",
"sql",
"[",
"start",
":",
"pos",
"]",
")",
")",
"start",
"=",
"pos",
"match",
"=",
"pattern",
".",
"search",
"(",
"sql",
",",
"start",
")",
"out",
".",
"append",
"(",
"sql",
"[",
"start",
":",
"len",
"(",
"sql",
")",
"]",
")",
"return",
"''",
".",
"join",
"(",
"out",
")",
",",
"subqueries"
]
| Split on subqueries and replace them by '&'. | [
"Split",
"on",
"subqueries",
"and",
"replace",
"them",
"by",
"&",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/subselect.py#L268-L286 | train |
django-salesforce/django-salesforce | salesforce/dbapi/subselect.py | simplify_expression | def simplify_expression(txt):
"""Remove all unecessary whitespace and some very usual space"""
minimal = re.sub(r'\s', ' ',
re.sub(r'\s(?=\W)', '',
re.sub(r'(?<=\W)\s', '',
txt.strip())))
# add space before some "(" and after some ")"
return re.sub(r'\)(?=\w)', ') ',
re.sub(r'(,|\b(?:{}))\('.format('|'.join(RESERVED_WORDS)), '\\1 (', minimal)
) | python | def simplify_expression(txt):
"""Remove all unecessary whitespace and some very usual space"""
minimal = re.sub(r'\s', ' ',
re.sub(r'\s(?=\W)', '',
re.sub(r'(?<=\W)\s', '',
txt.strip())))
# add space before some "(" and after some ")"
return re.sub(r'\)(?=\w)', ') ',
re.sub(r'(,|\b(?:{}))\('.format('|'.join(RESERVED_WORDS)), '\\1 (', minimal)
) | [
"def",
"simplify_expression",
"(",
"txt",
")",
":",
"minimal",
"=",
"re",
".",
"sub",
"(",
"r'\\s'",
",",
"' '",
",",
"re",
".",
"sub",
"(",
"r'\\s(?=\\W)'",
",",
"''",
",",
"re",
".",
"sub",
"(",
"r'(?<=\\W)\\s'",
",",
"''",
",",
"txt",
".",
"strip",
"(",
")",
")",
")",
")",
"# add space before some \"(\" and after some \")\"",
"return",
"re",
".",
"sub",
"(",
"r'\\)(?=\\w)'",
",",
"') '",
",",
"re",
".",
"sub",
"(",
"r'(,|\\b(?:{}))\\('",
".",
"format",
"(",
"'|'",
".",
"join",
"(",
"RESERVED_WORDS",
")",
")",
",",
"'\\\\1 ('",
",",
"minimal",
")",
")"
]
| Remove all unecessary whitespace and some very usual space | [
"Remove",
"all",
"unecessary",
"whitespace",
"and",
"some",
"very",
"usual",
"space"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/subselect.py#L289-L298 | train |
django-salesforce/django-salesforce | salesforce/dbapi/subselect.py | QQuery._make_flat | def _make_flat(self, row_dict, path, subroots):
"""Replace the nested dict objects by a flat dict with keys "object.object.name"."""
# can get a cursor parameter, if introspection should be possible on the fly
out = {}
for k, v in row_dict.items():
klc = k.lower() # "key lower case"
if (not (isinstance(v, dict) and 'attributes' in v)
or ('done' in v and 'records' in v and 'totalSize' in v)):
# :
if klc not in subroots:
out[klc] = v
else:
strpath = '.'.join(path + (klc,)) + '.'
strip_pos = len(strpath) - len(klc + '.')
for alias in self.aliases:
if alias.lower().startswith(strpath):
out[alias.lower()[strip_pos:]] = None # empty outer join field names
else:
new_subroots = subroots[klc] if k != 'attributes' else {}
for sub_k, sub_v in self._make_flat(v, path + (klc,), new_subroots).items():
out[k.lower() + '.' + sub_k] = sub_v
return out | python | def _make_flat(self, row_dict, path, subroots):
"""Replace the nested dict objects by a flat dict with keys "object.object.name"."""
# can get a cursor parameter, if introspection should be possible on the fly
out = {}
for k, v in row_dict.items():
klc = k.lower() # "key lower case"
if (not (isinstance(v, dict) and 'attributes' in v)
or ('done' in v and 'records' in v and 'totalSize' in v)):
# :
if klc not in subroots:
out[klc] = v
else:
strpath = '.'.join(path + (klc,)) + '.'
strip_pos = len(strpath) - len(klc + '.')
for alias in self.aliases:
if alias.lower().startswith(strpath):
out[alias.lower()[strip_pos:]] = None # empty outer join field names
else:
new_subroots = subroots[klc] if k != 'attributes' else {}
for sub_k, sub_v in self._make_flat(v, path + (klc,), new_subroots).items():
out[k.lower() + '.' + sub_k] = sub_v
return out | [
"def",
"_make_flat",
"(",
"self",
",",
"row_dict",
",",
"path",
",",
"subroots",
")",
":",
"# can get a cursor parameter, if introspection should be possible on the fly",
"out",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"row_dict",
".",
"items",
"(",
")",
":",
"klc",
"=",
"k",
".",
"lower",
"(",
")",
"# \"key lower case\"",
"if",
"(",
"not",
"(",
"isinstance",
"(",
"v",
",",
"dict",
")",
"and",
"'attributes'",
"in",
"v",
")",
"or",
"(",
"'done'",
"in",
"v",
"and",
"'records'",
"in",
"v",
"and",
"'totalSize'",
"in",
"v",
")",
")",
":",
"# :",
"if",
"klc",
"not",
"in",
"subroots",
":",
"out",
"[",
"klc",
"]",
"=",
"v",
"else",
":",
"strpath",
"=",
"'.'",
".",
"join",
"(",
"path",
"+",
"(",
"klc",
",",
")",
")",
"+",
"'.'",
"strip_pos",
"=",
"len",
"(",
"strpath",
")",
"-",
"len",
"(",
"klc",
"+",
"'.'",
")",
"for",
"alias",
"in",
"self",
".",
"aliases",
":",
"if",
"alias",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"strpath",
")",
":",
"out",
"[",
"alias",
".",
"lower",
"(",
")",
"[",
"strip_pos",
":",
"]",
"]",
"=",
"None",
"# empty outer join field names",
"else",
":",
"new_subroots",
"=",
"subroots",
"[",
"klc",
"]",
"if",
"k",
"!=",
"'attributes'",
"else",
"{",
"}",
"for",
"sub_k",
",",
"sub_v",
"in",
"self",
".",
"_make_flat",
"(",
"v",
",",
"path",
"+",
"(",
"klc",
",",
")",
",",
"new_subroots",
")",
".",
"items",
"(",
")",
":",
"out",
"[",
"k",
".",
"lower",
"(",
")",
"+",
"'.'",
"+",
"sub_k",
"]",
"=",
"sub_v",
"return",
"out"
]
| Replace the nested dict objects by a flat dict with keys "object.object.name". | [
"Replace",
"the",
"nested",
"dict",
"objects",
"by",
"a",
"flat",
"dict",
"with",
"keys",
"object",
".",
"object",
".",
"name",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/subselect.py#L128-L149 | train |
django-salesforce/django-salesforce | salesforce/dbapi/subselect.py | QQuery.parse_rest_response | def parse_rest_response(self, records, rowcount, row_type=list):
"""Parse the REST API response to DB API cursor flat response"""
if self.is_plain_count:
# result of "SELECT COUNT() FROM ... WHERE ..."
assert list(records) == []
yield rowcount # originally [resp.json()['totalSize']]
else:
while True:
for row_deep in records:
assert self.is_aggregation == (row_deep['attributes']['type'] == 'AggregateResult')
row_flat = self._make_flat(row_deep, path=(), subroots=self.subroots)
# TODO Will be the expression "or x['done']" really correct also for long subrequests?
assert all(not isinstance(x, dict) or x['done'] for x in row_flat)
if issubclass(row_type, dict):
yield {k: fix_data_type(row_flat[k.lower()]) for k in self.aliases}
else:
yield [fix_data_type(row_flat[k.lower()]) for k in self.aliases]
# if not resp['done']:
# if not cursor:
# raise ProgrammingError("Must get a cursor")
# resp = cursor.query_more(resp['nextRecordsUrl']).json()
# else:
# break
break | python | def parse_rest_response(self, records, rowcount, row_type=list):
"""Parse the REST API response to DB API cursor flat response"""
if self.is_plain_count:
# result of "SELECT COUNT() FROM ... WHERE ..."
assert list(records) == []
yield rowcount # originally [resp.json()['totalSize']]
else:
while True:
for row_deep in records:
assert self.is_aggregation == (row_deep['attributes']['type'] == 'AggregateResult')
row_flat = self._make_flat(row_deep, path=(), subroots=self.subroots)
# TODO Will be the expression "or x['done']" really correct also for long subrequests?
assert all(not isinstance(x, dict) or x['done'] for x in row_flat)
if issubclass(row_type, dict):
yield {k: fix_data_type(row_flat[k.lower()]) for k in self.aliases}
else:
yield [fix_data_type(row_flat[k.lower()]) for k in self.aliases]
# if not resp['done']:
# if not cursor:
# raise ProgrammingError("Must get a cursor")
# resp = cursor.query_more(resp['nextRecordsUrl']).json()
# else:
# break
break | [
"def",
"parse_rest_response",
"(",
"self",
",",
"records",
",",
"rowcount",
",",
"row_type",
"=",
"list",
")",
":",
"if",
"self",
".",
"is_plain_count",
":",
"# result of \"SELECT COUNT() FROM ... WHERE ...\"",
"assert",
"list",
"(",
"records",
")",
"==",
"[",
"]",
"yield",
"rowcount",
"# originally [resp.json()['totalSize']]",
"else",
":",
"while",
"True",
":",
"for",
"row_deep",
"in",
"records",
":",
"assert",
"self",
".",
"is_aggregation",
"==",
"(",
"row_deep",
"[",
"'attributes'",
"]",
"[",
"'type'",
"]",
"==",
"'AggregateResult'",
")",
"row_flat",
"=",
"self",
".",
"_make_flat",
"(",
"row_deep",
",",
"path",
"=",
"(",
")",
",",
"subroots",
"=",
"self",
".",
"subroots",
")",
"# TODO Will be the expression \"or x['done']\" really correct also for long subrequests?",
"assert",
"all",
"(",
"not",
"isinstance",
"(",
"x",
",",
"dict",
")",
"or",
"x",
"[",
"'done'",
"]",
"for",
"x",
"in",
"row_flat",
")",
"if",
"issubclass",
"(",
"row_type",
",",
"dict",
")",
":",
"yield",
"{",
"k",
":",
"fix_data_type",
"(",
"row_flat",
"[",
"k",
".",
"lower",
"(",
")",
"]",
")",
"for",
"k",
"in",
"self",
".",
"aliases",
"}",
"else",
":",
"yield",
"[",
"fix_data_type",
"(",
"row_flat",
"[",
"k",
".",
"lower",
"(",
")",
"]",
")",
"for",
"k",
"in",
"self",
".",
"aliases",
"]",
"# if not resp['done']:",
"# if not cursor:",
"# raise ProgrammingError(\"Must get a cursor\")",
"# resp = cursor.query_more(resp['nextRecordsUrl']).json()",
"# else:",
"# break",
"break"
]
| Parse the REST API response to DB API cursor flat response | [
"Parse",
"the",
"REST",
"API",
"response",
"to",
"DB",
"API",
"cursor",
"flat",
"response"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/subselect.py#L151-L174 | train |
django-salesforce/django-salesforce | salesforce/models.py | make_dynamic_fields | def make_dynamic_fields(pattern_module, dynamic_field_patterns, attrs):
"""Add some Salesforce fields from a pattern_module models.py
Parameters:
pattern_module: Module where to search additional fields settings.
It is an imported module created by introspection (inspectdb),
usually named `models_template.py`. (You will probably not add it
to version control for you because the diffs are frequent and huge.)
dynamic_field_patterns: List of regular expression for Salesforce
field names that should be included automatically into the model.
attrs: Input/Output dictionary of model attributes. (no need to
worry, added automatically)
The patterns are applied sequentionally.
If the pattern starts with "-" then the matched names are excluded.
The search stops after the first match.
A normal field that exists directly in a class is never rewritten
by a dynamic field..
All ForeingKey fields should be created explicitely. (For now to
prevent possible issues and also for better readibility of the
model. The automatic "dynamic" fields are intended especially for
"maybe can be useful" fields and will work with ForeignKey in simple
cases, e.g. without Proxy models etc. Works good for me.)
This is useful for development: Many fields or all fields can be
easily accessed by the model without a huge code. Finally
all wildcard fields except the explicit names can be removed when
the development is ready or .
If you create migrations, you probably want to disable "dynamic_field_patterns"
by setting them empty.
Example:
Meta:
db_table = 'Contact'
dynamic_patterns = exported.models, ['Last', '.*Date$']
"""
# pylint:disable=invalid-name,too-many-branches,too-many-locals
import re
attr_meta = attrs['Meta']
db_table = getattr(attr_meta, 'db_table', None)
if not db_table:
raise RuntimeError('The "db_table" must be set in Meta if "dynamic_field_patterns" is used.')
is_custom_model = getattr(attr_meta, 'custom', False)
patterns = []
for pat in dynamic_field_patterns:
enabled = True
if pat.startswith('-'):
enabled = False
pat = pat[1:]
patterns.append((enabled, re.compile(r'^(?:{})$'.format(pat), re.I)))
used_columns = []
for name, attr in attrs.items():
if isinstance(attr, SfField):
field = attr
if field.sf_custom is None and is_custom_model:
field.sf_custom = True
if not field.name:
field.name = name
attname, column = field.get_attname_column() # pylint:disable=unused-variable
used_columns.append(column)
if not pattern_module:
raise RuntimeError("a pattern_module is required for dynamic fields.")
for name, obj in vars(pattern_module).items():
if not name.startswith('_') and isclass(obj) and issubclass(obj, ModelTemplate):
default_table = obj.__name__
if getattr(getattr(obj, 'Meta', None), 'db_table', default_table) == db_table:
cls = obj
break
else:
# not found db_table model, but decide between warning or exception
if any(not x.startswith('__') for x in dir(pattern_module)):
raise RuntimeError("No Model for table '%s' found in the module '%s'"
% (db_table, pattern_module.__name__))
warnings.warn("The module '%s' is empty. (It is OK if you are "
"rewriting new Models by pipe from inspectdb command.)"
% pattern_module.__name__)
return
lazy_fields = [(name, obj) for name, obj in vars(cls).items()
if isinstance(obj, LazyField) and issubclass(obj.klass, SfField)
]
for name, obj in sorted(lazy_fields, key=lambda name_obj: name_obj[1].counter):
for enabled, pat in patterns:
if pat.match(name):
break
else:
enabled = False
if enabled:
if issubclass(obj.klass, ForeignKey):
to = obj.kw['to']
if isclass(to) and issubclass(to, ModelTemplate):
obj.kw['to'] = to.__name__
field = obj.create()
attrs[name] = field
assert pattern_module | python | def make_dynamic_fields(pattern_module, dynamic_field_patterns, attrs):
"""Add some Salesforce fields from a pattern_module models.py
Parameters:
pattern_module: Module where to search additional fields settings.
It is an imported module created by introspection (inspectdb),
usually named `models_template.py`. (You will probably not add it
to version control for you because the diffs are frequent and huge.)
dynamic_field_patterns: List of regular expression for Salesforce
field names that should be included automatically into the model.
attrs: Input/Output dictionary of model attributes. (no need to
worry, added automatically)
The patterns are applied sequentionally.
If the pattern starts with "-" then the matched names are excluded.
The search stops after the first match.
A normal field that exists directly in a class is never rewritten
by a dynamic field..
All ForeingKey fields should be created explicitely. (For now to
prevent possible issues and also for better readibility of the
model. The automatic "dynamic" fields are intended especially for
"maybe can be useful" fields and will work with ForeignKey in simple
cases, e.g. without Proxy models etc. Works good for me.)
This is useful for development: Many fields or all fields can be
easily accessed by the model without a huge code. Finally
all wildcard fields except the explicit names can be removed when
the development is ready or .
If you create migrations, you probably want to disable "dynamic_field_patterns"
by setting them empty.
Example:
Meta:
db_table = 'Contact'
dynamic_patterns = exported.models, ['Last', '.*Date$']
"""
# pylint:disable=invalid-name,too-many-branches,too-many-locals
import re
attr_meta = attrs['Meta']
db_table = getattr(attr_meta, 'db_table', None)
if not db_table:
raise RuntimeError('The "db_table" must be set in Meta if "dynamic_field_patterns" is used.')
is_custom_model = getattr(attr_meta, 'custom', False)
patterns = []
for pat in dynamic_field_patterns:
enabled = True
if pat.startswith('-'):
enabled = False
pat = pat[1:]
patterns.append((enabled, re.compile(r'^(?:{})$'.format(pat), re.I)))
used_columns = []
for name, attr in attrs.items():
if isinstance(attr, SfField):
field = attr
if field.sf_custom is None and is_custom_model:
field.sf_custom = True
if not field.name:
field.name = name
attname, column = field.get_attname_column() # pylint:disable=unused-variable
used_columns.append(column)
if not pattern_module:
raise RuntimeError("a pattern_module is required for dynamic fields.")
for name, obj in vars(pattern_module).items():
if not name.startswith('_') and isclass(obj) and issubclass(obj, ModelTemplate):
default_table = obj.__name__
if getattr(getattr(obj, 'Meta', None), 'db_table', default_table) == db_table:
cls = obj
break
else:
# not found db_table model, but decide between warning or exception
if any(not x.startswith('__') for x in dir(pattern_module)):
raise RuntimeError("No Model for table '%s' found in the module '%s'"
% (db_table, pattern_module.__name__))
warnings.warn("The module '%s' is empty. (It is OK if you are "
"rewriting new Models by pipe from inspectdb command.)"
% pattern_module.__name__)
return
lazy_fields = [(name, obj) for name, obj in vars(cls).items()
if isinstance(obj, LazyField) and issubclass(obj.klass, SfField)
]
for name, obj in sorted(lazy_fields, key=lambda name_obj: name_obj[1].counter):
for enabled, pat in patterns:
if pat.match(name):
break
else:
enabled = False
if enabled:
if issubclass(obj.klass, ForeignKey):
to = obj.kw['to']
if isclass(to) and issubclass(to, ModelTemplate):
obj.kw['to'] = to.__name__
field = obj.create()
attrs[name] = field
assert pattern_module | [
"def",
"make_dynamic_fields",
"(",
"pattern_module",
",",
"dynamic_field_patterns",
",",
"attrs",
")",
":",
"# pylint:disable=invalid-name,too-many-branches,too-many-locals",
"import",
"re",
"attr_meta",
"=",
"attrs",
"[",
"'Meta'",
"]",
"db_table",
"=",
"getattr",
"(",
"attr_meta",
",",
"'db_table'",
",",
"None",
")",
"if",
"not",
"db_table",
":",
"raise",
"RuntimeError",
"(",
"'The \"db_table\" must be set in Meta if \"dynamic_field_patterns\" is used.'",
")",
"is_custom_model",
"=",
"getattr",
"(",
"attr_meta",
",",
"'custom'",
",",
"False",
")",
"patterns",
"=",
"[",
"]",
"for",
"pat",
"in",
"dynamic_field_patterns",
":",
"enabled",
"=",
"True",
"if",
"pat",
".",
"startswith",
"(",
"'-'",
")",
":",
"enabled",
"=",
"False",
"pat",
"=",
"pat",
"[",
"1",
":",
"]",
"patterns",
".",
"append",
"(",
"(",
"enabled",
",",
"re",
".",
"compile",
"(",
"r'^(?:{})$'",
".",
"format",
"(",
"pat",
")",
",",
"re",
".",
"I",
")",
")",
")",
"used_columns",
"=",
"[",
"]",
"for",
"name",
",",
"attr",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"attr",
",",
"SfField",
")",
":",
"field",
"=",
"attr",
"if",
"field",
".",
"sf_custom",
"is",
"None",
"and",
"is_custom_model",
":",
"field",
".",
"sf_custom",
"=",
"True",
"if",
"not",
"field",
".",
"name",
":",
"field",
".",
"name",
"=",
"name",
"attname",
",",
"column",
"=",
"field",
".",
"get_attname_column",
"(",
")",
"# pylint:disable=unused-variable",
"used_columns",
".",
"append",
"(",
"column",
")",
"if",
"not",
"pattern_module",
":",
"raise",
"RuntimeError",
"(",
"\"a pattern_module is required for dynamic fields.\"",
")",
"for",
"name",
",",
"obj",
"in",
"vars",
"(",
"pattern_module",
")",
".",
"items",
"(",
")",
":",
"if",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
"and",
"isclass",
"(",
"obj",
")",
"and",
"issubclass",
"(",
"obj",
",",
"ModelTemplate",
")",
":",
"default_table",
"=",
"obj",
".",
"__name__",
"if",
"getattr",
"(",
"getattr",
"(",
"obj",
",",
"'Meta'",
",",
"None",
")",
",",
"'db_table'",
",",
"default_table",
")",
"==",
"db_table",
":",
"cls",
"=",
"obj",
"break",
"else",
":",
"# not found db_table model, but decide between warning or exception",
"if",
"any",
"(",
"not",
"x",
".",
"startswith",
"(",
"'__'",
")",
"for",
"x",
"in",
"dir",
"(",
"pattern_module",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"\"No Model for table '%s' found in the module '%s'\"",
"%",
"(",
"db_table",
",",
"pattern_module",
".",
"__name__",
")",
")",
"warnings",
".",
"warn",
"(",
"\"The module '%s' is empty. (It is OK if you are \"",
"\"rewriting new Models by pipe from inspectdb command.)\"",
"%",
"pattern_module",
".",
"__name__",
")",
"return",
"lazy_fields",
"=",
"[",
"(",
"name",
",",
"obj",
")",
"for",
"name",
",",
"obj",
"in",
"vars",
"(",
"cls",
")",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"LazyField",
")",
"and",
"issubclass",
"(",
"obj",
".",
"klass",
",",
"SfField",
")",
"]",
"for",
"name",
",",
"obj",
"in",
"sorted",
"(",
"lazy_fields",
",",
"key",
"=",
"lambda",
"name_obj",
":",
"name_obj",
"[",
"1",
"]",
".",
"counter",
")",
":",
"for",
"enabled",
",",
"pat",
"in",
"patterns",
":",
"if",
"pat",
".",
"match",
"(",
"name",
")",
":",
"break",
"else",
":",
"enabled",
"=",
"False",
"if",
"enabled",
":",
"if",
"issubclass",
"(",
"obj",
".",
"klass",
",",
"ForeignKey",
")",
":",
"to",
"=",
"obj",
".",
"kw",
"[",
"'to'",
"]",
"if",
"isclass",
"(",
"to",
")",
"and",
"issubclass",
"(",
"to",
",",
"ModelTemplate",
")",
":",
"obj",
".",
"kw",
"[",
"'to'",
"]",
"=",
"to",
".",
"__name__",
"field",
"=",
"obj",
".",
"create",
"(",
")",
"attrs",
"[",
"name",
"]",
"=",
"field",
"assert",
"pattern_module"
]
| Add some Salesforce fields from a pattern_module models.py
Parameters:
pattern_module: Module where to search additional fields settings.
It is an imported module created by introspection (inspectdb),
usually named `models_template.py`. (You will probably not add it
to version control for you because the diffs are frequent and huge.)
dynamic_field_patterns: List of regular expression for Salesforce
field names that should be included automatically into the model.
attrs: Input/Output dictionary of model attributes. (no need to
worry, added automatically)
The patterns are applied sequentionally.
If the pattern starts with "-" then the matched names are excluded.
The search stops after the first match.
A normal field that exists directly in a class is never rewritten
by a dynamic field..
All ForeingKey fields should be created explicitely. (For now to
prevent possible issues and also for better readibility of the
model. The automatic "dynamic" fields are intended especially for
"maybe can be useful" fields and will work with ForeignKey in simple
cases, e.g. without Proxy models etc. Works good for me.)
This is useful for development: Many fields or all fields can be
easily accessed by the model without a huge code. Finally
all wildcard fields except the explicit names can be removed when
the development is ready or .
If you create migrations, you probably want to disable "dynamic_field_patterns"
by setting them empty.
Example:
Meta:
db_table = 'Contact'
dynamic_patterns = exported.models, ['Last', '.*Date$'] | [
"Add",
"some",
"Salesforce",
"fields",
"from",
"a",
"pattern_module",
"models",
".",
"py"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/models.py#L103-L199 | train |
django-salesforce/django-salesforce | salesforce/dbapi/exceptions.py | prepare_exception | def prepare_exception(obj, messages=None, response=None, verbs=None):
"""Prepare excetion params or only an exception message
parameters:
messages: list of strings, that will be separated by new line
response: response from a request to SFDC REST API
verbs: list of options about verbosity
"""
# pylint:disable=too-many-branches
verbs = set(verbs or [])
known_options = ['method+url']
if messages is None:
messages = []
if isinstance(messages, (text_type, str)):
messages = [messages]
assert isinstance(messages, list)
assert not verbs.difference(known_options)
data = None
# a boolean from a failed response is False, though error messages in json should be decoded
if response is not None and 'json' in response.headers.get('Content-Type', '') and response.text:
data = json.loads(response.text)
if data:
data_0 = data[0]
if 'errorCode' in data_0:
subreq = ''
if 'referenceId' in data_0:
subreq = " (in subrequest {!r})".format(data_0['referenceId'])
messages = [data_0['errorCode'] + subreq] + messages
if data_0.get('fields'):
messages.append('FIELDS: {}'.format(data_0['fields']))
if len(data) > 1:
messages.append('MORE_ERRORS ({})'.format(len(data)))
if 'method+url' in verbs:
method = response.request.method
url = response.request.url
if len(url) > 100:
url = url[:100] + '...'
data_info = ''
if (method in ('POST', 'PATCH') and
(not response.request.body or 'json' not in response.request.headers['content-type'])):
data_info = ' (without json request data)'
messages.append('in {} "{}"{}'.format(method, url, data_info))
separ = '\n '
if not PY3:
messages = [x if isinstance(x, str) else x.encode('utf-8') for x in messages]
messages = [x.replace('\n', separ) for x in messages]
message = separ.join(messages)
if obj:
obj.data = data
obj.response = response
obj.verbs = verbs
return message | python | def prepare_exception(obj, messages=None, response=None, verbs=None):
"""Prepare excetion params or only an exception message
parameters:
messages: list of strings, that will be separated by new line
response: response from a request to SFDC REST API
verbs: list of options about verbosity
"""
# pylint:disable=too-many-branches
verbs = set(verbs or [])
known_options = ['method+url']
if messages is None:
messages = []
if isinstance(messages, (text_type, str)):
messages = [messages]
assert isinstance(messages, list)
assert not verbs.difference(known_options)
data = None
# a boolean from a failed response is False, though error messages in json should be decoded
if response is not None and 'json' in response.headers.get('Content-Type', '') and response.text:
data = json.loads(response.text)
if data:
data_0 = data[0]
if 'errorCode' in data_0:
subreq = ''
if 'referenceId' in data_0:
subreq = " (in subrequest {!r})".format(data_0['referenceId'])
messages = [data_0['errorCode'] + subreq] + messages
if data_0.get('fields'):
messages.append('FIELDS: {}'.format(data_0['fields']))
if len(data) > 1:
messages.append('MORE_ERRORS ({})'.format(len(data)))
if 'method+url' in verbs:
method = response.request.method
url = response.request.url
if len(url) > 100:
url = url[:100] + '...'
data_info = ''
if (method in ('POST', 'PATCH') and
(not response.request.body or 'json' not in response.request.headers['content-type'])):
data_info = ' (without json request data)'
messages.append('in {} "{}"{}'.format(method, url, data_info))
separ = '\n '
if not PY3:
messages = [x if isinstance(x, str) else x.encode('utf-8') for x in messages]
messages = [x.replace('\n', separ) for x in messages]
message = separ.join(messages)
if obj:
obj.data = data
obj.response = response
obj.verbs = verbs
return message | [
"def",
"prepare_exception",
"(",
"obj",
",",
"messages",
"=",
"None",
",",
"response",
"=",
"None",
",",
"verbs",
"=",
"None",
")",
":",
"# pylint:disable=too-many-branches",
"verbs",
"=",
"set",
"(",
"verbs",
"or",
"[",
"]",
")",
"known_options",
"=",
"[",
"'method+url'",
"]",
"if",
"messages",
"is",
"None",
":",
"messages",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"messages",
",",
"(",
"text_type",
",",
"str",
")",
")",
":",
"messages",
"=",
"[",
"messages",
"]",
"assert",
"isinstance",
"(",
"messages",
",",
"list",
")",
"assert",
"not",
"verbs",
".",
"difference",
"(",
"known_options",
")",
"data",
"=",
"None",
"# a boolean from a failed response is False, though error messages in json should be decoded",
"if",
"response",
"is",
"not",
"None",
"and",
"'json'",
"in",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"''",
")",
"and",
"response",
".",
"text",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
"if",
"data",
":",
"data_0",
"=",
"data",
"[",
"0",
"]",
"if",
"'errorCode'",
"in",
"data_0",
":",
"subreq",
"=",
"''",
"if",
"'referenceId'",
"in",
"data_0",
":",
"subreq",
"=",
"\" (in subrequest {!r})\"",
".",
"format",
"(",
"data_0",
"[",
"'referenceId'",
"]",
")",
"messages",
"=",
"[",
"data_0",
"[",
"'errorCode'",
"]",
"+",
"subreq",
"]",
"+",
"messages",
"if",
"data_0",
".",
"get",
"(",
"'fields'",
")",
":",
"messages",
".",
"append",
"(",
"'FIELDS: {}'",
".",
"format",
"(",
"data_0",
"[",
"'fields'",
"]",
")",
")",
"if",
"len",
"(",
"data",
")",
">",
"1",
":",
"messages",
".",
"append",
"(",
"'MORE_ERRORS ({})'",
".",
"format",
"(",
"len",
"(",
"data",
")",
")",
")",
"if",
"'method+url'",
"in",
"verbs",
":",
"method",
"=",
"response",
".",
"request",
".",
"method",
"url",
"=",
"response",
".",
"request",
".",
"url",
"if",
"len",
"(",
"url",
")",
">",
"100",
":",
"url",
"=",
"url",
"[",
":",
"100",
"]",
"+",
"'...'",
"data_info",
"=",
"''",
"if",
"(",
"method",
"in",
"(",
"'POST'",
",",
"'PATCH'",
")",
"and",
"(",
"not",
"response",
".",
"request",
".",
"body",
"or",
"'json'",
"not",
"in",
"response",
".",
"request",
".",
"headers",
"[",
"'content-type'",
"]",
")",
")",
":",
"data_info",
"=",
"' (without json request data)'",
"messages",
".",
"append",
"(",
"'in {} \"{}\"{}'",
".",
"format",
"(",
"method",
",",
"url",
",",
"data_info",
")",
")",
"separ",
"=",
"'\\n '",
"if",
"not",
"PY3",
":",
"messages",
"=",
"[",
"x",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
"else",
"x",
".",
"encode",
"(",
"'utf-8'",
")",
"for",
"x",
"in",
"messages",
"]",
"messages",
"=",
"[",
"x",
".",
"replace",
"(",
"'\\n'",
",",
"separ",
")",
"for",
"x",
"in",
"messages",
"]",
"message",
"=",
"separ",
".",
"join",
"(",
"messages",
")",
"if",
"obj",
":",
"obj",
".",
"data",
"=",
"data",
"obj",
".",
"response",
"=",
"response",
"obj",
".",
"verbs",
"=",
"verbs",
"return",
"message"
]
| Prepare excetion params or only an exception message
parameters:
messages: list of strings, that will be separated by new line
response: response from a request to SFDC REST API
verbs: list of options about verbosity | [
"Prepare",
"excetion",
"params",
"or",
"only",
"an",
"exception",
"message"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/exceptions.py#L67-L119 | train |
django-salesforce/django-salesforce | salesforce/dbapi/exceptions.py | warn_sf | def warn_sf(messages, response, verbs=None, klass=SalesforceWarning):
"""Issue a warning SalesforceWarning, with message combined from message and data from SFDC response"""
warnings.warn(klass(messages, response, verbs), stacklevel=2) | python | def warn_sf(messages, response, verbs=None, klass=SalesforceWarning):
"""Issue a warning SalesforceWarning, with message combined from message and data from SFDC response"""
warnings.warn(klass(messages, response, verbs), stacklevel=2) | [
"def",
"warn_sf",
"(",
"messages",
",",
"response",
",",
"verbs",
"=",
"None",
",",
"klass",
"=",
"SalesforceWarning",
")",
":",
"warnings",
".",
"warn",
"(",
"klass",
"(",
"messages",
",",
"response",
",",
"verbs",
")",
",",
"stacklevel",
"=",
"2",
")"
]
| Issue a warning SalesforceWarning, with message combined from message and data from SFDC response | [
"Issue",
"a",
"warning",
"SalesforceWarning",
"with",
"message",
"combined",
"from",
"message",
"and",
"data",
"from",
"SFDC",
"response"
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/exceptions.py#L122-L124 | train |
django-salesforce/django-salesforce | salesforce/backend/compiler.py | SQLCompiler.get_from_clause | def get_from_clause(self):
"""
Return the FROM clause, converted the SOQL dialect.
It should be only the name of base object, even in parent-to-child and
child-to-parent relationships queries.
"""
self.query_topology()
root_table = self.soql_trans[self.root_alias]
return [root_table], [] | python | def get_from_clause(self):
"""
Return the FROM clause, converted the SOQL dialect.
It should be only the name of base object, even in parent-to-child and
child-to-parent relationships queries.
"""
self.query_topology()
root_table = self.soql_trans[self.root_alias]
return [root_table], [] | [
"def",
"get_from_clause",
"(",
"self",
")",
":",
"self",
".",
"query_topology",
"(",
")",
"root_table",
"=",
"self",
".",
"soql_trans",
"[",
"self",
".",
"root_alias",
"]",
"return",
"[",
"root_table",
"]",
",",
"[",
"]"
]
| Return the FROM clause, converted the SOQL dialect.
It should be only the name of base object, even in parent-to-child and
child-to-parent relationships queries. | [
"Return",
"the",
"FROM",
"clause",
"converted",
"the",
"SOQL",
"dialect",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/compiler.py#L34-L43 | train |
django-salesforce/django-salesforce | salesforce/backend/compiler.py | SQLCompiler.quote_name_unless_alias | def quote_name_unless_alias(self, name):
"""
A wrapper around connection.ops.quote_name that doesn't quote aliases
for table names. Mostly used during the ORDER BY clause.
"""
r = self.connection.ops.quote_name(name)
self.quote_cache[name] = r
return r | python | def quote_name_unless_alias(self, name):
"""
A wrapper around connection.ops.quote_name that doesn't quote aliases
for table names. Mostly used during the ORDER BY clause.
"""
r = self.connection.ops.quote_name(name)
self.quote_cache[name] = r
return r | [
"def",
"quote_name_unless_alias",
"(",
"self",
",",
"name",
")",
":",
"r",
"=",
"self",
".",
"connection",
".",
"ops",
".",
"quote_name",
"(",
"name",
")",
"self",
".",
"quote_cache",
"[",
"name",
"]",
"=",
"r",
"return",
"r"
]
| A wrapper around connection.ops.quote_name that doesn't quote aliases
for table names. Mostly used during the ORDER BY clause. | [
"A",
"wrapper",
"around",
"connection",
".",
"ops",
".",
"quote_name",
"that",
"doesn",
"t",
"quote",
"aliases",
"for",
"table",
"names",
".",
"Mostly",
"used",
"during",
"the",
"ORDER",
"BY",
"clause",
"."
]
| 6fd5643dba69d49c5881de50875cf90204a8f808 | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/compiler.py#L45-L52 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.