utool._internal package

Submodules

utool._internal.__prefwidg_dep module

from __future__ import absolute_import, division, print_function import sys import traceback from utool.Preferences import Pref # Qt from guitool.__PyQt__ import QtCore, QtGui from guitool.__PyQt__.Qt import (QAbstractItemModel, QModelIndex, QVariant, QWidget,

QString, Qt, QObject, pyqtSlot)

# Decorator to help catch errors that QT wont report def report_thread_error(fn):

def report_thread_error_wrapper(*args, **kwargs):
try:
ret = fn(*args, **kwargs) return ret
except Exception as ex:
print(‘nn !! Thread Raised Exception: ‘ + str(ex)) print(‘nn !! Thread Exception Traceback: nn’ + traceback.format_exc()) sys.stdout.flush() et, ei, tb = sys.exc_info() raise

return report_thread_error_wrapper

# — # Functions # — try:

_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:

_encoding = QtGui.QApplication.UnicodeUTF8

def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)

# — # THE ABSTRACT ITEM MODEL # — #QComboBox class QPreferenceModel(QAbstractItemModel):

“”” Convention states only items with column index 0 can have children “”” @report_thread_error def __init__(self, pref_struct, parent=None):

super(QPreferenceModel, self).__init__(parent) self.rootPref = pref_struct

@report_thread_error def index2Pref(self, index=QModelIndex()):

“”” Internal helper method “”” if index.isValid():

item = index.internalPointer() if item:

return item

return self.rootPref

#———– # Overloaded ItemModel Read Functions @report_thread_error def rowCount(self, parent=QModelIndex()):

parentPref = self.index2Pref(parent) return parentPref.qt_row_count()

@report_thread_error def columnCount(self, parent=QModelIndex()):

parentPref = self.index2Pref(parent) return parentPref.qt_col_count()

@report_thread_error def data(self, index, role=Qt.DisplayRole):

“”” Returns the data stored under the given role for the item referred to by the index. “”” if not index.isValid():

return QVariant()
if role != Qt.DisplayRole and role != Qt.EditRole:
return QVariant()

nodePref = self.index2Pref(index) data = nodePref.qt_get_data(index.column()) var = QVariant(data) #print(‘— data() —’) #print(‘role = %r’ % role) #print(‘data = %r’ % data) #print(‘type(data) = %r’ % type(data)) if isinstance(data, float):

var = QVariant(QString.number(data, format=’g’, precision=6))
if isinstance(data, bool):
var = QVariant(data).toString()
if isinstance(data, int):
var = QVariant(data).toString()

#print(‘var= %r’ % var) #print(‘type(var)= %r’ % type(var)) return var

@report_thread_error def index(self, row, col, parent=QModelIndex()):

“”“Returns the index of the item in the model specified by the given row, column and parent index.”“” if parent.isValid() and parent.column() != 0:

return QModelIndex()

parentPref = self.index2Pref(parent) childPref = parentPref.qt_get_child(row) if childPref:

return self.createIndex(row, col, childPref)
else:
return QModelIndex()

@report_thread_error def parent(self, index=None):

“”“Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned.”“” if index is None: # Overload with QObject.parent()

return QObject.parent(self)
if not index.isValid():
return QModelIndex()

nodePref = self.index2Pref(index) parentPref = nodePref.qt_get_parent() if parentPref == self.rootPref:

return QModelIndex()

return self.createIndex(parentPref.qt_parents_index_of_me(), 0, parentPref)

#———– # Overloaded ItemModel Write Functions @report_thread_error def flags(self, index):

“”“Returns the item flags for the given index.”“” if index.column() == 0:

# The First Column is just a label and unchangable return Qt.ItemIsEnabled | Qt.ItemIsSelectable
if not index.isValid():
return Qt.ItemFlag(0)

childPref = self.index2Pref(index) if childPref:

if childPref.qt_is_editable():
return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable

return Qt.ItemFlag(0)

@report_thread_error def setData(self, index, data, role=Qt.EditRole):

“”“Sets the role data for the item at index to value.”“” if role != Qt.EditRole:

return False

#print(‘— setData() —’) #print(‘role = %r’ % role) #print(‘data = %r’ % data) #print(‘type(data) = %r’ % type(data)) leafPref = self.index2Pref(index) result = leafPref.qt_set_leaf_data(data) if result is True:

self.dataChanged.emit(index, index)

return result

@report_thread_error def headerData(self, section, orientation, role=Qt.DisplayRole):

