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",
")... | 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_transfo... | 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_transfo... | [
"def",
"remove",
"(",
"self",
",",
"name",
")",
":",
"cpu_transforms",
"=",
"self",
".",
"_remove_transform",
"(",
"self",
".",
"cpu_transforms",
",",
"name",
")",
"gpu_transforms",
"=",
"self",
".",
"_remove_transform",
"(",
"self",
".",
"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",
"[",
":",
":",
"-",
... | 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",
"(",
... | 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... | 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... | [
"def",
"connect",
"(",
"self",
",",
"func",
"=",
"None",
",",
"event",
"=",
"None",
",",
"set_method",
"=",
"False",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"partial",
"(",
"self",
".",
"connect",
",",
"set_method",
"=",
"set_method",
")... | 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... | [
"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",
"(",... | 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 = s... | 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 = s... | [
"def",
"emit",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"callbacks",
"=",
"self",
".",
"_callbacks",
".",
"get",
"(",
"event",
",",
"[",
"]",
")",
"# Call the last callback if this is a single event.",
"single",
"=",
... | 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 va... | 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 va... | [
"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",
",",
... | 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... | 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... | [
"def",
"discover_plugins",
"(",
"dirs",
")",
":",
"# Scan all subdirectories recursively.",
"for",
"path",
"in",
"_iter_plugin_files",
"(",
"dirs",
")",
":",
"filename",
"=",
"op",
".",
"basename",
"(",
"path",
")",
"subdir",
"=",
"op",
".",
"dirname",
"(",
... | 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... | 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... | [
"def",
"add_view",
"(",
"self",
",",
"view",
",",
"name",
"=",
"None",
",",
"position",
"=",
"None",
",",
"closable",
"=",
"False",
",",
"floatable",
"=",
"True",
",",
"floating",
"=",
"None",
")",
":",
"# Set the name in the view.",
"view",
".",
"view_i... | 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
... | 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
... | [
"def",
"list_views",
"(",
"self",
",",
"name",
"=",
"''",
",",
"is_visible",
"=",
"True",
")",
":",
"children",
"=",
"self",
".",
"findChildren",
"(",
"QWidget",
")",
"return",
"[",
"child",
".",
"view",
"for",
"child",
"in",
"children",
"if",
"isinsta... | 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",
"retur... | 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",
".",... | 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.resto... | 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.resto... | [
"def",
"restore_geometry_state",
"(",
"self",
",",
"gs",
")",
":",
"if",
"not",
"gs",
":",
"return",
"if",
"gs",
".",
"get",
"(",
"'geometry'",
",",
"None",
")",
":",
"self",
".",
"restoreGeometry",
"(",
"(",
"gs",
"[",
"'geometry'",
"]",
")",
")",
... | 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"... | 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(... | 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(... | [
"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",... | 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",
... | 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' i... | 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' i... | [
"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 inst... | 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... | 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... | [
"def",
"memcache",
"(",
"self",
",",
"f",
")",
":",
"name",
"=",
"_fullname",
"(",
"f",
")",
"cache",
"=",
"self",
".",
"load_memcache",
"(",
"name",
")",
"@",
"wraps",
"(",
"f",
")",
"def",
"memcached",
"(",
"*",
"args",
")",
":",
"\"\"\"Cache the... | 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.debu... | 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.debu... | [
"def",
"save",
"(",
"self",
",",
"name",
",",
"data",
",",
"location",
"=",
"'local'",
",",
"kind",
"=",
"'json'",
")",
":",
"file_ext",
"=",
"'.json'",
"if",
"kind",
"==",
"'json'",
"else",
"'.pkl'",
"path",
"=",
"self",
".",
"_get_path",
"(",
"name... | 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):
... | 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):
... | [
"def",
"load",
"(",
"self",
",",
"name",
",",
"location",
"=",
"'local'",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"name",
",",
"location",
",",
"file_ext",
"=",
"'.json'",
")",
"if",
"op",
".",
"exists",
"(",
"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':
... | 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':
... | [
"def",
"load_config",
"(",
"path",
"=",
"None",
")",
":",
"if",
"not",
"path",
"or",
"not",
"op",
".",
"exists",
"(",
"path",
")",
":",
"return",
"Config",
"(",
")",
"path",
"=",
"op",
".",
"realpath",
"(",
"path",
")",
"dirpath",
",",
"filename",
... | 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 = ad... | 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 = ad... | [
"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"... | 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",
".",
... | 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",
... | 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'.f... | 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'.f... | [
"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",
"(",
... | 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",
"(",
... | 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",... | 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",
"=",
"_p... | 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",... | 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`.\"",
... | 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 = {'f... | 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 = {'f... | [
"def",
"add_column",
"(",
"self",
",",
"func",
",",
"name",
"=",
"None",
",",
"show",
"=",
"True",
")",
":",
"assert",
"func",
"name",
"=",
"name",
"or",
"func",
".",
"__name__",
"if",
"name",
"==",
"'<lambda>'",
":",
"raise",
"ValueError",
"(",
"\"P... | 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_... | 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_... | [
"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 row... | 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(\"{}\", \"{}\");'",
".",
"forma... | 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:
... | 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:
... | [
"def",
"select",
"(",
"self",
",",
"ids",
",",
"do_emit",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Select the rows without emiting the event.",
"self",
".",
"eval_js",
"(",
"'table.select({}, false);'",
".",
"format",
"(",
"dumps",
"(",
"ids",
")",
... | 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 int... | 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 int... | [
"def",
"set_interval",
"(",
"self",
",",
"interval",
"=",
"None",
",",
"change_status",
"=",
"True",
",",
"force_update",
"=",
"False",
")",
":",
"if",
"interval",
"is",
"None",
":",
"interval",
"=",
"self",
".",
"_interval",
"interval",
"=",
"self",
"."... | 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_durat... | 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"... | 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",
"["... | 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",
".",
... | 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 "
... | 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 "
... | [
"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"... | 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 FileNotFoundErr... | 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 FileNotFoundErr... | [
"def",
"_secret_yaml",
"(",
"loader",
",",
"node",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"loader",
".",
"name",
")",
",",
"\"secrets.yaml\"",
")",
"try",
":",
"with",
"open",
"(",
"fnam... | 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... | 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... | [
"def",
"_stub_tag",
"(",
"constructor",
",",
"node",
")",
":",
"seen",
"=",
"getattr",
"(",
"constructor",
",",
"\"_stub_seen\"",
",",
"None",
")",
"if",
"seen",
"is",
"None",
":",
"seen",
"=",
"constructor",
".",
"_stub_seen",
"=",
"set",
"(",
")",
"i... | 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 config... | 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 config... | [
"def",
"load_yaml",
"(",
"fname",
")",
":",
"yaml",
"=",
"YAML",
"(",
"typ",
"=",
"\"safe\"",
")",
"# Compat with HASS",
"yaml",
".",
"allow_duplicate_keys",
"=",
"True",
"# Stub HASS constructors",
"HassSafeConstructor",
".",
"name",
"=",
"fname",
"yaml",
".",
... | 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_... | 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_... | [
"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:///{}\"",
".",
"... | 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",
"d... | 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 d... | 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 d... | [
"def",
"sqlalch_datetime",
"(",
"dt",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"str",
")",
":",
"return",
"datetime",
".",
"strptime",
"(",
"dt",
",",
"\"%Y-%m-%d %H:%M:%S.%f\"",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"UTC",
")",
"if",
"dt",
"."... | 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",
")",
... | 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",
"(",... | 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",
... | 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.
... | 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.
... | [
"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 ... | 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')
... | 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')
... | [
"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')... | 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.isfloa... | 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.isfloa... | [
"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_d... | 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]
... | 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]
... | [
"def",
"correlations",
"(",
"self",
")",
":",
"corr_df",
"=",
"self",
".",
"_sensors_num_df",
".",
"corr",
"(",
")",
"corr_names",
"=",
"[",
"]",
"corrs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"corr_df",
".",
"index",
")",
")",... | 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))
... | 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))
... | [
"def",
"plot",
"(",
"self",
",",
"entities",
":",
"List",
"[",
"str",
"]",
")",
":",
"ax",
"=",
"self",
".",
"_sensors_num_df",
"[",
"entities",
"]",
".",
"plot",
"(",
"figsize",
"=",
"[",
"12",
",",
"6",
"]",
")",
"ax",
".",
"legend",
"(",
"lo... | 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
resa... | 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
resa... | [
"def",
"plot",
"(",
"self",
",",
"entity",
")",
":",
"df",
"=",
"self",
".",
"_binary_df",
"[",
"[",
"entity",
"]",
"]",
"resampled",
"=",
"df",
".",
"resample",
"(",
"\"s\"",
")",
".",
"ffill",
"(",
")",
"# Sample at seconds and ffill",
"resampled",
"... | 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 =... | 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 =... | [
"def",
"is_sf_database",
"(",
"db",
",",
"model",
"=",
"None",
")",
":",
"from",
"django",
".",
"db",
"import",
"connections",
"if",
"db",
"is",
"None",
":",
"return",
"getattr",
"(",
"model",
",",
"'_salesforce_object'",
",",
"False",
")",
"engine",
"="... | 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 ma... | 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 ma... | [
"def",
"allow_migrate",
"(",
"self",
",",
"db",
",",
"app_label",
",",
"model_name",
"=",
"None",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model_name",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"app_label",
",",
"model_name",
")",
"else",
":",
... | 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=se... | 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=se... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"if",
"router",
".",
"is_sf_database",
"(",
"self",
".",
"db",
")",
":",
"q",
"=",
"models_sql_query",
".",
"SalesforceQuery",
"(",
"self",
".",
"model",
",",
"where",
"=",
"compiler",
".",
"SalesforceWhereNode... | 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",... | 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",... | [
"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",
"# ... | 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 = []... | 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 = []... | [
"def",
"extract_values",
"(",
"query",
")",
":",
"# pylint",
"if",
"isinstance",
"(",
"query",
",",
"subqueries",
".",
"UpdateQuery",
")",
":",
"row",
"=",
"query",
".",
"values",
"return",
"extract_values_inner",
"(",
"row",
",",
"query",
")",
"if",
"isin... | 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_dja... | 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_dja... | [
"def",
"execute",
"(",
"self",
",",
"q",
",",
"args",
"=",
"(",
")",
")",
":",
"# pylint:disable=too-many-branches",
"self",
".",
"rowcount",
"=",
"None",
"response",
"=",
"None",
"if",
"self",
".",
"query",
"is",
"None",
":",
"self",
".",
"execute_selec... | 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)... | 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)... | [
"def",
"execute_django",
"(",
"self",
",",
"soql",
",",
"args",
"=",
"(",
")",
")",
":",
"response",
"=",
"None",
"sqltype",
"=",
"soql",
".",
"split",
"(",
"None",
",",
"1",
")",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"if",
"isinstance",
"(",
... | 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
... | 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
... | [
"def",
"get_pks_from_query",
"(",
"self",
",",
"query",
")",
":",
"where",
"=",
"query",
".",
"where",
"sql",
"=",
"None",
"if",
"where",
".",
"connector",
"==",
"'AND'",
"and",
"not",
"where",
".",
"negated",
"and",
"len",
"(",
"where",
".",
"children... | 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:
... | 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:
... | [
"def",
"fix_international",
"(",
"text",
")",
":",
"class",
"SmartInternational",
"(",
"str",
")",
":",
"def",
"__new__",
"(",
"cls",
",",
"text",
")",
":",
"return",
"str",
".",
"__new__",
"(",
"cls",
",",
"text",
")",
"def",
"endswith",
"(",
"self",
... | 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.
"""
... | 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.
"""
... | [
"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-argumen... | 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 op... | 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 op... | [
"def",
"get_tagged_version",
"(",
")",
":",
"with",
"open",
"(",
"relative_path",
"(",
"'salesforce/__init__.py'",
")",
",",
"'r'",
")",
"as",
"fd",
":",
"version",
"=",
"re",
".",
"search",
"(",
"r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]'",
",",
"fd",
".... | 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(k... | 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(k... | [
"def",
"dynamic_start",
"(",
"self",
",",
"access_token",
",",
"instance_url",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"dynamic",
"=",
"{",
"'access_token'",
":",
"str",
"(",
"access_token",
")",
",",
"'instance_url'",
":",
"str",
"(",
... | 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"'[^... | 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"'[^... | [
"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",
"="... | 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
... | 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
... | [
"def",
"subst_quoted_strings",
"(",
"sql",
",",
"params",
")",
":",
"parts",
"=",
"sql",
".",
"split",
"(",
"'@'",
")",
"params_dont_match",
"=",
"\"number of parameters doesn' match the transformed query\"",
"assert",
"len",
"(",
"parts",
")",
"==",
"len",
"(",
... | 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 ... | 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 ... | [
"def",
"find_closing_parenthesis",
"(",
"sql",
",",
"startpos",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'[()]'",
")",
"level",
"=",
"0",
"opening",
"=",
"[",
"]",
"for",
"match",
"in",
"pattern",
".",
"finditer",
"(",
"sql",
",",
"startp... | 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)
whi... | 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)
whi... | [
"def",
"split_subquery",
"(",
"sql",
")",
":",
"sql",
",",
"params",
"=",
"mark_quoted_strings",
"(",
"sql",
")",
"sql",
"=",
"simplify_expression",
"(",
"sql",
")",
"_",
"=",
"params",
"# NOQA",
"start",
"=",
"0",
"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 afte... | 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 afte... | [
"def",
"simplify_expression",
"(",
"txt",
")",
":",
"minimal",
"=",
"re",
".",
"sub",
"(",
"r'\\s'",
",",
"' '",
",",
"re",
".",
"sub",
"(",
"r'\\s(?=\\W)'",
",",
"''",
",",
"re",
".",
"sub",
"(",
"r'(?<=\\W)\\s'",
",",
"''",
",",
"txt",
".",
"stri... | 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 low... | 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 low... | [
"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",
"(",
")",
":",
... | 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... | 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... | [
"def",
"parse_rest_response",
"(",
"self",
",",
"records",
",",
"rowcount",
",",
"row_type",
"=",
"list",
")",
":",
"if",
"self",
".",
"is_plain_count",
":",
"# result of \"SELECT COUNT() FROM ... WHERE ...\"",
"assert",
"list",
"(",
"records",
")",
"==",
"[",
"... | 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),
usua... | 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),
usua... | [
"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",
"(",
... | 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 ver... | [
"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 verbosi... | 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 verbosi... | [
"def",
"prepare_exception",
"(",
"obj",
",",
"messages",
"=",
"None",
",",
"response",
"=",
"None",
",",
"verbs",
"=",
"None",
")",
":",
"# pylint:disable=too-many-branches",
"verbs",
"=",
"set",
"(",
"verbs",
"or",
"[",
"]",
")",
"known_options",
"=",
"["... | 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... | 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... | [
"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.