INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Called when the comm is changed. | 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 |
Close method. | 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()
... |
Sends the widget state or a piece of it to the front - end if it exists. | 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... |
Gets the widget state or a piece of it. | 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 ... |
Called when a state is received from the front - end. | 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... |
( Un ) Register a custom msg receive callback. | 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 widget displayed callback. | 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... |
Dynamically add trait attributes to the Widget. | 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) |
Called when a property has changed. | 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... |
Hold syncing any state until the outermost context manager exits | 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
... |
Check the property lock ( property_lock ) | 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... |
Called when a msg is received from the front - end | 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 IPython. display. display is called on the widget. | 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... |
Sends a message to the model in the front - end. | 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) |
Add int docstring template to class init. | 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 bounded int docstring template to class init. | 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:
... |
Serialize a Python datetime object to json. | 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')
... |
Deserialize a Python datetime object from json. | 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... |
Serialize a Python date object. | 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... |
Find references to other widgets in a widget s state | 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:
... |
Gets the embed state of a widget and all other widgets it refers to as well | 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 ... |
Adds the state of any link models between two models in store | 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... |
Get the state of all widgets specified and their dependencies. | 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... |
Gets data for embedding. | 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.
... |
Return a snippet that can be embedded in an HTML file. | 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
-... |
Write a minimal HTML file with widget views embedded. | 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.
... |
Standardize the options tuple format. | 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... |
A function that uses the compare function to return a value from the list. | 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) |
Set the values and labels and select the first option if we aren t initializing | 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... |
Propagate changes in index to the value and label properties | 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:
... |
Check the range of each proposed index. | 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') |
Replace all values with the actual objects in the options list | 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') |
Adds a class to the top level element of the widget. | 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 |
Removes a class from the top level element of the widget. | 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... |
Register the jupyter. widget comm target | 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) |
Substitute format strings in class or function docstring | 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_... |
Get absolute path to resource works for dev and for PyInstaller | 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... |
: 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 | 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... |
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 | 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.... |
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. | 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 View menu that shows Enter Full Screen. | 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... |
Convert given hex color to NSColor. | 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])... |
Return a BrowserView instance by the: value of its given: attribute and None if no match is found. | 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 PyObjCMethodSignature object for given signature string. | 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... |
Invoke a folder selection dialog here: return: | 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 =... |
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.
"""
... |
Decorator to call a pywebview API checking for _webview_ready and raisings appropriate Exceptions on failure. | 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... |
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 600px: param resizable T... | 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 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: Default filename for save file dialog.... | 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... |
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 entry point.: p... | 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... |
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 | 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... |
Setup data layer according to parameters: | 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... |
Load input image and preprocess for Caffe: - cast to float - switch channels RGB - > BGR - subtract mean - transpose to channel x height x width order | 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 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. | 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 pre - processed depth for NYUDv2 segmentation set. | 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 HHA features from Gupta et al. ECCV14. See https:// github. com/ s - gupta/ rcnn - depth/ blob/ master/ rcnn/ saveHHA. m | 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 input image and preprocess for Caffe: - cast to float - switch channels RGB - > BGR - subtract mean - transpose to channel x height x width order | 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 label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. | 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... |
Make a 2D bilinear kernel suitable for upsampling | 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 ... |
Returns accuracy score evaluation result. | 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... |
Transfer weights by copying matching parameters coercing parameters of incompatible shape and dropping unmatched parameters. | 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... |
Set weights of each layer in layers to bilinear kernels for interpolation. | 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
... |
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. | 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... |
Setup data layer according to parameters: | 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: | 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... |
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. | 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. | 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... |
Transfer the VOC color palette to an output mask for visualization. | 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 |
Deterministically shuffle identically under both py2 + py3. | 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(... |
In this context os. environ is modified according to patch. | 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... |
On windows there s a different directory for the virtualenv | 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) |
Install the pre - commit hooks. | 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... |
Uninstall the pre - commit hooks. | 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_... |
Fixes for the following issues on windows - https:// bugs. python. org/ issue8557 - windows does not parse shebangs | 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... |
Prints a message for running a hook. | 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 ... |
See https:// github. com/ pre - commit/ pre - commit/ issues/ 354 | 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 =... |
A simplified implementation of xargs. | 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)
... |
Makes an archive of a repository in the given destdir. | 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... |
Compute the number of columns to display hook messages. The widest that will be displayed is in the no files skipped case: | 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 ... |
Actually run the hooks. | 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... |
On windows rmtree fails for readonly dirs. | 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
):
... |
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 | 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
"""
... |
Auto - update the pre - commit config to the latest versions of repos. | 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... |
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. | 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
- ... |
As of Windows 10 the Windows console supports ( some ) ANSI escape sequences but it needs to be enabled using SetConsoleMode first. | 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... |
Format text with color. | 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:
... |
Choose whether to use color based on the command argument. | 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... |
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. | 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... |
Perform a shallow clone of a repository and its submodules | 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(
'-... |
Clone the given url and checkout the specific ref. | 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', *... |
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. | 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 values according to Howard and Ruder s slanted triangular learning rate schedule. | 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... |
Check that arguments have the same length. | 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 elements have the same dimension on specified axis. | 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 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(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]
... |
Bind operators to specified functions for the scope of the context: | 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)
... |
Change the device to execute on for the scope of the block. | 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
... |
x Must match expected type Must match expected shape y Must match expected type | 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... |
Check we can learn to output a zero vector | 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)
... |
Return the output of the wrapped PyTorch model for the given input along with a callback to handle the backward pass. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.