if orientation == Qt.Horizontal and role == Qt.DisplayRole:
if section == 0:
return QVariant(‘Config Key’)
if section == 1:
return QVariant(‘Config Value’)

return QVariant()

# — # THE PREFERENCE SKELETON # — class Ui_editPrefSkel(object):

def setupUi(self, editPrefSkel):
editPrefSkel.setObjectName(_fromUtf8(‘editPrefSkel’)) editPrefSkel.resize(668, 530) # Add Pane for TreeView self.verticalLayout = QtGui.QVBoxLayout(editPrefSkel) self.verticalLayout.setObjectName(_fromUtf8(‘verticalLayout’)) # The TreeView for QAbstractItemModel to attach to self.prefTreeView = QtGui.QTreeView(editPrefSkel) self.prefTreeView.setObjectName(_fromUtf8(‘prefTreeView’)) self.verticalLayout.addWidget(self.prefTreeView) # Add Pane for buttons self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8(‘horizontalLayout’)) # #self.redrawBUT = QtGui.QPushButton(editPrefSkel) #self.redrawBUT.setObjectName(_fromUtf8(‘redrawBUT’)) #self.horizontalLayout.addWidget(self.redrawBUT) ## #self.unloadFeaturesAndModelsBUT = QtGui.QPushButton(editPrefSkel) #self.unloadFeaturesAndModelsBUT.setObjectName(_fromUtf8(‘unloadFeaturesAndModelsBUT’)) #self.horizontalLayout.addWidget(self.unloadFeaturesAndModelsBUT) # self.defaultPrefsBUT = QtGui.QPushButton(editPrefSkel) self.defaultPrefsBUT.setObjectName(_fromUtf8(‘defaultPrefsBUT’)) self.horizontalLayout.addWidget(self.defaultPrefsBUT) # Buttons are a child of the View self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(editPrefSkel) QtCore.QMetaObject.connectSlotsByName(editPrefSkel)
def retranslateUi(self, editPrefSkel):
# UTF-8 Support editPrefSkel.setWindowTitle(_translate(‘editPrefSkel’, ‘Edit Preferences’, None)) #self.redrawBUT.setText(_translate(‘editPrefSkel’, ‘Redraw’, None)) #self.unloadFeaturesAndModelsBUT.setText(_translate(‘editPrefSkel’, ‘Unload Features and Models’, None)) self.defaultPrefsBUT.setText(_translate(‘editPrefSkel’, ‘Defaults’, None))

# — # THE PREFERENCE WIDGET # — class EditPrefWidget(QWidget):

“”“The Settings Pane; Subclass of Main Windows.”“” def __init__(self, pref_struct):

super(EditPrefWidget, self).__init__() self.ui = Ui_editPrefSkel() self.ui.setupUi(self) self.pref_model = None self.populatePrefTreeSlot(pref_struct) #self.ui.redrawBUT.clicked.connect(fac.redraw) #self.ui.defaultPrefsBUT.clicked.connect(fac.default_prefs) #self.ui.unloadFeaturesAndModelsBUT.clicked.connect(fac.unload_features_and_models)

@pyqtSlot(Pref, name=’populatePrefTreeSlot’) def populatePrefTreeSlot(self, pref_struct):

“”“Populates the Preference Tree Model”“” #printDBG(‘Bulding Preference Model of: ‘ + repr(pref_struct)) #Creates a QStandardItemModel that you can connect to a QTreeView self.pref_model = QPreferenceModel(pref_struct) #printDBG(‘Built: ‘ + repr(self.pref_model)) self.ui.prefTreeView.setModel(self.pref_model) self.ui.prefTreeView.header().resizeSection(0, 250)
def refresh_layout(self):
self.pref_model.layoutAboutToBeChanged.emit() self.pref_model.layoutChanged.emit()

utool._internal.meta_util_arg module

utool._internal.meta_util_arg.get_argflag(flag)[source]
utool._internal.meta_util_arg.get_argval(argstr, type_=None, default=None)[source]

Returns a value of an argument specified on the command line after some flag

python -c “import utool; print([(type(x), x) for x in [utool.get_argval(‘–quest’)]])” –quest=”holy grail” python -c “import utool; print([(type(x), x) for x in [utool.get_argval(‘–quest’)]])” –quest=”42” python -c “import utool; print([(type(x), x) for x in [utool.get_argval(‘–quest’)]])” –quest=42 python -c “import utool; print([(type(x), x) for x in [utool.get_argval(‘–quest’)]])” –quest 42 python -c “import utool; print([(type(x), x) for x in [utool.get_argval(‘–quest’, float)]])” –quest 42

