partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Widget._comm_changed
Called when the comm is changed.
ipywidgets/widgets/widget.py
def _comm_changed(self, change): """Called when the comm is changed.""" if change['new'] is None: return self._model_id = self.model_id self.comm.on_msg(self._handle_msg) Widget.widgets[self.model_id] = self
def _comm_changed(self, change): """Called when the comm is changed.""" if change['new'] is None: return self._model_id = self.model_id self.comm.on_msg(self._handle_msg) Widget.widgets[self.model_id] = self
[ "Called", "when", "the", "comm", "is", "changed", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L440-L447
[ "def", "_comm_changed", "(", "self", ",", "change", ")", ":", "if", "change", "[", "'new'", "]", "is", "None", ":", "return", "self", ".", "_model_id", "=", "self", ".", "model_id", "self", ".", "comm", ".", "on_msg", "(", "self", ".", "_handle_msg", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget.close
Close method. Closes the underlying comm. When the comm is closed, all of the widget views are automatically removed from the front-end.
ipywidgets/widgets/widget.py
def close(self): """Close method. Closes the underlying comm. When the comm is closed, all of the widget views are automatically removed from the front-end.""" if self.comm is not None: Widget.widgets.pop(self.model_id, None) self.comm.close() ...
def close(self): """Close method. Closes the underlying comm. When the comm is closed, all of the widget views are automatically removed from the front-end.""" if self.comm is not None: Widget.widgets.pop(self.model_id, None) self.comm.close() ...
[ "Close", "method", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L460-L470
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "comm", "is", "not", "None", ":", "Widget", ".", "widgets", ".", "pop", "(", "self", ".", "model_id", ",", "None", ")", "self", ".", "comm", ".", "close", "(", ")", "self", ".", "comm", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget.send_state
Sends the widget state, or a piece of it, to the front-end, if it exists. Parameters ---------- key : unicode, or iterable (optional) A single property's name or iterable of property names to sync with the front-end.
ipywidgets/widgets/widget.py
def send_state(self, key=None): """Sends the widget state, or a piece of it, to the front-end, if it exists. Parameters ---------- key : unicode, or iterable (optional) A single property's name or iterable of property names to sync with the front-end. """ sta...
def send_state(self, key=None): """Sends the widget state, or a piece of it, to the front-end, if it exists. Parameters ---------- key : unicode, or iterable (optional) A single property's name or iterable of property names to sync with the front-end. """ sta...
[ "Sends", "the", "widget", "state", "or", "a", "piece", "of", "it", "to", "the", "front", "-", "end", "if", "it", "exists", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L472-L488
[ "def", "send_state", "(", "self", ",", "key", "=", "None", ")", ":", "state", "=", "self", ".", "get_state", "(", "key", "=", "key", ")", "if", "len", "(", "state", ")", ">", "0", ":", "if", "self", ".", "_property_lock", ":", "# we need to keep this...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget.get_state
Gets the widget state, or a piece of it. Parameters ---------- key : unicode or iterable (optional) A single property's name or iterable of property names to get. Returns ------- state : dict of states metadata : dict metadata for each fi...
ipywidgets/widgets/widget.py
def get_state(self, key=None, drop_defaults=False): """Gets the widget state, or a piece of it. Parameters ---------- key : unicode or iterable (optional) A single property's name or iterable of property names to get. Returns ------- state : dict of ...
def get_state(self, key=None, drop_defaults=False): """Gets the widget state, or a piece of it. Parameters ---------- key : unicode or iterable (optional) A single property's name or iterable of property names to get. Returns ------- state : dict of ...
[ "Gets", "the", "widget", "state", "or", "a", "piece", "of", "it", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L491-L522
[ "def", "get_state", "(", "self", ",", "key", "=", "None", ",", "drop_defaults", "=", "False", ")", ":", "if", "key", "is", "None", ":", "keys", "=", "self", ".", "keys", "elif", "isinstance", "(", "key", ",", "string_types", ")", ":", "keys", "=", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget.set_state
Called when a state is received from the front-end.
ipywidgets/widgets/widget.py
def set_state(self, sync_data): """Called when a state is received from the front-end.""" # The order of these context managers is important. Properties must # be locked when the hold_trait_notification context manager is # released and notifications are fired. with self._lock_pr...
def set_state(self, sync_data): """Called when a state is received from the front-end.""" # The order of these context managers is important. Properties must # be locked when the hold_trait_notification context manager is # released and notifications are fired. with self._lock_pr...
[ "Called", "when", "a", "state", "is", "received", "from", "the", "front", "-", "end", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L534-L544
[ "def", "set_state", "(", "self", ",", "sync_data", ")", ":", "# The order of these context managers is important. Properties must", "# be locked when the hold_trait_notification context manager is", "# released and notifications are fired.", "with", "self", ".", "_lock_property", "(", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget.on_msg
(Un)Register a custom msg receive callback. Parameters ---------- callback: callable callback will be passed three arguments when a message arrives:: callback(widget, content, buffers) remove: bool True if the callback should be unregistered.
ipywidgets/widgets/widget.py
def on_msg(self, callback, remove=False): """(Un)Register a custom msg receive callback. Parameters ---------- callback: callable callback will be passed three arguments when a message arrives:: callback(widget, content, buffers) remove: bool ...
def on_msg(self, callback, remove=False): """(Un)Register a custom msg receive callback. Parameters ---------- callback: callable callback will be passed three arguments when a message arrives:: callback(widget, content, buffers) remove: bool ...
[ "(", "Un", ")", "Register", "a", "custom", "msg", "receive", "callback", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L558-L570
[ "def", "on_msg", "(", "self", ",", "callback", ",", "remove", "=", "False", ")", ":", "self", ".", "_msg_callbacks", ".", "register_callback", "(", "callback", ",", "remove", "=", "remove", ")" ]
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget.on_displayed
(Un)Register a widget displayed callback. Parameters ---------- callback: method handler Must have a signature of:: callback(widget, **kwargs) kwargs from display are passed through without modification. remove: bool True if the call...
ipywidgets/widgets/widget.py
def on_displayed(self, callback, remove=False): """(Un)Register a widget displayed callback. Parameters ---------- callback: method handler Must have a signature of:: callback(widget, **kwargs) kwargs from display are passed through without modi...
def on_displayed(self, callback, remove=False): """(Un)Register a widget displayed callback. Parameters ---------- callback: method handler Must have a signature of:: callback(widget, **kwargs) kwargs from display are passed through without modi...
[ "(", "Un", ")", "Register", "a", "widget", "displayed", "callback", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L572-L585
[ "def", "on_displayed", "(", "self", ",", "callback", ",", "remove", "=", "False", ")", ":", "self", ".", "_display_callbacks", ".", "register_callback", "(", "callback", ",", "remove", "=", "remove", ")" ]
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget.add_traits
Dynamically add trait attributes to the Widget.
ipywidgets/widgets/widget.py
def add_traits(self, **traits): """Dynamically add trait attributes to the Widget.""" super(Widget, self).add_traits(**traits) for name, trait in traits.items(): if trait.get_metadata('sync'): self.keys.append(name) self.send_state(name)
def add_traits(self, **traits): """Dynamically add trait attributes to the Widget.""" super(Widget, self).add_traits(**traits) for name, trait in traits.items(): if trait.get_metadata('sync'): self.keys.append(name) self.send_state(name)
[ "Dynamically", "add", "trait", "attributes", "to", "the", "Widget", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L587-L593
[ "def", "add_traits", "(", "self", ",", "*", "*", "traits", ")", ":", "super", "(", "Widget", ",", "self", ")", ".", "add_traits", "(", "*", "*", "traits", ")", "for", "name", ",", "trait", "in", "traits", ".", "items", "(", ")", ":", "if", "trait...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget.notify_change
Called when a property has changed.
ipywidgets/widgets/widget.py
def notify_change(self, change): """Called when a property has changed.""" # Send the state to the frontend before the user-registered callbacks # are called. name = change['name'] if self.comm is not None and self.comm.kernel is not None: # Make sure this isn't infor...
def notify_change(self, change): """Called when a property has changed.""" # Send the state to the frontend before the user-registered callbacks # are called. name = change['name'] if self.comm is not None and self.comm.kernel is not None: # Make sure this isn't infor...
[ "Called", "when", "a", "property", "has", "changed", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L595-L605
[ "def", "notify_change", "(", "self", ",", "change", ")", ":", "# Send the state to the frontend before the user-registered callbacks", "# are called.", "name", "=", "change", "[", "'name'", "]", "if", "self", ".", "comm", "is", "not", "None", "and", "self", ".", "...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget.hold_sync
Hold syncing any state until the outermost context manager exits
ipywidgets/widgets/widget.py
def hold_sync(self): """Hold syncing any state until the outermost context manager exits""" if self._holding_sync is True: yield else: try: self._holding_sync = True yield finally: self._holding_sync = False ...
def hold_sync(self): """Hold syncing any state until the outermost context manager exits""" if self._holding_sync is True: yield else: try: self._holding_sync = True yield finally: self._holding_sync = False ...
[ "Hold", "syncing", "any", "state", "until", "the", "outermost", "context", "manager", "exits" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L629-L640
[ "def", "hold_sync", "(", "self", ")", ":", "if", "self", ".", "_holding_sync", "is", "True", ":", "yield", "else", ":", "try", ":", "self", ".", "_holding_sync", "=", "True", "yield", "finally", ":", "self", ".", "_holding_sync", "=", "False", "self", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget._should_send_property
Check the property lock (property_lock)
ipywidgets/widgets/widget.py
def _should_send_property(self, key, value): """Check the property lock (property_lock)""" to_json = self.trait_metadata(key, 'to_json', self._trait_to_json) if key in self._property_lock: # model_state, buffer_paths, buffers split_value = _remove_buffers({ key: to_json(v...
def _should_send_property(self, key, value): """Check the property lock (property_lock)""" to_json = self.trait_metadata(key, 'to_json', self._trait_to_json) if key in self._property_lock: # model_state, buffer_paths, buffers split_value = _remove_buffers({ key: to_json(v...
[ "Check", "the", "property", "lock", "(", "property_lock", ")" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L642-L660
[ "def", "_should_send_property", "(", "self", ",", "key", ",", "value", ")", ":", "to_json", "=", "self", ".", "trait_metadata", "(", "key", ",", "'to_json'", ",", "self", ".", "_trait_to_json", ")", "if", "key", "in", "self", ".", "_property_lock", ":", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget._handle_msg
Called when a msg is received from the front-end
ipywidgets/widgets/widget.py
def _handle_msg(self, msg): """Called when a msg is received from the front-end""" data = msg['content']['data'] method = data['method'] if method == 'update': if 'state' in data: state = data['state'] if 'buffer_paths' in data: ...
def _handle_msg(self, msg): """Called when a msg is received from the front-end""" data = msg['content']['data'] method = data['method'] if method == 'update': if 'state' in data: state = data['state'] if 'buffer_paths' in data: ...
[ "Called", "when", "a", "msg", "is", "received", "from", "the", "front", "-", "end" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L664-L687
[ "def", "_handle_msg", "(", "self", ",", "msg", ")", ":", "data", "=", "msg", "[", "'content'", "]", "[", "'data'", "]", "method", "=", "data", "[", "'method'", "]", "if", "method", "==", "'update'", ":", "if", "'state'", "in", "data", ":", "state", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget._ipython_display_
Called when `IPython.display.display` is called on the widget.
ipywidgets/widgets/widget.py
def _ipython_display_(self, **kwargs): """Called when `IPython.display.display` is called on the widget.""" plaintext = repr(self) if len(plaintext) > 110: plaintext = plaintext[:110] + '…' data = { 'text/plain': plaintext, } if self._view_name is...
def _ipython_display_(self, **kwargs): """Called when `IPython.display.display` is called on the widget.""" plaintext = repr(self) if len(plaintext) > 110: plaintext = plaintext[:110] + '…' data = { 'text/plain': plaintext, } if self._view_name is...
[ "Called", "when", "IPython", ".", "display", ".", "display", "is", "called", "on", "the", "widget", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L707-L730
[ "def", "_ipython_display_", "(", "self", ",", "*", "*", "kwargs", ")", ":", "plaintext", "=", "repr", "(", "self", ")", "if", "len", "(", "plaintext", ")", ">", "110", ":", "plaintext", "=", "plaintext", "[", ":", "110", "]", "+", "'…'", "data", "=...
36fe37594cd5a268def228709ca27e37b99ac606
train
Widget._send
Sends a message to the model in the front-end.
ipywidgets/widgets/widget.py
def _send(self, msg, buffers=None): """Sends a message to the model in the front-end.""" if self.comm is not None and self.comm.kernel is not None: self.comm.send(data=msg, buffers=buffers)
def _send(self, msg, buffers=None): """Sends a message to the model in the front-end.""" if self.comm is not None and self.comm.kernel is not None: self.comm.send(data=msg, buffers=buffers)
[ "Sends", "a", "message", "to", "the", "model", "in", "the", "front", "-", "end", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L732-L735
[ "def", "_send", "(", "self", ",", "msg", ",", "buffers", "=", "None", ")", ":", "if", "self", ".", "comm", "is", "not", "None", "and", "self", ".", "comm", ".", "kernel", "is", "not", "None", ":", "self", ".", "comm", ".", "send", "(", "data", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
_int_doc
Add int docstring template to class init.
ipywidgets/widgets/widget_int.py
def _int_doc(cls): """Add int docstring template to class init.""" def __init__(self, value=None, **kwargs): if value is not None: kwargs['value'] = value super(cls, self).__init__(**kwargs) __init__.__doc__ = _int_doc_t cls.__init__ = __init__ return cls
def _int_doc(cls): """Add int docstring template to class init.""" def __init__(self, value=None, **kwargs): if value is not None: kwargs['value'] = value super(cls, self).__init__(**kwargs) __init__.__doc__ = _int_doc_t cls.__init__ = __init__ return cls
[ "Add", "int", "docstring", "template", "to", "class", "init", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_int.py#L39-L48
[ "def", "_int_doc", "(", "cls", ")", ":", "def", "__init__", "(", "self", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "value", "is", "not", "None", ":", "kwargs", "[", "'value'", "]", "=", "value", "super", "(", "cls", ",",...
36fe37594cd5a268def228709ca27e37b99ac606
train
_bounded_int_doc
Add bounded int docstring template to class init.
ipywidgets/widgets/widget_int.py
def _bounded_int_doc(cls): """Add bounded int docstring template to class init.""" def __init__(self, value=None, min=None, max=None, step=None, **kwargs): if value is not None: kwargs['value'] = value if min is not None: kwargs['min'] = min if max is not None: ...
def _bounded_int_doc(cls): """Add bounded int docstring template to class init.""" def __init__(self, value=None, min=None, max=None, step=None, **kwargs): if value is not None: kwargs['value'] = value if min is not None: kwargs['min'] = min if max is not None: ...
[ "Add", "bounded", "int", "docstring", "template", "to", "class", "init", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_int.py#L50-L65
[ "def", "_bounded_int_doc", "(", "cls", ")", ":", "def", "__init__", "(", "self", ",", "value", "=", "None", ",", "min", "=", "None", ",", "max", "=", "None", ",", "step", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "value", "is", "not",...
36fe37594cd5a268def228709ca27e37b99ac606
train
datetime_to_json
Serialize a Python datetime object to json. Instantiating a JavaScript Date object with a string assumes that the string is a UTC string, while instantiating it with constructor arguments assumes that it's in local time: >>> cdate = new Date('2015-05-12') Mon May 11 2015 20:00:00 GMT-0400 (Eastern...
ipywidgets/widgets/trait_types.py
def datetime_to_json(pydt, manager): """Serialize a Python datetime object to json. Instantiating a JavaScript Date object with a string assumes that the string is a UTC string, while instantiating it with constructor arguments assumes that it's in local time: >>> cdate = new Date('2015-05-12') ...
def datetime_to_json(pydt, manager): """Serialize a Python datetime object to json. Instantiating a JavaScript Date object with a string assumes that the string is a UTC string, while instantiating it with constructor arguments assumes that it's in local time: >>> cdate = new Date('2015-05-12') ...
[ "Serialize", "a", "Python", "datetime", "object", "to", "json", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/trait_types.py#L69-L95
[ "def", "datetime_to_json", "(", "pydt", ",", "manager", ")", ":", "if", "pydt", "is", "None", ":", "return", "None", "else", ":", "return", "dict", "(", "year", "=", "pydt", ".", "year", ",", "month", "=", "pydt", ".", "month", "-", "1", ",", "# Mo...
36fe37594cd5a268def228709ca27e37b99ac606
train
datetime_from_json
Deserialize a Python datetime object from json.
ipywidgets/widgets/trait_types.py
def datetime_from_json(js, manager): """Deserialize a Python datetime object from json.""" if js is None: return None else: return dt.datetime( js['year'], js['month'] + 1, # Months are 1-based in Python js['date'], js['hours'], js...
def datetime_from_json(js, manager): """Deserialize a Python datetime object from json.""" if js is None: return None else: return dt.datetime( js['year'], js['month'] + 1, # Months are 1-based in Python js['date'], js['hours'], js...
[ "Deserialize", "a", "Python", "datetime", "object", "from", "json", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/trait_types.py#L98-L111
[ "def", "datetime_from_json", "(", "js", ",", "manager", ")", ":", "if", "js", "is", "None", ":", "return", "None", "else", ":", "return", "dt", ".", "datetime", "(", "js", "[", "'year'", "]", ",", "js", "[", "'month'", "]", "+", "1", ",", "# Months...
36fe37594cd5a268def228709ca27e37b99ac606
train
date_to_json
Serialize a Python date object. Attributes of this dictionary are to be passed to the JavaScript Date constructor.
ipywidgets/widgets/trait_types.py
def date_to_json(pydate, manager): """Serialize a Python date object. Attributes of this dictionary are to be passed to the JavaScript Date constructor. """ if pydate is None: return None else: return dict( year=pydate.year, month=pydate.month - 1, # Mon...
def date_to_json(pydate, manager): """Serialize a Python date object. Attributes of this dictionary are to be passed to the JavaScript Date constructor. """ if pydate is None: return None else: return dict( year=pydate.year, month=pydate.month - 1, # Mon...
[ "Serialize", "a", "Python", "date", "object", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/trait_types.py#L119-L132
[ "def", "date_to_json", "(", "pydate", ",", "manager", ")", ":", "if", "pydate", "is", "None", ":", "return", "None", "else", ":", "return", "dict", "(", "year", "=", "pydate", ".", "year", ",", "month", "=", "pydate", ".", "month", "-", "1", ",", "...
36fe37594cd5a268def228709ca27e37b99ac606
train
_find_widget_refs_by_state
Find references to other widgets in a widget's state
ipywidgets/embed.py
def _find_widget_refs_by_state(widget, state): """Find references to other widgets in a widget's state""" # Copy keys to allow changes to state during iteration: keys = tuple(state.keys()) for key in keys: value = getattr(widget, key) # Trivial case: Direct references to other widgets: ...
def _find_widget_refs_by_state(widget, state): """Find references to other widgets in a widget's state""" # Copy keys to allow changes to state during iteration: keys = tuple(state.keys()) for key in keys: value = getattr(widget, key) # Trivial case: Direct references to other widgets: ...
[ "Find", "references", "to", "other", "widgets", "in", "a", "widget", "s", "state" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/embed.py#L95-L113
[ "def", "_find_widget_refs_by_state", "(", "widget", ",", "state", ")", ":", "# Copy keys to allow changes to state during iteration:", "keys", "=", "tuple", "(", "state", ".", "keys", "(", ")", ")", "for", "key", "in", "keys", ":", "value", "=", "getattr", "(", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
_get_recursive_state
Gets the embed state of a widget, and all other widgets it refers to as well
ipywidgets/embed.py
def _get_recursive_state(widget, store=None, drop_defaults=False): """Gets the embed state of a widget, and all other widgets it refers to as well""" if store is None: store = dict() state = widget._get_embed_state(drop_defaults=drop_defaults) store[widget.model_id] = state # Loop over all ...
def _get_recursive_state(widget, store=None, drop_defaults=False): """Gets the embed state of a widget, and all other widgets it refers to as well""" if store is None: store = dict() state = widget._get_embed_state(drop_defaults=drop_defaults) store[widget.model_id] = state # Loop over all ...
[ "Gets", "the", "embed", "state", "of", "a", "widget", "and", "all", "other", "widgets", "it", "refers", "to", "as", "well" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/embed.py#L116-L127
[ "def", "_get_recursive_state", "(", "widget", ",", "store", "=", "None", ",", "drop_defaults", "=", "False", ")", ":", "if", "store", "is", "None", ":", "store", "=", "dict", "(", ")", "state", "=", "widget", ".", "_get_embed_state", "(", "drop_defaults", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
add_resolved_links
Adds the state of any link models between two models in store
ipywidgets/embed.py
def add_resolved_links(store, drop_defaults): """Adds the state of any link models between two models in store""" for widget_id, widget in Widget.widgets.items(): # go over all widgets if isinstance(widget, Link) and widget_id not in store: if widget.source[0].model_id in store and widget.ta...
def add_resolved_links(store, drop_defaults): """Adds the state of any link models between two models in store""" for widget_id, widget in Widget.widgets.items(): # go over all widgets if isinstance(widget, Link) and widget_id not in store: if widget.source[0].model_id in store and widget.ta...
[ "Adds", "the", "state", "of", "any", "link", "models", "between", "two", "models", "in", "store" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/embed.py#L130-L135
[ "def", "add_resolved_links", "(", "store", ",", "drop_defaults", ")", ":", "for", "widget_id", ",", "widget", "in", "Widget", ".", "widgets", ".", "items", "(", ")", ":", "# go over all widgets", "if", "isinstance", "(", "widget", ",", "Link", ")", "and", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
dependency_state
Get the state of all widgets specified, and their dependencies. This uses a simple dependency finder, including: - any widget directly referenced in the state of an included widget - any widget in a list/tuple attribute in the state of an included widget - any widget in a dict attribute in the state...
ipywidgets/embed.py
def dependency_state(widgets, drop_defaults=True): """Get the state of all widgets specified, and their dependencies. This uses a simple dependency finder, including: - any widget directly referenced in the state of an included widget - any widget in a list/tuple attribute in the state of an included...
def dependency_state(widgets, drop_defaults=True): """Get the state of all widgets specified, and their dependencies. This uses a simple dependency finder, including: - any widget directly referenced in the state of an included widget - any widget in a list/tuple attribute in the state of an included...
[ "Get", "the", "state", "of", "all", "widgets", "specified", "and", "their", "dependencies", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/embed.py#L138-L181
[ "def", "dependency_state", "(", "widgets", ",", "drop_defaults", "=", "True", ")", ":", "# collect the state of all relevant widgets", "if", "widgets", "is", "None", ":", "# Get state of all widgets, no smart resolution needed.", "state", "=", "Widget", ".", "get_manager_st...
36fe37594cd5a268def228709ca27e37b99ac606
train
embed_data
Gets data for embedding. Use this to get the raw data for embedding if you have special formatting needs. Parameters ---------- {views_attribute} drop_defaults: boolean Whether to drop default values from the widget states. state: dict or None (default) The state to include...
ipywidgets/embed.py
def embed_data(views, drop_defaults=True, state=None): """Gets data for embedding. Use this to get the raw data for embedding if you have special formatting needs. Parameters ---------- {views_attribute} drop_defaults: boolean Whether to drop default values from the widget states. ...
def embed_data(views, drop_defaults=True, state=None): """Gets data for embedding. Use this to get the raw data for embedding if you have special formatting needs. Parameters ---------- {views_attribute} drop_defaults: boolean Whether to drop default values from the widget states. ...
[ "Gets", "data", "for", "embedding", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/embed.py#L185-L228
[ "def", "embed_data", "(", "views", ",", "drop_defaults", "=", "True", ",", "state", "=", "None", ")", ":", "if", "views", "is", "None", ":", "views", "=", "[", "w", "for", "w", "in", "Widget", ".", "widgets", ".", "values", "(", ")", "if", "isinsta...
36fe37594cd5a268def228709ca27e37b99ac606
train
embed_snippet
Return a snippet that can be embedded in an HTML file. Parameters ---------- {views_attribute} {embed_kwargs} Returns ------- A unicode string with an HTML snippet containing several `<script>` tags.
ipywidgets/embed.py
def embed_snippet(views, drop_defaults=True, state=None, indent=2, embed_url=None, requirejs=True, cors=True ): """Return a snippet that can be embedded in an HTML file. Parameters -...
def embed_snippet(views, drop_defaults=True, state=None, indent=2, embed_url=None, requirejs=True, cors=True ): """Return a snippet that can be embedded in an HTML file. Parameters -...
[ "Return", "a", "snippet", "that", "can", "be", "embedded", "in", "an", "HTML", "file", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/embed.py#L244-L283
[ "def", "embed_snippet", "(", "views", ",", "drop_defaults", "=", "True", ",", "state", "=", "None", ",", "indent", "=", "2", ",", "embed_url", "=", "None", ",", "requirejs", "=", "True", ",", "cors", "=", "True", ")", ":", "data", "=", "embed_data", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
embed_minimal_html
Write a minimal HTML file with widget views embedded. Parameters ---------- fp: filename or file-like object The file to write the HTML output to. {views_attribute} title: title of the html page. template: Template in which to embed the widget state. This should be a Python stri...
ipywidgets/embed.py
def embed_minimal_html(fp, views, title=u'IPyWidget export', template=None, **kwargs): """Write a minimal HTML file with widget views embedded. Parameters ---------- fp: filename or file-like object The file to write the HTML output to. {views_attribute} title: title of the html page. ...
def embed_minimal_html(fp, views, title=u'IPyWidget export', template=None, **kwargs): """Write a minimal HTML file with widget views embedded. Parameters ---------- fp: filename or file-like object The file to write the HTML output to. {views_attribute} title: title of the html page. ...
[ "Write", "a", "minimal", "HTML", "file", "with", "widget", "views", "embedded", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/embed.py#L287-L319
[ "def", "embed_minimal_html", "(", "fp", ",", "views", ",", "title", "=", "u'IPyWidget export'", ",", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "snippet", "=", "embed_snippet", "(", "views", ",", "*", "*", "kwargs", ")", "values", "=", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
_make_options
Standardize the options tuple format. The returned tuple should be in the format (('label', value), ('label', value), ...). The input can be * an iterable of (label, value) pairs * an iterable of values, and labels will be generated
ipywidgets/widgets/widget_selection.py
def _make_options(x): """Standardize the options tuple format. The returned tuple should be in the format (('label', value), ('label', value), ...). The input can be * an iterable of (label, value) pairs * an iterable of values, and labels will be generated """ # Check if x is a mapping of...
def _make_options(x): """Standardize the options tuple format. The returned tuple should be in the format (('label', value), ('label', value), ...). The input can be * an iterable of (label, value) pairs * an iterable of values, and labels will be generated """ # Check if x is a mapping of...
[ "Standardize", "the", "options", "tuple", "format", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_selection.py#L108-L131
[ "def", "_make_options", "(", "x", ")", ":", "# Check if x is a mapping of labels to values", "if", "isinstance", "(", "x", ",", "Mapping", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"Support for mapping types has been deprecated and will be dropped in a...
36fe37594cd5a268def228709ca27e37b99ac606
train
findvalue
A function that uses the compare function to return a value from the list.
ipywidgets/widgets/widget_selection.py
def findvalue(array, value, compare = lambda x, y: x == y): "A function that uses the compare function to return a value from the list." try: return next(x for x in array if compare(x, value)) except StopIteration: raise ValueError('%r not in array'%value)
def findvalue(array, value, compare = lambda x, y: x == y): "A function that uses the compare function to return a value from the list." try: return next(x for x in array if compare(x, value)) except StopIteration: raise ValueError('%r not in array'%value)
[ "A", "function", "that", "uses", "the", "compare", "function", "to", "return", "a", "value", "from", "the", "list", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_selection.py#L133-L138
[ "def", "findvalue", "(", "array", ",", "value", ",", "compare", "=", "lambda", "x", ",", "y", ":", "x", "==", "y", ")", ":", "try", ":", "return", "next", "(", "x", "for", "x", "in", "array", "if", "compare", "(", "x", ",", "value", ")", ")", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
_Selection._propagate_options
Set the values and labels, and select the first option if we aren't initializing
ipywidgets/widgets/widget_selection.py
def _propagate_options(self, change): "Set the values and labels, and select the first option if we aren't initializing" options = self._options_full self.set_trait('_options_labels', tuple(i[0] for i in options)) self._options_values = tuple(i[1] for i in options) if self._initi...
def _propagate_options(self, change): "Set the values and labels, and select the first option if we aren't initializing" options = self._options_full self.set_trait('_options_labels', tuple(i[0] for i in options)) self._options_values = tuple(i[1] for i in options) if self._initi...
[ "Set", "the", "values", "and", "labels", "and", "select", "the", "first", "option", "if", "we", "aren", "t", "initializing" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_selection.py#L202-L217
[ "def", "_propagate_options", "(", "self", ",", "change", ")", ":", "options", "=", "self", ".", "_options_full", "self", ".", "set_trait", "(", "'_options_labels'", ",", "tuple", "(", "i", "[", "0", "]", "for", "i", "in", "options", ")", ")", "self", "...
36fe37594cd5a268def228709ca27e37b99ac606
train
_Selection._propagate_index
Propagate changes in index to the value and label properties
ipywidgets/widgets/widget_selection.py
def _propagate_index(self, change): "Propagate changes in index to the value and label properties" label = self._options_labels[change.new] if change.new is not None else None value = self._options_values[change.new] if change.new is not None else None if self.label is not label: ...
def _propagate_index(self, change): "Propagate changes in index to the value and label properties" label = self._options_labels[change.new] if change.new is not None else None value = self._options_values[change.new] if change.new is not None else None if self.label is not label: ...
[ "Propagate", "changes", "in", "index", "to", "the", "value", "and", "label", "properties" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_selection.py#L227-L234
[ "def", "_propagate_index", "(", "self", ",", "change", ")", ":", "label", "=", "self", ".", "_options_labels", "[", "change", ".", "new", "]", "if", "change", ".", "new", "is", "not", "None", "else", "None", "value", "=", "self", ".", "_options_values", ...
36fe37594cd5a268def228709ca27e37b99ac606
train
_MultipleSelection._validate_index
Check the range of each proposed index.
ipywidgets/widgets/widget_selection.py
def _validate_index(self, proposal): "Check the range of each proposed index." if all(0 <= i < len(self._options_labels) for i in proposal.value): return proposal.value else: raise TraitError('Invalid selection: index out of bounds')
def _validate_index(self, proposal): "Check the range of each proposed index." if all(0 <= i < len(self._options_labels) for i in proposal.value): return proposal.value else: raise TraitError('Invalid selection: index out of bounds')
[ "Check", "the", "range", "of", "each", "proposed", "index", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_selection.py#L336-L341
[ "def", "_validate_index", "(", "self", ",", "proposal", ")", ":", "if", "all", "(", "0", "<=", "i", "<", "len", "(", "self", ".", "_options_labels", ")", "for", "i", "in", "proposal", ".", "value", ")", ":", "return", "proposal", ".", "value", "else"...
36fe37594cd5a268def228709ca27e37b99ac606
train
_MultipleSelection._validate_value
Replace all values with the actual objects in the options list
ipywidgets/widgets/widget_selection.py
def _validate_value(self, proposal): "Replace all values with the actual objects in the options list" try: return tuple(findvalue(self._options_values, i, self.equals) for i in proposal.value) except ValueError: raise TraitError('Invalid selection: value not found')
def _validate_value(self, proposal): "Replace all values with the actual objects in the options list" try: return tuple(findvalue(self._options_values, i, self.equals) for i in proposal.value) except ValueError: raise TraitError('Invalid selection: value not found')
[ "Replace", "all", "values", "with", "the", "actual", "objects", "in", "the", "options", "list" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_selection.py#L355-L360
[ "def", "_validate_value", "(", "self", ",", "proposal", ")", ":", "try", ":", "return", "tuple", "(", "findvalue", "(", "self", ".", "_options_values", ",", "i", ",", "self", ".", "equals", ")", "for", "i", "in", "proposal", ".", "value", ")", "except"...
36fe37594cd5a268def228709ca27e37b99ac606
train
DOMWidget.add_class
Adds a class to the top level element of the widget. Doesn't add the class if it already exists.
ipywidgets/widgets/domwidget.py
def add_class(self, className): """ Adds a class to the top level element of the widget. Doesn't add the class if it already exists. """ if className not in self._dom_classes: self._dom_classes = list(self._dom_classes) + [className] return self
def add_class(self, className): """ Adds a class to the top level element of the widget. Doesn't add the class if it already exists. """ if className not in self._dom_classes: self._dom_classes = list(self._dom_classes) + [className] return self
[ "Adds", "a", "class", "to", "the", "top", "level", "element", "of", "the", "widget", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/domwidget.py#L20-L28
[ "def", "add_class", "(", "self", ",", "className", ")", ":", "if", "className", "not", "in", "self", ".", "_dom_classes", ":", "self", ".", "_dom_classes", "=", "list", "(", "self", ".", "_dom_classes", ")", "+", "[", "className", "]", "return", "self" ]
36fe37594cd5a268def228709ca27e37b99ac606
train
DOMWidget.remove_class
Removes a class from the top level element of the widget. Doesn't remove the class if it doesn't exist.
ipywidgets/widgets/domwidget.py
def remove_class(self, className): """ Removes a class from the top level element of the widget. Doesn't remove the class if it doesn't exist. """ if className in self._dom_classes: self._dom_classes = [c for c in self._dom_classes if c != className] return s...
def remove_class(self, className): """ Removes a class from the top level element of the widget. Doesn't remove the class if it doesn't exist. """ if className in self._dom_classes: self._dom_classes = [c for c in self._dom_classes if c != className] return s...
[ "Removes", "a", "class", "from", "the", "top", "level", "element", "of", "the", "widget", "." ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/domwidget.py#L30-L38
[ "def", "remove_class", "(", "self", ",", "className", ")", ":", "if", "className", "in", "self", ".", "_dom_classes", ":", "self", ".", "_dom_classes", "=", "[", "c", "for", "c", "in", "self", ".", "_dom_classes", "if", "c", "!=", "className", "]", "re...
36fe37594cd5a268def228709ca27e37b99ac606
train
register_comm_target
Register the jupyter.widget comm target
ipywidgets/__init__.py
def register_comm_target(kernel=None): """Register the jupyter.widget comm target""" if kernel is None: kernel = get_ipython().kernel kernel.comm_manager.register_target('jupyter.widget', Widget.handle_comm_opened)
def register_comm_target(kernel=None): """Register the jupyter.widget comm target""" if kernel is None: kernel = get_ipython().kernel kernel.comm_manager.register_target('jupyter.widget', Widget.handle_comm_opened)
[ "Register", "the", "jupyter", ".", "widget", "comm", "target" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/__init__.py#L36-L40
[ "def", "register_comm_target", "(", "kernel", "=", "None", ")", ":", "if", "kernel", "is", "None", ":", "kernel", "=", "get_ipython", "(", ")", ".", "kernel", "kernel", ".", "comm_manager", ".", "register_target", "(", "'jupyter.widget'", ",", "Widget", ".",...
36fe37594cd5a268def228709ca27e37b99ac606
train
doc_subst
Substitute format strings in class or function docstring
ipywidgets/widgets/docutils.py
def doc_subst(snippets): """ Substitute format strings in class or function docstring """ def decorator(cls): # Strip the snippets to avoid trailing new lines and whitespace stripped_snippets = { key: snippet.strip() for (key, snippet) in snippets.items() } cls.__doc_...
def doc_subst(snippets): """ Substitute format strings in class or function docstring """ def decorator(cls): # Strip the snippets to avoid trailing new lines and whitespace stripped_snippets = { key: snippet.strip() for (key, snippet) in snippets.items() } cls.__doc_...
[ "Substitute", "format", "strings", "in", "class", "or", "function", "docstring" ]
jupyter-widgets/ipywidgets
python
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/docutils.py#L4-L13
[ "def", "doc_subst", "(", "snippets", ")", ":", "def", "decorator", "(", "cls", ")", ":", "# Strip the snippets to avoid trailing new lines and whitespace", "stripped_snippets", "=", "{", "key", ":", "snippet", ".", "strip", "(", ")", "for", "(", "key", ",", "sni...
36fe37594cd5a268def228709ca27e37b99ac606
train
base_uri
Get absolute path to resource, works for dev and for PyInstaller
webview/util.py
def base_uri(relative_path=''): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: if 'pytest' in sys.modules: for arg in reversed(sys.arg...
def base_uri(relative_path=''): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: if 'pytest' in sys.modules: for arg in reversed(sys.arg...
[ "Get", "absolute", "path", "to", "resource", "works", "for", "dev", "and", "for", "PyInstaller" ]
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/util.py#L20-L39
[ "def", "base_uri", "(", "relative_path", "=", "''", ")", ":", "try", ":", "# PyInstaller creates a temp folder and stores path in _MEIPASS", "base_path", "=", "sys", ".", "_MEIPASS", "except", "Exception", ":", "if", "'pytest'", "in", "sys", ".", "modules", ":", "...
fc44d84656e88f83ca496abb50ee75e95540996e
train
parse_file_type
:param file_type: file type string 'description (*.file_extension1;*.file_extension2)' as required by file filter in create_file_dialog :return: (description, file extensions) tuple
webview/util.py
def parse_file_type(file_type): ''' :param file_type: file type string 'description (*.file_extension1;*.file_extension2)' as required by file filter in create_file_dialog :return: (description, file extensions) tuple ''' valid_file_filter = r'^([\w ]+)\((\*(?:\.(?:\w+|\*))*(?:;\*\.\w+)*)\)$' ma...
def parse_file_type(file_type): ''' :param file_type: file type string 'description (*.file_extension1;*.file_extension2)' as required by file filter in create_file_dialog :return: (description, file extensions) tuple ''' valid_file_filter = r'^([\w ]+)\((\*(?:\.(?:\w+|\*))*(?:;\*\.\w+)*)\)$' ma...
[ ":", "param", "file_type", ":", "file", "type", "string", "description", "(", "*", ".", "file_extension1", ";", "*", ".", "file_extension2", ")", "as", "required", "by", "file", "filter", "in", "create_file_dialog", ":", "return", ":", "(", "description", "f...
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/util.py#L49-L60
[ "def", "parse_file_type", "(", "file_type", ")", ":", "valid_file_filter", "=", "r'^([\\w ]+)\\((\\*(?:\\.(?:\\w+|\\*))*(?:;\\*\\.\\w+)*)\\)$'", "match", "=", "re", ".", "search", "(", "valid_file_filter", ",", "file_type", ")", "if", "match", ":", "return", "match", ...
fc44d84656e88f83ca496abb50ee75e95540996e
train
make_unicode
Python 2 and 3 compatibility function that converts a string to Unicode. In case of Unicode, the string is returned unchanged :param string: input string :return: Unicode string
webview/util.py
def make_unicode(string): """ Python 2 and 3 compatibility function that converts a string to Unicode. In case of Unicode, the string is returned unchanged :param string: input string :return: Unicode string """ if sys.version < '3' and isinstance(string, str): return unicode(string....
def make_unicode(string): """ Python 2 and 3 compatibility function that converts a string to Unicode. In case of Unicode, the string is returned unchanged :param string: input string :return: Unicode string """ if sys.version < '3' and isinstance(string, str): return unicode(string....
[ "Python", "2", "and", "3", "compatibility", "function", "that", "converts", "a", "string", "to", "Unicode", ".", "In", "case", "of", "Unicode", "the", "string", "is", "returned", "unchanged", ":", "param", "string", ":", "input", "string", ":", "return", "...
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/util.py#L85-L95
[ "def", "make_unicode", "(", "string", ")", ":", "if", "sys", ".", "version", "<", "'3'", "and", "isinstance", "(", "string", ",", "str", ")", ":", "return", "unicode", "(", "string", ".", "decode", "(", "'utf-8'", ")", ")", "return", "string" ]
fc44d84656e88f83ca496abb50ee75e95540996e
train
BrowserView._add_app_menu
Create a default Cocoa menu that shows 'Services', 'Hide', 'Hide Others', 'Show All', and 'Quit'. Will append the application name to some menu items if it's available.
webview/cocoa.py
def _add_app_menu(self): """ Create a default Cocoa menu that shows 'Services', 'Hide', 'Hide Others', 'Show All', and 'Quit'. Will append the application name to some menu items if it's available. """ # Set the main menu for the application mainMenu = AppKit.NSMe...
def _add_app_menu(self): """ Create a default Cocoa menu that shows 'Services', 'Hide', 'Hide Others', 'Show All', and 'Quit'. Will append the application name to some menu items if it's available. """ # Set the main menu for the application mainMenu = AppKit.NSMe...
[ "Create", "a", "default", "Cocoa", "menu", "that", "shows", "Services", "Hide", "Hide", "Others", "Show", "All", "and", "Quit", ".", "Will", "append", "the", "application", "name", "to", "some", "menu", "items", "if", "it", "s", "available", "." ]
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/cocoa.py#L551-L588
[ "def", "_add_app_menu", "(", "self", ")", ":", "# Set the main menu for the application", "mainMenu", "=", "AppKit", ".", "NSMenu", ".", "alloc", "(", ")", ".", "init", "(", ")", "self", ".", "app", ".", "setMainMenu_", "(", "mainMenu", ")", "# Create an appli...
fc44d84656e88f83ca496abb50ee75e95540996e
train
BrowserView._add_view_menu
Create a default View menu that shows 'Enter Full Screen'.
webview/cocoa.py
def _add_view_menu(self): """ Create a default View menu that shows 'Enter Full Screen'. """ mainMenu = self.app.mainMenu() # Create an View menu and make it a submenu of the main menu viewMenu = AppKit.NSMenu.alloc().init() viewMenu.setTitle_(localization["cocoa...
def _add_view_menu(self): """ Create a default View menu that shows 'Enter Full Screen'. """ mainMenu = self.app.mainMenu() # Create an View menu and make it a submenu of the main menu viewMenu = AppKit.NSMenu.alloc().init() viewMenu.setTitle_(localization["cocoa...
[ "Create", "a", "default", "View", "menu", "that", "shows", "Enter", "Full", "Screen", "." ]
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/cocoa.py#L590-L605
[ "def", "_add_view_menu", "(", "self", ")", ":", "mainMenu", "=", "self", ".", "app", ".", "mainMenu", "(", ")", "# Create an View menu and make it a submenu of the main menu", "viewMenu", "=", "AppKit", ".", "NSMenu", ".", "alloc", "(", ")", ".", "init", "(", ...
fc44d84656e88f83ca496abb50ee75e95540996e
train
BrowserView.nscolor_from_hex
Convert given hex color to NSColor. :hex_string: Hex code of the color as #RGB or #RRGGBB
webview/cocoa.py
def nscolor_from_hex(hex_string): """ Convert given hex color to NSColor. :hex_string: Hex code of the color as #RGB or #RRGGBB """ hex_string = hex_string[1:] # Remove leading hash if len(hex_string) == 3: hex_string = ''.join([c*2 for c in hex_string])...
def nscolor_from_hex(hex_string): """ Convert given hex color to NSColor. :hex_string: Hex code of the color as #RGB or #RRGGBB """ hex_string = hex_string[1:] # Remove leading hash if len(hex_string) == 3: hex_string = ''.join([c*2 for c in hex_string])...
[ "Convert", "given", "hex", "color", "to", "NSColor", "." ]
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/cocoa.py#L621-L640
[ "def", "nscolor_from_hex", "(", "hex_string", ")", ":", "hex_string", "=", "hex_string", "[", "1", ":", "]", "# Remove leading hash", "if", "len", "(", "hex_string", ")", "==", "3", ":", "hex_string", "=", "''", ".", "join", "(", "[", "c", "*", "2", "f...
fc44d84656e88f83ca496abb50ee75e95540996e
train
BrowserView.get_instance
Return a BrowserView instance by the :value of its given :attribute, and None if no match is found.
webview/cocoa.py
def get_instance(attr, value): """ Return a BrowserView instance by the :value of its given :attribute, and None if no match is found. """ for i in list(BrowserView.instances.values()): try: if getattr(i, attr) == value: return i ...
def get_instance(attr, value): """ Return a BrowserView instance by the :value of its given :attribute, and None if no match is found. """ for i in list(BrowserView.instances.values()): try: if getattr(i, attr) == value: return i ...
[ "Return", "a", "BrowserView", "instance", "by", "the", ":", "value", "of", "its", "given", ":", "attribute", "and", "None", "if", "no", "match", "is", "found", "." ]
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/cocoa.py#L643-L655
[ "def", "get_instance", "(", "attr", ",", "value", ")", ":", "for", "i", "in", "list", "(", "BrowserView", ".", "instances", ".", "values", "(", ")", ")", ":", "try", ":", "if", "getattr", "(", "i", ",", "attr", ")", "==", "value", ":", "return", ...
fc44d84656e88f83ca496abb50ee75e95540996e
train
BrowserView.pyobjc_method_signature
Return a PyObjCMethodSignature object for given signature string. :param signature_str: A byte string containing the type encoding for the method signature :return: A method signature object, assignable to attributes like __block_signature__ :rtype: <type objc._method_signature>
webview/cocoa.py
def pyobjc_method_signature(signature_str): """ Return a PyObjCMethodSignature object for given signature string. :param signature_str: A byte string containing the type encoding for the method signature :return: A method signature object, assignable to attributes like __block_signature...
def pyobjc_method_signature(signature_str): """ Return a PyObjCMethodSignature object for given signature string. :param signature_str: A byte string containing the type encoding for the method signature :return: A method signature object, assignable to attributes like __block_signature...
[ "Return", "a", "PyObjCMethodSignature", "object", "for", "given", "signature", "string", "." ]
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/cocoa.py#L700-L709
[ "def", "pyobjc_method_signature", "(", "signature_str", ")", ":", "_objc_so", ".", "PyObjCMethodSignature_WithMetaData", ".", "restype", "=", "ctypes", ".", "py_object", "return", "_objc_so", ".", "PyObjCMethodSignature_WithMetaData", "(", "ctypes", ".", "create_string_bu...
fc44d84656e88f83ca496abb50ee75e95540996e
train
choose_path
Invoke a folder selection dialog here :return:
examples/flask_app/src/backend/server.py
def choose_path(): """ Invoke a folder selection dialog here :return: """ dirs = webview.create_file_dialog(webview.FOLDER_DIALOG) if dirs and len(dirs) > 0: directory = dirs[0] if isinstance(directory, bytes): directory = directory.decode("utf-8") response =...
def choose_path(): """ Invoke a folder selection dialog here :return: """ dirs = webview.create_file_dialog(webview.FOLDER_DIALOG) if dirs and len(dirs) > 0: directory = dirs[0] if isinstance(directory, bytes): directory = directory.decode("utf-8") response =...
[ "Invoke", "a", "folder", "selection", "dialog", "here", ":", "return", ":" ]
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/examples/flask_app/src/backend/server.py#L50-L65
[ "def", "choose_path", "(", ")", ":", "dirs", "=", "webview", ".", "create_file_dialog", "(", "webview", ".", "FOLDER_DIALOG", ")", "if", "dirs", "and", "len", "(", "dirs", ")", ">", "0", ":", "directory", "=", "dirs", "[", "0", "]", "if", "isinstance",...
fc44d84656e88f83ca496abb50ee75e95540996e
train
set_ie_mode
By default hosted IE control emulates IE7 regardless which version of IE is installed. To fix this, a proper value must be set for the executable. See http://msdn.microsoft.com/en-us/library/ee330730%28v=vs.85%29.aspx#browser_emulation for details on this behaviour.
webview/win32_shared.py
def set_ie_mode(): """ By default hosted IE control emulates IE7 regardless which version of IE is installed. To fix this, a proper value must be set for the executable. See http://msdn.microsoft.com/en-us/library/ee330730%28v=vs.85%29.aspx#browser_emulation for details on this behaviour. """ ...
def set_ie_mode(): """ By default hosted IE control emulates IE7 regardless which version of IE is installed. To fix this, a proper value must be set for the executable. See http://msdn.microsoft.com/en-us/library/ee330730%28v=vs.85%29.aspx#browser_emulation for details on this behaviour. """ ...
[ "By", "default", "hosted", "IE", "control", "emulates", "IE7", "regardless", "which", "version", "of", "IE", "is", "installed", ".", "To", "fix", "this", "a", "proper", "value", "must", "be", "set", "for", "the", "executable", ".", "See", "http", ":", "/...
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/win32_shared.py#L11-L74
[ "def", "set_ie_mode", "(", ")", ":", "try", ":", "import", "_winreg", "as", "winreg", "# Python 2", "except", "ImportError", ":", "import", "winreg", "# Python 3", "def", "get_ie_mode", "(", ")", ":", "\"\"\"\n Get the installed version of IE\n :return:\n ...
fc44d84656e88f83ca496abb50ee75e95540996e
train
_api_call
Decorator to call a pywebview API, checking for _webview_ready and raisings appropriate Exceptions on failure.
webview/__init__.py
def _api_call(function): """ Decorator to call a pywebview API, checking for _webview_ready and raisings appropriate Exceptions on failure. """ @wraps(function) def wrapper(*args, **kwargs): try: if not _webview_ready.wait(15): raise Exception('Main window fai...
def _api_call(function): """ Decorator to call a pywebview API, checking for _webview_ready and raisings appropriate Exceptions on failure. """ @wraps(function) def wrapper(*args, **kwargs): try: if not _webview_ready.wait(15): raise Exception('Main window fai...
[ "Decorator", "to", "call", "a", "pywebview", "API", "checking", "for", "_webview_ready", "and", "raisings", "appropriate", "Exceptions", "on", "failure", "." ]
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/__init__.py#L174-L194
[ "def", "_api_call", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "not", "_webview_ready", ".", "wait", "(", "15", ")", ":", "raise", "Excepti...
fc44d84656e88f83ca496abb50ee75e95540996e
train
create_window
Create a web view window using a native GUI. The execution blocks after this function is invoked, so other program logic must be executed in a separate thread. :param title: Window title :param url: URL to load :param width: window width. Default is 800px :param height:window height. Default is 600p...
webview/__init__.py
def create_window(title, url=None, js_api=None, width=800, height=600, resizable=True, fullscreen=False, min_size=(200, 100), strings={}, confirm_quit=False, background_color='#FFFFFF', text_select=False, frameless=False, debug=False): """ Create a web view window using a nat...
def create_window(title, url=None, js_api=None, width=800, height=600, resizable=True, fullscreen=False, min_size=(200, 100), strings={}, confirm_quit=False, background_color='#FFFFFF', text_select=False, frameless=False, debug=False): """ Create a web view window using a nat...
[ "Create", "a", "web", "view", "window", "using", "a", "native", "GUI", ".", "The", "execution", "blocks", "after", "this", "function", "is", "invoked", "so", "other", "program", "logic", "must", "be", "executed", "in", "a", "separate", "thread", ".", ":", ...
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/__init__.py#L197-L242
[ "def", "create_window", "(", "title", ",", "url", "=", "None", ",", "js_api", "=", "None", ",", "width", "=", "800", ",", "height", "=", "600", ",", "resizable", "=", "True", ",", "fullscreen", "=", "False", ",", "min_size", "=", "(", "200", ",", "...
fc44d84656e88f83ca496abb50ee75e95540996e
train
create_file_dialog
Create a file dialog :param dialog_type: Dialog type: open file (OPEN_DIALOG), save file (SAVE_DIALOG), open folder (OPEN_FOLDER). Default is open file. :param directory: Initial directory :param allow_multiple: Allow multiple selection. Default is false. :param save_filename: De...
webview/__init__.py
def create_file_dialog(dialog_type=OPEN_DIALOG, directory='', allow_multiple=False, save_filename='', file_types=()): """ Create a file dialog :param dialog_type: Dialog type: open file (OPEN_DIALOG), save file (SAVE_DIALOG), open folder (OPEN_FOLDER). Default is open file. :para...
def create_file_dialog(dialog_type=OPEN_DIALOG, directory='', allow_multiple=False, save_filename='', file_types=()): """ Create a file dialog :param dialog_type: Dialog type: open file (OPEN_DIALOG), save file (SAVE_DIALOG), open folder (OPEN_FOLDER). Default is open file. :para...
[ "Create", "a", "file", "dialog", ":", "param", "dialog_type", ":", "Dialog", "type", ":", "open", "file", "(", "OPEN_DIALOG", ")", "save", "file", "(", "SAVE_DIALOG", ")", "open", "folder", "(", "OPEN_FOLDER", ")", ".", "Default", "is", "open", "file", "...
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/__init__.py#L246-L266
[ "def", "create_file_dialog", "(", "dialog_type", "=", "OPEN_DIALOG", ",", "directory", "=", "''", ",", "allow_multiple", "=", "False", ",", "save_filename", "=", "''", ",", "file_types", "=", "(", ")", ")", ":", "if", "type", "(", "file_types", ")", "!=", ...
fc44d84656e88f83ca496abb50ee75e95540996e
train
load_html
Load a new content into a previously created WebView window. This function must be invoked after WebView windows is created with create_window(). Otherwise an exception is thrown. :param content: Content to load. :param base_uri: Base URI for resolving links. Default is the directory of the application entr...
webview/__init__.py
def load_html(content, base_uri=base_uri(), uid='master'): """ Load a new content into a previously created WebView window. This function must be invoked after WebView windows is created with create_window(). Otherwise an exception is thrown. :param content: Content to load. :param base_uri: Base UR...
def load_html(content, base_uri=base_uri(), uid='master'): """ Load a new content into a previously created WebView window. This function must be invoked after WebView windows is created with create_window(). Otherwise an exception is thrown. :param content: Content to load. :param base_uri: Base UR...
[ "Load", "a", "new", "content", "into", "a", "previously", "created", "WebView", "window", ".", "This", "function", "must", "be", "invoked", "after", "WebView", "windows", "is", "created", "with", "create_window", "()", ".", "Otherwise", "an", "exception", "is"...
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/__init__.py#L281-L290
[ "def", "load_html", "(", "content", ",", "base_uri", "=", "base_uri", "(", ")", ",", "uid", "=", "'master'", ")", ":", "content", "=", "make_unicode", "(", "content", ")", "gui", ".", "load_html", "(", "content", ",", "base_uri", ",", "uid", ")" ]
fc44d84656e88f83ca496abb50ee75e95540996e
train
evaluate_js
Evaluate given JavaScript code and return the result :param script: The JavaScript code to be evaluated :param uid: uid of the target instance :return: Return value of the evaluated code
webview/__init__.py
def evaluate_js(script, uid='master'): """ Evaluate given JavaScript code and return the result :param script: The JavaScript code to be evaluated :param uid: uid of the target instance :return: Return value of the evaluated code """ escaped_script = 'JSON.stringify(eval("{0}"))'.format(esca...
def evaluate_js(script, uid='master'): """ Evaluate given JavaScript code and return the result :param script: The JavaScript code to be evaluated :param uid: uid of the target instance :return: Return value of the evaluated code """ escaped_script = 'JSON.stringify(eval("{0}"))'.format(esca...
[ "Evaluate", "given", "JavaScript", "code", "and", "return", "the", "result", ":", "param", "script", ":", "The", "JavaScript", "code", "to", "be", "evaluated", ":", "param", "uid", ":", "uid", "of", "the", "target", "instance", ":", "return", ":", "Return"...
r0x0r/pywebview
python
https://github.com/r0x0r/pywebview/blob/fc44d84656e88f83ca496abb50ee75e95540996e/webview/__init__.py#L346-L354
[ "def", "evaluate_js", "(", "script", ",", "uid", "=", "'master'", ")", ":", "escaped_script", "=", "'JSON.stringify(eval(\"{0}\"))'", ".", "format", "(", "escape_string", "(", "script", ")", ")", "return", "gui", ".", "evaluate_js", "(", "escaped_script", ",", ...
fc44d84656e88f83ca496abb50ee75e95540996e
train
NYUDSegDataLayer.setup
Setup data layer according to parameters: - nyud_dir: path to NYUDv2 dir - split: train / val / test - tops: list of tops to output from {color, depth, hha, label} - randomize: load in random order (default: True) - seed: seed for randomization (default: None / current time) ...
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
def setup(self, bottom, top): """ Setup data layer according to parameters: - nyud_dir: path to NYUDv2 dir - split: train / val / test - tops: list of tops to output from {color, depth, hha, label} - randomize: load in random order (default: True) - seed: seed fo...
def setup(self, bottom, top): """ Setup data layer according to parameters: - nyud_dir: path to NYUDv2 dir - split: train / val / test - tops: list of tops to output from {color, depth, hha, label} - randomize: load in random order (default: True) - seed: seed fo...
[ "Setup", "data", "layer", "according", "to", "parameters", ":" ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L24-L74
[ "def", "setup", "(", "self", ",", "bottom", ",", "top", ")", ":", "# config", "params", "=", "eval", "(", "self", ".", "param_str", ")", "self", ".", "nyud_dir", "=", "params", "[", "'nyud_dir'", "]", "self", ".", "split", "=", "params", "[", "'split...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
NYUDSegDataLayer.load_image
Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
def load_image(self, idx): """ Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order """ im = Image.open('{}/data/images/img_{}.png'.format(self.nyud_dir, idx))...
def load_image(self, idx): """ Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order """ im = Image.open('{}/data/images/img_{}.png'.format(self.nyud_dir, idx))...
[ "Load", "input", "image", "and", "preprocess", "for", "Caffe", ":", "-", "cast", "to", "float", "-", "switch", "channels", "RGB", "-", ">", "BGR", "-", "subtract", "mean", "-", "transpose", "to", "channel", "x", "height", "x", "width", "order" ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L110-L123
[ "def", "load_image", "(", "self", ",", "idx", ")", ":", "im", "=", "Image", ".", "open", "(", "'{}/data/images/img_{}.png'", ".", "format", "(", "self", ".", "nyud_dir", ",", "idx", ")", ")", "in_", "=", "np", ".", "array", "(", "im", ",", "dtype", ...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
NYUDSegDataLayer.load_label
Load label image as 1 x height x width integer array of label indices. Shift labels so that classes are 0-39 and void is 255 (to ignore it). The leading singleton dimension is required by the loss.
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. Shift labels so that classes are 0-39 and void is 255 (to ignore it). The leading singleton dimension is required by the loss. """ label = scipy.io.loadmat('{}/segmentati...
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. Shift labels so that classes are 0-39 and void is 255 (to ignore it). The leading singleton dimension is required by the loss. """ label = scipy.io.loadmat('{}/segmentati...
[ "Load", "label", "image", "as", "1", "x", "height", "x", "width", "integer", "array", "of", "label", "indices", ".", "Shift", "labels", "so", "that", "classes", "are", "0", "-", "39", "and", "void", "is", "255", "(", "to", "ignore", "it", ")", ".", ...
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L125-L134
[ "def", "load_label", "(", "self", ",", "idx", ")", ":", "label", "=", "scipy", ".", "io", ".", "loadmat", "(", "'{}/segmentation/img_{}.mat'", ".", "format", "(", "self", ".", "nyud_dir", ",", "idx", ")", ")", "[", "'segmentation'", "]", ".", "astype", ...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
NYUDSegDataLayer.load_depth
Load pre-processed depth for NYUDv2 segmentation set.
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
def load_depth(self, idx): """ Load pre-processed depth for NYUDv2 segmentation set. """ im = Image.open('{}/data/depth/img_{}.png'.format(self.nyud_dir, idx)) d = np.array(im, dtype=np.float32) d = np.log(d) d -= self.mean_logd d = d[np.newaxis, ...] ...
def load_depth(self, idx): """ Load pre-processed depth for NYUDv2 segmentation set. """ im = Image.open('{}/data/depth/img_{}.png'.format(self.nyud_dir, idx)) d = np.array(im, dtype=np.float32) d = np.log(d) d -= self.mean_logd d = d[np.newaxis, ...] ...
[ "Load", "pre", "-", "processed", "depth", "for", "NYUDv2", "segmentation", "set", "." ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L136-L145
[ "def", "load_depth", "(", "self", ",", "idx", ")", ":", "im", "=", "Image", ".", "open", "(", "'{}/data/depth/img_{}.png'", ".", "format", "(", "self", ".", "nyud_dir", ",", "idx", ")", ")", "d", "=", "np", ".", "array", "(", "im", ",", "dtype", "=...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
NYUDSegDataLayer.load_hha
Load HHA features from Gupta et al. ECCV14. See https://github.com/s-gupta/rcnn-depth/blob/master/rcnn/saveHHA.m
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
def load_hha(self, idx): """ Load HHA features from Gupta et al. ECCV14. See https://github.com/s-gupta/rcnn-depth/blob/master/rcnn/saveHHA.m """ im = Image.open('{}/data/hha/img_{}.png'.format(self.nyud_dir, idx)) hha = np.array(im, dtype=np.float32) hha -= self....
def load_hha(self, idx): """ Load HHA features from Gupta et al. ECCV14. See https://github.com/s-gupta/rcnn-depth/blob/master/rcnn/saveHHA.m """ im = Image.open('{}/data/hha/img_{}.png'.format(self.nyud_dir, idx)) hha = np.array(im, dtype=np.float32) hha -= self....
[ "Load", "HHA", "features", "from", "Gupta", "et", "al", ".", "ECCV14", ".", "See", "https", ":", "//", "github", ".", "com", "/", "s", "-", "gupta", "/", "rcnn", "-", "depth", "/", "blob", "/", "master", "/", "rcnn", "/", "saveHHA", ".", "m" ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L147-L156
[ "def", "load_hha", "(", "self", ",", "idx", ")", ":", "im", "=", "Image", ".", "open", "(", "'{}/data/hha/img_{}.png'", ".", "format", "(", "self", ".", "nyud_dir", ",", "idx", ")", ")", "hha", "=", "np", ".", "array", "(", "im", ",", "dtype", "=",...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
SIFTFlowSegDataLayer.load_image
Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order
torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py
def load_image(self, idx): """ Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order """ im = Image.open('{}/Images/spatial_envelope_256x256_static_8outdoorcate...
def load_image(self, idx): """ Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order """ im = Image.open('{}/Images/spatial_envelope_256x256_static_8outdoorcate...
[ "Load", "input", "image", "and", "preprocess", "for", "Caffe", ":", "-", "cast", "to", "float", "-", "switch", "channels", "RGB", "-", ">", "BGR", "-", "subtract", "mean", "-", "transpose", "to", "channel", "x", "height", "x", "width", "order" ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py#L92-L105
[ "def", "load_image", "(", "self", ",", "idx", ")", ":", "im", "=", "Image", ".", "open", "(", "'{}/Images/spatial_envelope_256x256_static_8outdoorcategories/{}.jpg'", ".", "format", "(", "self", ".", "siftflow_dir", ",", "idx", ")", ")", "in_", "=", "np", ".",...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
SIFTFlowSegDataLayer.load_label
Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss.
torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py
def load_label(self, idx, label_type=None): """ Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. """ if label_type == 'semantic': label = scipy.io.loadmat('{}/SemanticLabels/spatial_envelop...
def load_label(self, idx, label_type=None): """ Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. """ if label_type == 'semantic': label = scipy.io.loadmat('{}/SemanticLabels/spatial_envelop...
[ "Load", "label", "image", "as", "1", "x", "height", "x", "width", "integer", "array", "of", "label", "indices", ".", "The", "leading", "singleton", "dimension", "is", "required", "by", "the", "loss", "." ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py#L107-L122
[ "def", "load_label", "(", "self", ",", "idx", ",", "label_type", "=", "None", ")", ":", "if", "label_type", "==", "'semantic'", ":", "label", "=", "scipy", ".", "io", ".", "loadmat", "(", "'{}/SemanticLabels/spatial_envelope_256x256_static_8outdoorcategories/{}.mat'...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
get_upsampling_weight
Make a 2D bilinear kernel suitable for upsampling
torchfcn/models/fcn32s.py
def get_upsampling_weight(in_channels, out_channels, kernel_size): """Make a 2D bilinear kernel suitable for upsampling""" factor = (kernel_size + 1) // 2 if kernel_size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:kernel_size, :kernel_size] filt = (1 ...
def get_upsampling_weight(in_channels, out_channels, kernel_size): """Make a 2D bilinear kernel suitable for upsampling""" factor = (kernel_size + 1) // 2 if kernel_size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:kernel_size, :kernel_size] filt = (1 ...
[ "Make", "a", "2D", "bilinear", "kernel", "suitable", "for", "upsampling" ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/models/fcn32s.py#L10-L23
[ "def", "get_upsampling_weight", "(", "in_channels", ",", "out_channels", ",", "kernel_size", ")", ":", "factor", "=", "(", "kernel_size", "+", "1", ")", "//", "2", "if", "kernel_size", "%", "2", "==", "1", ":", "center", "=", "factor", "-", "1", "else", ...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
label_accuracy_score
Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc
torchfcn/utils.py
def label_accuracy_score(label_trues, label_preds, n_class): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc """ hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += _fast_hist(lt.fla...
def label_accuracy_score(label_trues, label_preds, n_class): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc """ hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += _fast_hist(lt.fla...
[ "Returns", "accuracy", "score", "evaluation", "result", "." ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/utils.py#L12-L34
[ "def", "label_accuracy_score", "(", "label_trues", ",", "label_preds", ",", "n_class", ")", ":", "hist", "=", "np", ".", "zeros", "(", "(", "n_class", ",", "n_class", ")", ")", "for", "lt", ",", "lp", "in", "zip", "(", "label_trues", ",", "label_preds", ...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
transplant
Transfer weights by copying matching parameters, coercing parameters of incompatible shape, and dropping unmatched parameters. The coercion is useful to convert fully connected layers to their equivalent convolutional layers, since the weights are the same and only the shapes are different. In particu...
torchfcn/ext/fcn.berkeleyvision.org/surgery.py
def transplant(new_net, net, suffix=''): """ Transfer weights by copying matching parameters, coercing parameters of incompatible shape, and dropping unmatched parameters. The coercion is useful to convert fully connected layers to their equivalent convolutional layers, since the weights are the sa...
def transplant(new_net, net, suffix=''): """ Transfer weights by copying matching parameters, coercing parameters of incompatible shape, and dropping unmatched parameters. The coercion is useful to convert fully connected layers to their equivalent convolutional layers, since the weights are the sa...
[ "Transfer", "weights", "by", "copying", "matching", "parameters", "coercing", "parameters", "of", "incompatible", "shape", "and", "dropping", "unmatched", "parameters", "." ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/surgery.py#L5-L31
[ "def", "transplant", "(", "new_net", ",", "net", ",", "suffix", "=", "''", ")", ":", "for", "p", "in", "net", ".", "params", ":", "p_new", "=", "p", "+", "suffix", "if", "p_new", "not", "in", "new_net", ".", "params", ":", "print", "'dropping'", ",...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
interp
Set weights of each layer in layers to bilinear kernels for interpolation.
torchfcn/ext/fcn.berkeleyvision.org/surgery.py
def interp(net, layers): """ Set weights of each layer in layers to bilinear kernels for interpolation. """ for l in layers: m, k, h, w = net.params[l][0].data.shape if m != k and k != 1: print 'input + output channels need to be the same or |output| == 1' raise ...
def interp(net, layers): """ Set weights of each layer in layers to bilinear kernels for interpolation. """ for l in layers: m, k, h, w = net.params[l][0].data.shape if m != k and k != 1: print 'input + output channels need to be the same or |output| == 1' raise ...
[ "Set", "weights", "of", "each", "layer", "in", "layers", "to", "bilinear", "kernels", "for", "interpolation", "." ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/surgery.py#L46-L59
[ "def", "interp", "(", "net", ",", "layers", ")", ":", "for", "l", "in", "layers", ":", "m", ",", "k", ",", "h", ",", "w", "=", "net", ".", "params", "[", "l", "]", "[", "0", "]", ".", "data", ".", "shape", "if", "m", "!=", "k", "and", "k"...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
expand_score
Transplant an old score layer's parameters, with k < k' classes, into a new score layer with k classes s.t. the first k' are the old classes.
torchfcn/ext/fcn.berkeleyvision.org/surgery.py
def expand_score(new_net, new_layer, net, layer): """ Transplant an old score layer's parameters, with k < k' classes, into a new score layer with k classes s.t. the first k' are the old classes. """ old_cl = net.params[layer][0].num new_net.params[new_layer][0].data[:old_cl][...] = net.params[l...
def expand_score(new_net, new_layer, net, layer): """ Transplant an old score layer's parameters, with k < k' classes, into a new score layer with k classes s.t. the first k' are the old classes. """ old_cl = net.params[layer][0].num new_net.params[new_layer][0].data[:old_cl][...] = net.params[l...
[ "Transplant", "an", "old", "score", "layer", "s", "parameters", "with", "k", "<", "k", "classes", "into", "a", "new", "score", "layer", "with", "k", "classes", "s", ".", "t", ".", "the", "first", "k", "are", "the", "old", "classes", "." ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/surgery.py#L61-L68
[ "def", "expand_score", "(", "new_net", ",", "new_layer", ",", "net", ",", "layer", ")", ":", "old_cl", "=", "net", ".", "params", "[", "layer", "]", "[", "0", "]", ".", "num", "new_net", ".", "params", "[", "new_layer", "]", "[", "0", "]", ".", "...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
VOCSegDataLayer.setup
Setup data layer according to parameters: - voc_dir: path to PASCAL VOC year dir - split: train / val / test - mean: tuple of mean values to subtract - randomize: load in random order (default: True) - seed: seed for randomization (default: None / current time) for PASC...
torchfcn/ext/fcn.berkeleyvision.org/voc_layers.py
def setup(self, bottom, top): """ Setup data layer according to parameters: - voc_dir: path to PASCAL VOC year dir - split: train / val / test - mean: tuple of mean values to subtract - randomize: load in random order (default: True) - seed: seed for randomizatio...
def setup(self, bottom, top): """ Setup data layer according to parameters: - voc_dir: path to PASCAL VOC year dir - split: train / val / test - mean: tuple of mean values to subtract - randomize: load in random order (default: True) - seed: seed for randomizatio...
[ "Setup", "data", "layer", "according", "to", "parameters", ":" ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/voc_layers.py#L16-L62
[ "def", "setup", "(", "self", ",", "bottom", ",", "top", ")", ":", "# config", "params", "=", "eval", "(", "self", ".", "param_str", ")", "self", ".", "voc_dir", "=", "params", "[", "'voc_dir'", "]", "self", ".", "split", "=", "params", "[", "'split'"...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
PASCALContextSegDataLayer.setup
Setup data layer according to parameters: - voc_dir: path to PASCAL VOC dir (must contain 2010) - context_dir: path to PASCAL-Context annotations - split: train / val / test - randomize: load in random order (default: True) - seed: seed for randomization (default: None / current...
torchfcn/ext/fcn.berkeleyvision.org/pascalcontext_layers.py
def setup(self, bottom, top): """ Setup data layer according to parameters: - voc_dir: path to PASCAL VOC dir (must contain 2010) - context_dir: path to PASCAL-Context annotations - split: train / val / test - randomize: load in random order (default: True) - see...
def setup(self, bottom, top): """ Setup data layer according to parameters: - voc_dir: path to PASCAL VOC dir (must contain 2010) - context_dir: path to PASCAL-Context annotations - split: train / val / test - randomize: load in random order (default: True) - see...
[ "Setup", "data", "layer", "according", "to", "parameters", ":" ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/pascalcontext_layers.py#L23-L72
[ "def", "setup", "(", "self", ",", "bottom", ",", "top", ")", ":", "# config", "params", "=", "eval", "(", "self", ".", "param_str", ")", "self", ".", "voc_dir", "=", "params", "[", "'voc_dir'", "]", "+", "'/VOC2010'", "self", ".", "context_dir", "=", ...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
PASCALContextSegDataLayer.load_label
Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. The full 400 labels are translated to the 59 class task labels.
torchfcn/ext/fcn.berkeleyvision.org/pascalcontext_layers.py
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. The full 400 labels are translated to the 59 class task labels. """ label_400 = scipy.io.loadmat('{}/trainval/{}....
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. The full 400 labels are translated to the 59 class task labels. """ label_400 = scipy.io.loadmat('{}/trainval/{}....
[ "Load", "label", "image", "as", "1", "x", "height", "x", "width", "integer", "array", "of", "label", "indices", ".", "The", "leading", "singleton", "dimension", "is", "required", "by", "the", "loss", ".", "The", "full", "400", "labels", "are", "translated"...
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/pascalcontext_layers.py#L113-L125
[ "def", "load_label", "(", "self", ",", "idx", ")", ":", "label_400", "=", "scipy", ".", "io", ".", "loadmat", "(", "'{}/trainval/{}.mat'", ".", "format", "(", "self", ".", "context_dir", ",", "idx", ")", ")", "[", "'LabelMap'", "]", "label", "=", "np",...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
voc.load_label
Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss.
torchfcn/ext/fcn.berkeleyvision.org/voc_helper.py
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. """ label = Image.open('{}/SegmentationClass/{}.png'.format(self.dir, idx)) label = np.array(label, dtype=np.uint...
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. """ label = Image.open('{}/SegmentationClass/{}.png'.format(self.dir, idx)) label = np.array(label, dtype=np.uint...
[ "Load", "label", "image", "as", "1", "x", "height", "x", "width", "integer", "array", "of", "label", "indices", ".", "The", "leading", "singleton", "dimension", "is", "required", "by", "the", "loss", "." ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/voc_helper.py#L27-L35
[ "def", "load_label", "(", "self", ",", "idx", ")", ":", "label", "=", "Image", ".", "open", "(", "'{}/SegmentationClass/{}.png'", ".", "format", "(", "self", ".", "dir", ",", "idx", ")", ")", "label", "=", "np", ".", "array", "(", "label", ",", "dtyp...
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
voc.palette
Transfer the VOC color palette to an output mask for visualization.
torchfcn/ext/fcn.berkeleyvision.org/voc_helper.py
def palette(self, label_im): ''' Transfer the VOC color palette to an output mask for visualization. ''' if label_im.ndim == 3: label_im = label_im[0] label = Image.fromarray(label_im, mode='P') label.palette = copy.copy(self.palette) return label
def palette(self, label_im): ''' Transfer the VOC color palette to an output mask for visualization. ''' if label_im.ndim == 3: label_im = label_im[0] label = Image.fromarray(label_im, mode='P') label.palette = copy.copy(self.palette) return label
[ "Transfer", "the", "VOC", "color", "palette", "to", "an", "output", "mask", "for", "visualization", "." ]
wkentaro/pytorch-fcn
python
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/voc_helper.py#L37-L45
[ "def", "palette", "(", "self", ",", "label_im", ")", ":", "if", "label_im", ".", "ndim", "==", "3", ":", "label_im", "=", "label_im", "[", "0", "]", "label", "=", "Image", ".", "fromarray", "(", "label_im", ",", "mode", "=", "'P'", ")", "label", "....
97189cbccb2c9b8bd776b356a1fd4b6c03f67d79
train
_shuffled
Deterministically shuffle identically under both py2 + py3.
pre_commit/languages/helpers.py
def _shuffled(seq): """Deterministically shuffle identically under both py2 + py3.""" fixed_random = random.Random() if six.PY2: # pragma: no cover (py2) fixed_random.seed(FIXED_RANDOM_SEED) else: # pragma: no cover (py3) fixed_random.seed(FIXED_RANDOM_SEED, version=1) seq = list(...
def _shuffled(seq): """Deterministically shuffle identically under both py2 + py3.""" fixed_random = random.Random() if six.PY2: # pragma: no cover (py2) fixed_random.seed(FIXED_RANDOM_SEED) else: # pragma: no cover (py3) fixed_random.seed(FIXED_RANDOM_SEED, version=1) seq = list(...
[ "Deterministically", "shuffle", "identically", "under", "both", "py2", "+", "py3", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/languages/helpers.py#L73-L83
[ "def", "_shuffled", "(", "seq", ")", ":", "fixed_random", "=", "random", ".", "Random", "(", ")", "if", "six", ".", "PY2", ":", "# pragma: no cover (py2)", "fixed_random", ".", "seed", "(", "FIXED_RANDOM_SEED", ")", "else", ":", "# pragma: no cover (py3)", "fi...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
envcontext
In this context, `os.environ` is modified according to `patch`. `patch` is an iterable of 2-tuples (key, value): `key`: string `value`: - string: `environ[key] == value` inside the context. - UNSET: `key not in environ` inside the context. - template: A template ...
pre_commit/envcontext.py
def envcontext(patch, _env=None): """In this context, `os.environ` is modified according to `patch`. `patch` is an iterable of 2-tuples (key, value): `key`: string `value`: - string: `environ[key] == value` inside the context. - UNSET: `key not in environ` inside the con...
def envcontext(patch, _env=None): """In this context, `os.environ` is modified according to `patch`. `patch` is an iterable of 2-tuples (key, value): `key`: string `value`: - string: `environ[key] == value` inside the context. - UNSET: `key not in environ` inside the con...
[ "In", "this", "context", "os", ".", "environ", "is", "modified", "according", "to", "patch", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/envcontext.py#L24-L50
[ "def", "envcontext", "(", "patch", ",", "_env", "=", "None", ")", ":", "env", "=", "os", ".", "environ", "if", "_env", "is", "None", "else", "_env", "before", "=", "env", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "patch", ":", "if", "v...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
bin_dir
On windows there's a different directory for the virtualenv
pre_commit/languages/python.py
def bin_dir(venv): """On windows there's a different directory for the virtualenv""" bin_part = 'Scripts' if os.name == 'nt' else 'bin' return os.path.join(venv, bin_part)
def bin_dir(venv): """On windows there's a different directory for the virtualenv""" bin_part = 'Scripts' if os.name == 'nt' else 'bin' return os.path.join(venv, bin_part)
[ "On", "windows", "there", "s", "a", "different", "directory", "for", "the", "virtualenv" ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/languages/python.py#L21-L24
[ "def", "bin_dir", "(", "venv", ")", ":", "bin_part", "=", "'Scripts'", "if", "os", ".", "name", "==", "'nt'", "else", "'bin'", "return", "os", ".", "path", ".", "join", "(", "venv", ",", "bin_part", ")" ]
72f98d26e690da11dc2e41861d14c58eb21930cb
train
install
Install the pre-commit hooks.
pre_commit/commands/install_uninstall.py
def install( config_file, store, overwrite=False, hooks=False, hook_type='pre-commit', skip_on_missing_conf=False, ): """Install the pre-commit hooks.""" if cmd_output('git', 'config', 'core.hooksPath', retcode=None)[1].strip(): logger.error( 'Cowardly refusing to ins...
def install( config_file, store, overwrite=False, hooks=False, hook_type='pre-commit', skip_on_missing_conf=False, ): """Install the pre-commit hooks.""" if cmd_output('git', 'config', 'core.hooksPath', retcode=None)[1].strip(): logger.error( 'Cowardly refusing to ins...
[ "Install", "the", "pre", "-", "commit", "hooks", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/commands/install_uninstall.py#L69-L126
[ "def", "install", "(", "config_file", ",", "store", ",", "overwrite", "=", "False", ",", "hooks", "=", "False", ",", "hook_type", "=", "'pre-commit'", ",", "skip_on_missing_conf", "=", "False", ",", ")", ":", "if", "cmd_output", "(", "'git'", ",", "'config...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
uninstall
Uninstall the pre-commit hooks.
pre_commit/commands/install_uninstall.py
def uninstall(hook_type='pre-commit'): """Uninstall the pre-commit hooks.""" hook_path, legacy_path = _hook_paths(hook_type) # If our file doesn't exist or it isn't ours, gtfo. if not os.path.exists(hook_path) or not is_our_script(hook_path): return 0 os.remove(hook_path) output.write_...
def uninstall(hook_type='pre-commit'): """Uninstall the pre-commit hooks.""" hook_path, legacy_path = _hook_paths(hook_type) # If our file doesn't exist or it isn't ours, gtfo. if not os.path.exists(hook_path) or not is_our_script(hook_path): return 0 os.remove(hook_path) output.write_...
[ "Uninstall", "the", "pre", "-", "commit", "hooks", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/commands/install_uninstall.py#L133-L148
[ "def", "uninstall", "(", "hook_type", "=", "'pre-commit'", ")", ":", "hook_path", ",", "legacy_path", "=", "_hook_paths", "(", "hook_type", ")", "# If our file doesn't exist or it isn't ours, gtfo.", "if", "not", "os", ".", "path", ".", "exists", "(", "hook_path", ...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
normalize_cmd
Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine
pre_commit/parse_shebang.py
def normalize_cmd(cmd): """Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine """ # Use PATH to determine the executable exe = normexe(cmd[0]) # Figure out the sheban...
def normalize_cmd(cmd): """Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine """ # Use PATH to determine the executable exe = normexe(cmd[0]) # Figure out the sheban...
[ "Fixes", "for", "the", "following", "issues", "on", "windows", "-", "https", ":", "//", "bugs", ".", "python", ".", "org", "/", "issue8557", "-", "windows", "does", "not", "parse", "shebangs" ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/parse_shebang.py#L62-L78
[ "def", "normalize_cmd", "(", "cmd", ")", ":", "# Use PATH to determine the executable", "exe", "=", "normexe", "(", "cmd", "[", "0", "]", ")", "# Figure out the shebang from the resulting command", "cmd", "=", "parse_filename", "(", "exe", ")", "+", "(", "exe", ",...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
get_hook_message
Prints a message for running a hook. This currently supports three approaches: # Print `start` followed by dots, leaving 6 characters at the end >>> print_hook_message('start', end_len=6) start............................................................... # Print `start` followed by dots with th...
pre_commit/output.py
def get_hook_message( start, postfix='', end_msg=None, end_len=0, end_color=None, use_color=None, cols=80, ): """Prints a message for running a hook. This currently supports three approaches: # Print `start` followed by dots, leaving 6 characters at ...
def get_hook_message( start, postfix='', end_msg=None, end_len=0, end_color=None, use_color=None, cols=80, ): """Prints a message for running a hook. This currently supports three approaches: # Print `start` followed by dots, leaving 6 characters at ...
[ "Prints", "a", "message", "for", "running", "a", "hook", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/output.py#L10-L64
[ "def", "get_hook_message", "(", "start", ",", "postfix", "=", "''", ",", "end_msg", "=", "None", ",", "end_len", "=", "0", ",", "end_color", "=", "None", ",", "use_color", "=", "None", ",", "cols", "=", "80", ",", ")", ":", "if", "bool", "(", "end_...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
check_for_cygwin_mismatch
See https://github.com/pre-commit/pre-commit/issues/354
pre_commit/git.py
def check_for_cygwin_mismatch(): """See https://github.com/pre-commit/pre-commit/issues/354""" if sys.platform in ('cygwin', 'win32'): # pragma: no cover (windows) is_cygwin_python = sys.platform == 'cygwin' toplevel = cmd_output('git', 'rev-parse', '--show-toplevel')[1] is_cygwin_git =...
def check_for_cygwin_mismatch(): """See https://github.com/pre-commit/pre-commit/issues/354""" if sys.platform in ('cygwin', 'win32'): # pragma: no cover (windows) is_cygwin_python = sys.platform == 'cygwin' toplevel = cmd_output('git', 'rev-parse', '--show-toplevel')[1] is_cygwin_git =...
[ "See", "https", ":", "//", "github", ".", "com", "/", "pre", "-", "commit", "/", "pre", "-", "commit", "/", "issues", "/", "354" ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/git.py#L160-L179
[ "def", "check_for_cygwin_mismatch", "(", ")", ":", "if", "sys", ".", "platform", "in", "(", "'cygwin'", ",", "'win32'", ")", ":", "# pragma: no cover (windows)", "is_cygwin_python", "=", "sys", ".", "platform", "==", "'cygwin'", "toplevel", "=", "cmd_output", "(...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
xargs
A simplified implementation of xargs. negate: Make nonzero successful and zero a failure target_concurrency: Target number of partitions to run concurrently
pre_commit/xargs.py
def xargs(cmd, varargs, **kwargs): """A simplified implementation of xargs. negate: Make nonzero successful and zero a failure target_concurrency: Target number of partitions to run concurrently """ negate = kwargs.pop('negate', False) target_concurrency = kwargs.pop('target_concurrency', 1) ...
def xargs(cmd, varargs, **kwargs): """A simplified implementation of xargs. negate: Make nonzero successful and zero a failure target_concurrency: Target number of partitions to run concurrently """ negate = kwargs.pop('negate', False) target_concurrency = kwargs.pop('target_concurrency', 1) ...
[ "A", "simplified", "implementation", "of", "xargs", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/xargs.py#L104-L146
[ "def", "xargs", "(", "cmd", ",", "varargs", ",", "*", "*", "kwargs", ")", ":", "negate", "=", "kwargs", ".", "pop", "(", "'negate'", ",", "False", ")", "target_concurrency", "=", "kwargs", ".", "pop", "(", "'target_concurrency'", ",", "1", ")", "max_le...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
make_archive
Makes an archive of a repository in the given destdir. :param text name: Name to give the archive. For instance foo. The file that is created will be called foo.tar.gz. :param text repo: Repository to clone. :param text ref: Tag/SHA/branch to check out. :param text destdir: Directory to place arc...
pre_commit/make_archives.py
def make_archive(name, repo, ref, destdir): """Makes an archive of a repository in the given destdir. :param text name: Name to give the archive. For instance foo. The file that is created will be called foo.tar.gz. :param text repo: Repository to clone. :param text ref: Tag/SHA/branch to check o...
def make_archive(name, repo, ref, destdir): """Makes an archive of a repository in the given destdir. :param text name: Name to give the archive. For instance foo. The file that is created will be called foo.tar.gz. :param text repo: Repository to clone. :param text ref: Tag/SHA/branch to check o...
[ "Makes", "an", "archive", "of", "a", "repository", "in", "the", "given", "destdir", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/make_archives.py#L30-L53
[ "def", "make_archive", "(", "name", ",", "repo", ",", "ref", ",", "destdir", ")", ":", "output_path", "=", "os", ".", "path", ".", "join", "(", "destdir", ",", "name", "+", "'.tar.gz'", ")", "with", "tmpdir", "(", ")", "as", "tempdir", ":", "# Clone ...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
_compute_cols
Compute the number of columns to display hook messages. The widest that will be displayed is in the no files skipped case: Hook name...(no files to check) Skipped or in the verbose case Hook name [hookid]...(no files to check) Skipped
pre_commit/commands/run.py
def _compute_cols(hooks, verbose): """Compute the number of columns to display hook messages. The widest that will be displayed is in the no files skipped case: Hook name...(no files to check) Skipped or in the verbose case Hook name [hookid]...(no files to check) Skipped """ if ...
def _compute_cols(hooks, verbose): """Compute the number of columns to display hook messages. The widest that will be displayed is in the no files skipped case: Hook name...(no files to check) Skipped or in the verbose case Hook name [hookid]...(no files to check) Skipped """ if ...
[ "Compute", "the", "number", "of", "columns", "to", "display", "hook", "messages", ".", "The", "widest", "that", "will", "be", "displayed", "is", "in", "the", "no", "files", "skipped", "case", ":" ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/commands/run.py#L171-L187
[ "def", "_compute_cols", "(", "hooks", ",", "verbose", ")", ":", "if", "hooks", ":", "name_len", "=", "max", "(", "len", "(", "_hook_msg_start", "(", "hook", ",", "verbose", ")", ")", "for", "hook", "in", "hooks", ")", "else", ":", "name_len", "=", "0...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
_run_hooks
Actually run the hooks.
pre_commit/commands/run.py
def _run_hooks(config, hooks, args, environ): """Actually run the hooks.""" skips = _get_skips(environ) cols = _compute_cols(hooks, args.verbose) filenames = _all_filenames(args) filenames = filter_by_include_exclude(filenames, '', config['exclude']) classifier = Classifier(filenames) retval...
def _run_hooks(config, hooks, args, environ): """Actually run the hooks.""" skips = _get_skips(environ) cols = _compute_cols(hooks, args.verbose) filenames = _all_filenames(args) filenames = filter_by_include_exclude(filenames, '', config['exclude']) classifier = Classifier(filenames) retval...
[ "Actually", "run", "the", "hooks", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/commands/run.py#L205-L228
[ "def", "_run_hooks", "(", "config", ",", "hooks", ",", "args", ",", "environ", ")", ":", "skips", "=", "_get_skips", "(", "environ", ")", "cols", "=", "_compute_cols", "(", "hooks", ",", "args", ".", "verbose", ")", "filenames", "=", "_all_filenames", "(...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
rmtree
On windows, rmtree fails for readonly dirs.
pre_commit/util.py
def rmtree(path): """On windows, rmtree fails for readonly dirs.""" def handle_remove_readonly(func, path, exc): # pragma: no cover (windows) excvalue = exc[1] if ( func in (os.rmdir, os.remove, os.unlink) and excvalue.errno == errno.EACCES ): ...
def rmtree(path): """On windows, rmtree fails for readonly dirs.""" def handle_remove_readonly(func, path, exc): # pragma: no cover (windows) excvalue = exc[1] if ( func in (os.rmdir, os.remove, os.unlink) and excvalue.errno == errno.EACCES ): ...
[ "On", "windows", "rmtree", "fails", "for", "readonly", "dirs", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/util.py#L159-L171
[ "def", "rmtree", "(", "path", ")", ":", "def", "handle_remove_readonly", "(", "func", ",", "path", ",", "exc", ")", ":", "# pragma: no cover (windows)", "excvalue", "=", "exc", "[", "1", "]", "if", "(", "func", "in", "(", "os", ".", "rmdir", ",", "os",...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
_update_repo
Updates a repository to the tip of `master`. If the repository cannot be updated because a hook that is configured does not exist in `master`, this raises a RepositoryCannotBeUpdatedError Args: repo_config - A config for a repository
pre_commit/commands/autoupdate.py
def _update_repo(repo_config, store, tags_only): """Updates a repository to the tip of `master`. If the repository cannot be updated because a hook that is configured does not exist in `master`, this raises a RepositoryCannotBeUpdatedError Args: repo_config - A config for a repository """ ...
def _update_repo(repo_config, store, tags_only): """Updates a repository to the tip of `master`. If the repository cannot be updated because a hook that is configured does not exist in `master`, this raises a RepositoryCannotBeUpdatedError Args: repo_config - A config for a repository """ ...
[ "Updates", "a", "repository", "to", "the", "tip", "of", "master", ".", "If", "the", "repository", "cannot", "be", "updated", "because", "a", "hook", "that", "is", "configured", "does", "not", "exist", "in", "master", "this", "raises", "a", "RepositoryCannotB...
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/commands/autoupdate.py#L29-L73
[ "def", "_update_repo", "(", "repo_config", ",", "store", ",", "tags_only", ")", ":", "repo_path", "=", "store", ".", "clone", "(", "repo_config", "[", "'repo'", "]", ",", "repo_config", "[", "'rev'", "]", ")", "cmd_output", "(", "'git'", ",", "'fetch'", ...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
autoupdate
Auto-update the pre-commit config to the latest versions of repos.
pre_commit/commands/autoupdate.py
def autoupdate(config_file, store, tags_only, repos=()): """Auto-update the pre-commit config to the latest versions of repos.""" migrate_config(config_file, quiet=True) retv = 0 output_repos = [] changed = False input_config = load_config(config_file) for repo_config in input_config['repo...
def autoupdate(config_file, store, tags_only, repos=()): """Auto-update the pre-commit config to the latest versions of repos.""" migrate_config(config_file, quiet=True) retv = 0 output_repos = [] changed = False input_config = load_config(config_file) for repo_config in input_config['repo...
[ "Auto", "-", "update", "the", "pre", "-", "commit", "config", "to", "the", "latest", "versions", "of", "repos", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/commands/autoupdate.py#L117-L160
[ "def", "autoupdate", "(", "config_file", ",", "store", ",", "tags_only", ",", "repos", "=", "(", ")", ")", ":", "migrate_config", "(", "config_file", ",", "quiet", "=", "True", ")", "retv", "=", "0", "output_repos", "=", "[", "]", "changed", "=", "Fals...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
orig_py_exe
A -mvenv virtualenv made from a -mvirtualenv virtualenv installs packages to the incorrect location. Attempt to find the _original_ exe and invoke `-mvenv` from there. See: - https://github.com/pre-commit/pre-commit/issues/755 - https://github.com/pypa/virtualenv/issues/1095 - https://bugs.pyt...
pre_commit/languages/python_venv.py
def orig_py_exe(exe): # pragma: no cover (platform specific) """A -mvenv virtualenv made from a -mvirtualenv virtualenv installs packages to the incorrect location. Attempt to find the _original_ exe and invoke `-mvenv` from there. See: - https://github.com/pre-commit/pre-commit/issues/755 - ...
def orig_py_exe(exe): # pragma: no cover (platform specific) """A -mvenv virtualenv made from a -mvirtualenv virtualenv installs packages to the incorrect location. Attempt to find the _original_ exe and invoke `-mvenv` from there. See: - https://github.com/pre-commit/pre-commit/issues/755 - ...
[ "A", "-", "mvenv", "virtualenv", "made", "from", "a", "-", "mvirtualenv", "virtualenv", "installs", "packages", "to", "the", "incorrect", "location", ".", "Attempt", "to", "find", "the", "_original_", "exe", "and", "invoke", "-", "mvenv", "from", "there", "....
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/languages/python_venv.py#L21-L47
[ "def", "orig_py_exe", "(", "exe", ")", ":", "# pragma: no cover (platform specific)", "try", ":", "prefix_script", "=", "'import sys; print(sys.real_prefix)'", "_", ",", "prefix", ",", "_", "=", "cmd_output", "(", "exe", ",", "'-c'", ",", "prefix_script", ")", "pr...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
enable_virtual_terminal_processing
As of Windows 10, the Windows console supports (some) ANSI escape sequences, but it needs to be enabled using `SetConsoleMode` first. More info on the escape sequences supported: https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
pre_commit/color_windows.py
def enable_virtual_terminal_processing(): """As of Windows 10, the Windows console supports (some) ANSI escape sequences, but it needs to be enabled using `SetConsoleMode` first. More info on the escape sequences supported: https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx...
def enable_virtual_terminal_processing(): """As of Windows 10, the Windows console supports (some) ANSI escape sequences, but it needs to be enabled using `SetConsoleMode` first. More info on the escape sequences supported: https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx...
[ "As", "of", "Windows", "10", "the", "Windows", "console", "supports", "(", "some", ")", "ANSI", "escape", "sequences", "but", "it", "needs", "to", "be", "enabled", "using", "SetConsoleMode", "first", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/color_windows.py#L39-L48
[ "def", "enable_virtual_terminal_processing", "(", ")", ":", "stdout", "=", "GetStdHandle", "(", "STD_OUTPUT_HANDLE", ")", "flags", "=", "GetConsoleMode", "(", "stdout", ")", "SetConsoleMode", "(", "stdout", ",", "flags", "|", "ENABLE_VIRTUAL_TERMINAL_PROCESSING", ")" ...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
format_color
Format text with color. Args: text - Text to be formatted with color if `use_color` color - The color start string use_color_setting - Whether or not to color
pre_commit/color.py
def format_color(text, color, use_color_setting): """Format text with color. Args: text - Text to be formatted with color if `use_color` color - The color start string use_color_setting - Whether or not to color """ if not use_color_setting: return text else: ...
def format_color(text, color, use_color_setting): """Format text with color. Args: text - Text to be formatted with color if `use_color` color - The color start string use_color_setting - Whether or not to color """ if not use_color_setting: return text else: ...
[ "Format", "text", "with", "color", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/color.py#L25-L36
[ "def", "format_color", "(", "text", ",", "color", ",", "use_color_setting", ")", ":", "if", "not", "use_color_setting", ":", "return", "text", "else", ":", "return", "'{}{}{}'", ".", "format", "(", "color", ",", "text", ",", "NORMAL", ")" ]
72f98d26e690da11dc2e41861d14c58eb21930cb
train
use_color
Choose whether to use color based on the command argument. Args: setting - Either `auto`, `always`, or `never`
pre_commit/color.py
def use_color(setting): """Choose whether to use color based on the command argument. Args: setting - Either `auto`, `always`, or `never` """ if setting not in COLOR_CHOICES: raise InvalidColorSetting(setting) return ( setting == 'always' or (setting == 'auto' and s...
def use_color(setting): """Choose whether to use color based on the command argument. Args: setting - Either `auto`, `always`, or `never` """ if setting not in COLOR_CHOICES: raise InvalidColorSetting(setting) return ( setting == 'always' or (setting == 'auto' and s...
[ "Choose", "whether", "to", "use", "color", "based", "on", "the", "command", "argument", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/color.py#L42-L54
[ "def", "use_color", "(", "setting", ")", ":", "if", "setting", "not", "in", "COLOR_CHOICES", ":", "raise", "InvalidColorSetting", "(", "setting", ")", "return", "(", "setting", "==", "'always'", "or", "(", "setting", "==", "'auto'", "and", "sys", ".", "std...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
_get_default_directory
Returns the default directory for the Store. This is intentionally underscored to indicate that `Store.get_default_directory` is the intended way to get this information. This is also done so `Store.get_default_directory` can be mocked in tests and `_get_default_directory` can be tested.
pre_commit/store.py
def _get_default_directory(): """Returns the default directory for the Store. This is intentionally underscored to indicate that `Store.get_default_directory` is the intended way to get this information. This is also done so `Store.get_default_directory` can be mocked in tests and `_get_default_di...
def _get_default_directory(): """Returns the default directory for the Store. This is intentionally underscored to indicate that `Store.get_default_directory` is the intended way to get this information. This is also done so `Store.get_default_directory` can be mocked in tests and `_get_default_di...
[ "Returns", "the", "default", "directory", "for", "the", "Store", ".", "This", "is", "intentionally", "underscored", "to", "indicate", "that", "Store", ".", "get_default_directory", "is", "the", "intended", "way", "to", "get", "this", "information", ".", "This", ...
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/store.py#L23-L33
[ "def", "_get_default_directory", "(", ")", ":", "return", "os", ".", "environ", ".", "get", "(", "'PRE_COMMIT_HOME'", ")", "or", "os", ".", "path", ".", "join", "(", "os", ".", "environ", ".", "get", "(", "'XDG_CACHE_HOME'", ")", "or", "os", ".", "path...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
Store._shallow_clone
Perform a shallow clone of a repository and its submodules
pre_commit/store.py
def _shallow_clone(self, ref, git_cmd): # pragma: windows no cover """Perform a shallow clone of a repository and its submodules """ git_config = 'protocol.version=2' git_cmd('-c', git_config, 'fetch', 'origin', ref, '--depth=1') git_cmd('checkout', ref) git_cmd( '-...
def _shallow_clone(self, ref, git_cmd): # pragma: windows no cover """Perform a shallow clone of a repository and its submodules """ git_config = 'protocol.version=2' git_cmd('-c', git_config, 'fetch', 'origin', ref, '--depth=1') git_cmd('checkout', ref) git_cmd( '-...
[ "Perform", "a", "shallow", "clone", "of", "a", "repository", "and", "its", "submodules" ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/store.py#L145-L154
[ "def", "_shallow_clone", "(", "self", ",", "ref", ",", "git_cmd", ")", ":", "# pragma: windows no cover", "git_config", "=", "'protocol.version=2'", "git_cmd", "(", "'-c'", ",", "git_config", ",", "'fetch'", ",", "'origin'", ",", "ref", ",", "'--depth=1'", ")", ...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
Store.clone
Clone the given url and checkout the specific ref.
pre_commit/store.py
def clone(self, repo, ref, deps=()): """Clone the given url and checkout the specific ref.""" if os.path.isdir(repo): repo = os.path.abspath(repo) def clone_strategy(directory): env = git.no_git_env() def _git_cmd(*args): cmd_output('git', *...
def clone(self, repo, ref, deps=()): """Clone the given url and checkout the specific ref.""" if os.path.isdir(repo): repo = os.path.abspath(repo) def clone_strategy(directory): env = git.no_git_env() def _git_cmd(*args): cmd_output('git', *...
[ "Clone", "the", "given", "url", "and", "checkout", "the", "specific", "ref", "." ]
pre-commit/pre-commit
python
https://github.com/pre-commit/pre-commit/blob/72f98d26e690da11dc2e41861d14c58eb21930cb/pre_commit/store.py#L156-L176
[ "def", "clone", "(", "self", ",", "repo", ",", "ref", ",", "deps", "=", "(", ")", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "repo", ")", ":", "repo", "=", "os", ".", "path", ".", "abspath", "(", "repo", ")", "def", "clone_strategy",...
72f98d26e690da11dc2e41861d14c58eb21930cb
train
compounding
Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert nex...
thinc/rates.py
def compounding(start, stop, compound, t=0.0): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. ...
def compounding(start, stop, compound, t=0.0): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. ...
[ "Yield", "an", "infinite", "series", "of", "compounding", "values", ".", "Each", "time", "the", "generator", "is", "called", "a", "value", "is", "produced", "by", "multiplying", "the", "previous", "value", "by", "the", "compound", "rate", "." ]
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/rates.py#L26-L40
[ "def", "compounding", "(", "start", ",", "stop", ",", "compound", ",", "t", "=", "0.0", ")", ":", "curr", "=", "float", "(", "start", ")", "while", "True", ":", "yield", "_clip", "(", "curr", ",", "start", ",", "stop", ")", "curr", "*=", "compound"...
90129be5f0d6c665344245a7c37dbe1b8afceea2
train
slanted_triangular
Yield an infinite series of values according to Howard and Ruder's "slanted triangular learning rate" schedule.
thinc/rates.py
def slanted_triangular(max_rate, num_steps, cut_frac=0.1, ratio=32, decay=1, t=0.0): """Yield an infinite series of values according to Howard and Ruder's "slanted triangular learning rate" schedule. """ cut = int(num_steps * cut_frac) while True: t += 1 if t < cut: p = t...
def slanted_triangular(max_rate, num_steps, cut_frac=0.1, ratio=32, decay=1, t=0.0): """Yield an infinite series of values according to Howard and Ruder's "slanted triangular learning rate" schedule. """ cut = int(num_steps * cut_frac) while True: t += 1 if t < cut: p = t...
[ "Yield", "an", "infinite", "series", "of", "values", "according", "to", "Howard", "and", "Ruder", "s", "slanted", "triangular", "learning", "rate", "schedule", "." ]
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/rates.py#L56-L68
[ "def", "slanted_triangular", "(", "max_rate", ",", "num_steps", ",", "cut_frac", "=", "0.1", ",", "ratio", "=", "32", ",", "decay", "=", "1", ",", "t", "=", "0.0", ")", ":", "cut", "=", "int", "(", "num_steps", "*", "cut_frac", ")", "while", "True", ...
90129be5f0d6c665344245a7c37dbe1b8afceea2
train
equal_length
Check that arguments have the same length.
thinc/check.py
def equal_length(*args): """Check that arguments have the same length. """ for i, arg in enumerate(args): if not isinstance(arg, Sized): raise ExpectedTypeError(arg, ["Sized"]) if i >= 1 and len(arg) != len(args[0]): raise DifferentLengthError(args, arg)
def equal_length(*args): """Check that arguments have the same length. """ for i, arg in enumerate(args): if not isinstance(arg, Sized): raise ExpectedTypeError(arg, ["Sized"]) if i >= 1 and len(arg) != len(args[0]): raise DifferentLengthError(args, arg)
[ "Check", "that", "arguments", "have", "the", "same", "length", "." ]
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/check.py#L24-L31
[ "def", "equal_length", "(", "*", "args", ")", ":", "for", "i", ",", "arg", "in", "enumerate", "(", "args", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "Sized", ")", ":", "raise", "ExpectedTypeError", "(", "arg", ",", "[", "\"Sized\"", "]", ...
90129be5f0d6c665344245a7c37dbe1b8afceea2
train
equal_axis
Check that elements have the same dimension on specified axis.
thinc/check.py
def equal_axis(*args, **axis): """Check that elements have the same dimension on specified axis. """ axis = axis.get("axis", -1) for i, arg in enumerate(args): if not isinstance(arg, ndarray): raise ExpectedTypeError(arg, ["ndarray"]) if axis >= 0 and (axis + 1) < arg.shape[a...
def equal_axis(*args, **axis): """Check that elements have the same dimension on specified axis. """ axis = axis.get("axis", -1) for i, arg in enumerate(args): if not isinstance(arg, ndarray): raise ExpectedTypeError(arg, ["ndarray"]) if axis >= 0 and (axis + 1) < arg.shape[a...
[ "Check", "that", "elements", "have", "the", "same", "dimension", "on", "specified", "axis", "." ]
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/check.py#L34-L45
[ "def", "equal_axis", "(", "*", "args", ",", "*", "*", "axis", ")", ":", "axis", "=", "axis", ".", "get", "(", "\"axis\"", ",", "-", "1", ")", "for", "i", ",", "arg", "in", "enumerate", "(", "args", ")", ":", "if", "not", "isinstance", "(", "arg...
90129be5f0d6c665344245a7c37dbe1b8afceea2
train
has_shape
Check that a particular argument is an array with a given shape. The shape may contain string attributes, which will be fetched from arg0 to the function (usually self).
thinc/check.py
def has_shape(shape): """Check that a particular argument is an array with a given shape. The shape may contain string attributes, which will be fetched from arg0 to the function (usually self). """ def has_shape_inner(arg_id, args, kwargs): self = args[0] arg = args[arg_id] ...
def has_shape(shape): """Check that a particular argument is an array with a given shape. The shape may contain string attributes, which will be fetched from arg0 to the function (usually self). """ def has_shape_inner(arg_id, args, kwargs): self = args[0] arg = args[arg_id] ...
[ "Check", "that", "a", "particular", "argument", "is", "an", "array", "with", "a", "given", "shape", ".", "The", "shape", "may", "contain", "string", "attributes", "which", "will", "be", "fetched", "from", "arg0", "to", "the", "function", "(", "usually", "s...
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/check.py#L48-L71
[ "def", "has_shape", "(", "shape", ")", ":", "def", "has_shape_inner", "(", "arg_id", ",", "args", ",", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "arg", "=", "args", "[", "arg_id", "]", "if", "not", "hasattr", "(", "arg", ",", "\"shape...
90129be5f0d6c665344245a7c37dbe1b8afceea2
train
Model.define_operators
Bind operators to specified functions for the scope of the context: Example ------- model = Model() other = Model() with Model.define_operators({"+": lambda self, other: "plus"}): print(model + other) # "plus" print(model ...
thinc/neural/_classes/model.py
def define_operators(cls, operators): """Bind operators to specified functions for the scope of the context: Example ------- model = Model() other = Model() with Model.define_operators({"+": lambda self, other: "plus"}): print(model + other) ...
def define_operators(cls, operators): """Bind operators to specified functions for the scope of the context: Example ------- model = Model() other = Model() with Model.define_operators({"+": lambda self, other: "plus"}): print(model + other) ...
[ "Bind", "operators", "to", "specified", "functions", "for", "the", "scope", "of", "the", "context", ":" ]
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/neural/_classes/model.py#L35-L53
[ "def", "define_operators", "(", "cls", ",", "operators", ")", ":", "old_ops", "=", "dict", "(", "cls", ".", "_operators", ")", "for", "op", ",", "func", "in", "operators", ".", "items", "(", ")", ":", "cls", ".", "_operators", "[", "op", "]", "=", ...
90129be5f0d6c665344245a7c37dbe1b8afceea2
train
Model.use_device
Change the device to execute on for the scope of the block.
thinc/neural/_classes/model.py
def use_device(cls, device): """Change the device to execute on for the scope of the block.""" if device == cls.ops.device: yield else: curr_Ops, curr_ops = (cls.Ops, cls.ops) cls.Ops = get_ops(device) cls.ops = cls.Ops() yield ...
def use_device(cls, device): """Change the device to execute on for the scope of the block.""" if device == cls.ops.device: yield else: curr_Ops, curr_ops = (cls.Ops, cls.ops) cls.Ops = get_ops(device) cls.ops = cls.Ops() yield ...
[ "Change", "the", "device", "to", "execute", "on", "for", "the", "scope", "of", "the", "block", "." ]
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/neural/_classes/model.py#L57-L67
[ "def", "use_device", "(", "cls", ",", "device", ")", ":", "if", "device", "==", "cls", ".", "ops", ".", "device", ":", "yield", "else", ":", "curr_Ops", ",", "curr_ops", "=", "(", "cls", ".", "Ops", ",", "cls", ".", "ops", ")", "cls", ".", "Ops",...
90129be5f0d6c665344245a7c37dbe1b8afceea2
train
Model.evaluate
x Must match expected type Must match expected shape y Must match expected type
thinc/neural/_classes/model.py
def evaluate(self, X, y): """ x Must match expected type Must match expected shape y Must match expected type """ scores = self.ops.flatten(list(self.pipe(X))) if not hasattr(y, "shape"): y = self.ops.flatten(y) scor...
def evaluate(self, X, y): """ x Must match expected type Must match expected shape y Must match expected type """ scores = self.ops.flatten(list(self.pipe(X))) if not hasattr(y, "shape"): y = self.ops.flatten(y) scor...
[ "x", "Must", "match", "expected", "type", "Must", "match", "expected", "shape", "y", "Must", "match", "expected", "type" ]
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/neural/_classes/model.py#L207-L223
[ "def", "evaluate", "(", "self", ",", "X", ",", "y", ")", ":", "scores", "=", "self", ".", "ops", ".", "flatten", "(", "list", "(", "self", ".", "pipe", "(", "X", ")", ")", ")", "if", "not", "hasattr", "(", "y", ",", "\"shape\"", ")", ":", "y"...
90129be5f0d6c665344245a7c37dbe1b8afceea2
train
check_learns_zero_output_rnn
Check we can learn to output a zero vector
examples/wrap_pytorch_rnn.py
def check_learns_zero_output_rnn(model, sgd, X, Y, initial_hidden=None): """Check we can learn to output a zero vector""" outputs, get_dX = model.begin_update(X, initial_hidden) Yh, h_n = outputs tupleDy = (Yh - Y, h_n) dX = get_dX(tupleDy, sgd=sgd) prev = numpy.abs(Yh.sum()) print(prev) ...
def check_learns_zero_output_rnn(model, sgd, X, Y, initial_hidden=None): """Check we can learn to output a zero vector""" outputs, get_dX = model.begin_update(X, initial_hidden) Yh, h_n = outputs tupleDy = (Yh - Y, h_n) dX = get_dX(tupleDy, sgd=sgd) prev = numpy.abs(Yh.sum()) print(prev) ...
[ "Check", "we", "can", "learn", "to", "output", "a", "zero", "vector" ]
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/examples/wrap_pytorch_rnn.py#L60-L76
[ "def", "check_learns_zero_output_rnn", "(", "model", ",", "sgd", ",", "X", ",", "Y", ",", "initial_hidden", "=", "None", ")", ":", "outputs", ",", "get_dX", "=", "model", ".", "begin_update", "(", "X", ",", "initial_hidden", ")", "Yh", ",", "h_n", "=", ...
90129be5f0d6c665344245a7c37dbe1b8afceea2
train
PyTorchWrapper.begin_update
Return the output of the wrapped PyTorch model for the given input, along with a callback to handle the backward pass.
thinc/extra/wrappers.py
def begin_update(self, x_data, drop=0.0): """Return the output of the wrapped PyTorch model for the given input, along with a callback to handle the backward pass. """ x_var = torch.autograd.Variable(xp2torch(x_data), requires_grad=True) # Make prediction y_var = self._m...
def begin_update(self, x_data, drop=0.0): """Return the output of the wrapped PyTorch model for the given input, along with a callback to handle the backward pass. """ x_var = torch.autograd.Variable(xp2torch(x_data), requires_grad=True) # Make prediction y_var = self._m...
[ "Return", "the", "output", "of", "the", "wrapped", "PyTorch", "model", "for", "the", "given", "input", "along", "with", "a", "callback", "to", "handle", "the", "backward", "pass", "." ]
explosion/thinc
python
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/extra/wrappers.py#L47-L66
[ "def", "begin_update", "(", "self", ",", "x_data", ",", "drop", "=", "0.0", ")", ":", "x_var", "=", "torch", ".", "autograd", ".", "Variable", "(", "xp2torch", "(", "x_data", ")", ",", "requires_grad", "=", "True", ")", "# Make prediction", "y_var", "=",...
90129be5f0d6c665344245a7c37dbe1b8afceea2