>>> from utool.util_arg import *  # NOQA
>>> import sys
>>> sys.argv.extend(['--spam', 'eggs', '--quest=holy grail', '--ans=42'])
>>> get_argval('--spam', type_=str, default=None)
eggs
>>> get_argval('--quest', type_=str, default=None)
holy grail
>>> get_argval('--ans', type_=int, default=None)
42

utool._internal.meta_util_cache module

utool._internal.meta_util_cache.global_cache_read(key, appname=None, **kwargs)[source]

utool._internal.meta_util_constants module

utool._internal.meta_util_cplat module

utool._internal.meta_util_cplat.get_app_resource_dir(*args, **kwargs)[source]

Returns a writable directory for an application Input: appname - the name of the application

*args, - any other subdirectories may be specified
utool._internal.meta_util_cplat.get_resource_dir()[source]

Returns a directory which should be writable for any application

utool._internal.meta_util_dbg module

utool._internal.meta_util_dbg.get_caller_lineno(N=0, strict=True)[source]
utool._internal.meta_util_dbg.get_caller_name(N=0, strict=True)[source]

Standalone version of get_caller_name

utool._internal.meta_util_dbg.get_stack_frame(N=0, strict=True)[source]

utool._internal.meta_util_git module

utool._internal.meta_util_git.can_push(repo_url)[source]
utool._internal.meta_util_git.cd(dir_)[source]
utool._internal.meta_util_git.cmd(command)[source]
utool._internal.meta_util_git.ensure_ssh_url(repo_url)[source]
utool._internal.meta_util_git.fix_repo_url(repo_url, in_type=u'https', out_type=u'ssh', format_dict={u'ssh': (u'.com:', u'git@'), u'https': (u'.com/', u'https://')})[source]

Changes the repo_url format

utool._internal.meta_util_git.get_computer_name()[source]
utool._internal.meta_util_git.get_repo_dirs(repo_urls, checkout_dir)[source]

# TODO Fix name

utool._internal.meta_util_git.get_repo_dname(repo_url)[source]

Break url into a dirname

utool._internal.meta_util_git.repo_list(repo_urls, checkout_dir, forcessh=False)[source]
utool._internal.meta_util_git.set_userid(userid=None, permitted_repos=[])[source]
utool._internal.meta_util_git.url_list(repo_urls, forcessh=False)[source]

utool._internal.meta_util_iter module

utool._internal.meta_util_iter.ensure_iterable(obj)[source]
Parameters:obj (scalar or iterable) –
Returns:obj if it was iterable otherwise [obj]
Return type:it3erable

CommandLine:

python -m utool._internal.meta_util_iter --test-ensure_iterable
Timeit:
%timeit ut.ensure_iterable([1]) %timeit ut.ensure_iterable(1) %timeit ut.ensure_iterable(np.array(1)) %timeit ut.ensure_iterable([1]) %timeit [1]

Example

>>> # DISABLE_DOCTEST
>>> from utool._internal.meta_util_iter import *  # NOQA
>>> # build test data
>>> obj_list = [3, [3], '3', (3,), [3,4,5]]
>>> # execute function
>>> result = [ensure_iterable(obj) for obj in obj_list]
>>> # verify results
>>> result = str(result)
>>> print(result)
[[3], [3], ['3'], (3,), [3, 4, 5]]
utool._internal.meta_util_iter.isiterable(obj)[source]

Returns if the object can be iterated over and is NOT a string # TODO: implement isscalar similar to numpy

Parameters:obj (scalar or iterable) –
Returns:
Return type:bool

CommandLine:

python -m utool._internal.meta_util_iter --test-isiterable

Example

>>> # DISABLE_DOCTEST
>>> from utool._internal.meta_util_iter import *  # NOQA
>>> # build test data
>>> obj_list = [3, [3], '3', (3,), [3,4,5]]
>>> # execute function
>>> result = [isiterable(obj) for obj in obj_list]
>>> # verify results
>>> print(result)
[False, True, False, True, True]

utool._internal.meta_util_path module

utool._internal.meta_util_path.ensuredir(dpath)[source]
utool._internal.meta_util_path.truepath(path)[source]

Normalizes and returns absolute path with so specs

utool._internal.meta_util_path.unixjoin(*args)[source]

Like os.path.join, but uses forward slashes on win32

utool._internal.meta_util_path.unixpath(path)[source]

TODO: rename to unix_truepath Corrects fundamental problems with windows paths.~

utool._internal.meta_util_six module

utool._internal.meta_util_six.ensure_unicode(str_)[source]
TODO:
rob gp “isinstance(.*\bstr\b)”
utool._internal.meta_util_six.get_funccode(func)[source]
utool._internal.meta_util_six.get_funcdoc(func)[source]
utool._internal.meta_util_six.get_funcglobals(func)[source]
utool._internal.meta_util_six.get_funcname(func)[source]

Weird behavior for classes I dont know why this returns type / None import lasagne lasagne.layers.InputLayer lasagne.layers.InputLayer.__module__ lasagne.layers.InputLayer.__class__.__name__ == ‘type’ lasagne.layers.InputLayer.__class__ is type wtf

utool._internal.meta_util_six.get_imfunc(func)[source]
utool._internal.meta_util_six.set_funcdoc(func, newdoc)[source]
utool._internal.meta_util_six.set_funcname(func, newname)[source]

utool._internal.py2_syntax_funcs module

utool._internal.py2_syntax_funcs.ignores_exc_tb(*args, **kwargs)[source]

PYTHON 2 ONLY VERSION – needs to be in its own file for syntactic reasons

ignore_exc_tb decorates a function and remove both itself and the function from any exception traceback that occurs.

This is useful to decorate other trivial decorators which are polluting your stacktrace.

utool._internal.randomwrap module

This is a minimal Python client for Mads Haahr’s random number generator at www.random.org

# This tiny set of functions only implements a subset of the HTTP interface available. In particular it only uses the ‘live’ # random number generator, and doesn’t offer the option of using the alternative ‘stored’ random # number sets. However, it should be obvious how to extend it by sending requests with different parameters. # The web service code is modelled on Mark Pilgrim’s “Dive into Python” tutorial at http://www.diveintopython.org/http_web_services # This client by George Dunbar, University of Warwick (Copyright George Dunbar, 2008) # It is distributed under the Gnu General Public License.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

See <http://www.gnu.org/licenses/> for a copy of the GNU General Public License. For use that falls outside this license, please contact me.

To use in a python script or at the interactive prompt (randomwrapy.py has to be in the Python search path, of course):

from randomwrapy import *

rnumlistwithoutreplacement(0, 12)
# returns a list of the integers 0 - 12 inclusive, in a random order
rnumlistwithreplacement(12, 5)
# returns 12 integers from the range [0, 5]
rnumlistwithreplacement(12, 5, 2)
# returns 12 integers from the range [2, 5]
rrandom()
# returns a random float in the range [0, 1]
reportquota()
# tells you how many bits you have available; visit www.random.org/quota for more information

Arguments where given are (must be) numbers, of course. There is almost no error checking in these scripts! For example, if the web site is down, Python will simply raise an exception and report the http error code. See worldrandom.py for an alternative implementation that goes a little further with error checking.

utool._internal.randomwrap.build_request_parameterNR(min, max)[source]
utool._internal.randomwrap.build_request_parameterWR(howmany, min, max)[source]
utool._internal.randomwrap.checkquota()[source]
utool._internal.randomwrap.reportquota()[source]
utool._internal.randomwrap.rnumlistwithoutreplacement(min, max)[source]

Returns a randomly ordered list of the integers between min and max

utool._internal.randomwrap.rnumlistwithreplacement(howmany, max, min=0)[source]

Returns a list of howmany integers with a maximum value = max. The minimum value defaults to zero.

utool._internal.randomwrap.rrandom()[source]

Get the next random number in the range [0.0, 1.0]. Returns a float.

utool._internal.util_importer module

NEEDS CLEANUP SO IT EITHER DOES THE IMPORTS OR GENERATES THE FILE

python -c “import utool”

utool._internal.util_importer.dynamic_import(modname, IMPORT_TUPLES, developing=True, ignore_froms=[], dump=False, ignore_startswith=[], ignore_endswith=[], ignore_list=[], verbose=False)[source]

MAIN ENTRY POINT

Dynamically import listed util libraries and their attributes. Create reload_subs function.

Using __import__ like this is typically not considered good style However, it is better than import * and this will generate the good file text that can be used when the module is ‘frozen”

utool._internal.util_importer.make_import_tuples(module_path, exclude_modnames=[])[source]

Infer the IMPORT_TUPLES from a module_path

utool._internal.util_importer.make_initstr(modname, IMPORT_TUPLES, verbose=False)[source]

Just creates the string representation. Does no importing.

utool._internal.win32_send_keys module

Module contents

Need to hack to make work for internal modules and reload subs properly

Regen Command:
cd /home/joncrall/code/utool/utool/_internal makeinit.py -x win32_send_keys