def reload_addons(do_reload=True, do_reverse=True): modules = addon_utils.modules({}) modules.sort(key=lambda mod: mod.__name__) addons = bpy.context.user_preferences.addons # first disable all for mod_name in list(addons.keys()): addon_utils.disable(mod_name) assert(bool(addons) == False) # Run twice each time. for i in (0, 1): for mod in modules: mod_name = mod.__name__ print("\tenabling:", mod_name) addon_utils.enable(mod_name) assert(mod_name in addons) for mod in addon_utils.modules({}): mod_name = mod.__name__ print("\tdisabling:", mod_name) addon_utils.disable(mod_name) assert(not (mod_name in addons)) # now test reloading if do_reload: imp.reload(sys.modules[mod_name]) if do_reverse: # in case order matters when it shouldnt modules.reverse()
def generate_stub_for_module(module: str, output_dir: str, quiet: bool = False, add_header: bool = False, sigs: Dict[str, str] = {}, class_sigs: Dict[str, str] = {}, pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION) -> None: if pyversion[0] == 2: module_path, module_all = load_python2_module_info(module) else: mod = importlib.import_module(module) imp.reload(mod) if is_c_module(mod): target = module.replace('.', '/') + '.pyi' target = os.path.join(output_dir, target) generate_stub_for_c_module(module_name=module, target=target, add_header=add_header, sigs=sigs, class_sigs=class_sigs) return target module_path = mod.__file__ module_all = getattr(mod, '__all__', None) target = module.replace('.', '/') if os.path.basename(module_path) == '__init__.py': target += '/__init__.pyi' else: target += '.pyi' target = os.path.join(output_dir, target) generate_stub(module_path, output_dir, module_all, target=target, add_header=add_header, module=module, pyversion=pyversion) if not quiet: print('Created %s' % target) return target
def setup_method(self, method): imp.reload(configreader) imp.reload(test.config.app) context.setup( app='test', app_config=test.config.app.TestingConfig() ) context.setup_thread_id() context.default_log.info( '%s %s::%s %s' % ('=' * 20, self.__class__.__name__, self._testMethodName, '=' * 20) ) # modify http client to store http requests from amplify.agent.util.http import HTTPClient self.http_requests = [] original_get = HTTPClient.get original_post = HTTPClient.post def fake_get(obj, url, *args, **kwargs): self.http_requests.append(url) return original_get(obj, url, *args, **kwargs) def fake_post(obj, url, *args, **kwargs): self.http_requests.append(url) return original_post(obj, url, *args, **kwargs) HTTPClient.get = fake_get HTTPClient.post = fake_post
def test_view_context_fallback(self): """ Tests that the FaqByCategoryView produces the correct context when requesting a category in an untranslated language. """ category_2 = self.reload(self.category2, "en") category_2_url = category_2.get_absolute_url() question_2 = self.reload(self.question2, "en") request = self.get_page_request( page=self.page, user=self.user, path=category_2_url, ) url_kwargs = resolve(category_2_url).kwargs with self.settings(**self.enabled_parler_fallback_settings): reload(parler.appsettings) try: response = FaqByCategoryView.as_view()(request, **url_kwargs) except Http404: self.fail('Could not find category') self.assertEqualItems( response.context_data['object_list'], [question_2, ], )
def testPortable(self): # Overrides all XDG_* variables os.environ['ZEROINSTALL_PORTABLE_BASE'] = '/portable' imp.reload(basedir) self.assertEqual('/portable/config', basedir.xdg_config_home) self.assertEqual('/portable/cache', basedir.xdg_cache_home) self.assertEqual('/portable/data', basedir.xdg_data_home) self.assertEqual(['/portable/config'], basedir.xdg_config_dirs) self.assertEqual(['/portable/cache'], basedir.xdg_cache_dirs) self.assertEqual(['/portable/data'], basedir.xdg_data_dirs) del os.environ['ZEROINSTALL_PORTABLE_BASE'] os.environ['XDG_CONFIG_HOME'] = '/home/me/config' os.environ['XDG_CONFIG_DIRS'] = '/system/config' os.environ['XDG_DATA_HOME'] = '/home/me/data' os.environ['XDG_DATA_DIRS'] = '/system/data' + os.pathsep + '/disto/data' os.environ['XDG_CACHE_HOME'] = '/home/me/cache' os.environ['XDG_CACHE_DIRS'] = '/system/cache' imp.reload(basedir) self.assertEqual('/home/me/config', basedir.xdg_config_home) self.assertEqual('/home/me/cache', basedir.xdg_cache_home) self.assertEqual('/home/me/data', basedir.xdg_data_home) self.assertEqual(['/home/me/config', '/system/config'], basedir.xdg_config_dirs) self.assertEqual(['/home/me/cache', '/system/cache'], basedir.xdg_cache_dirs) self.assertEqual(['/home/me/data', '/system/data', '/disto/data'], basedir.xdg_data_dirs)
def reload_nodefunction(self): from micropsi_core.nodenet import nodefunctions if self.nodefunction_name and not self.nodefunction_definition and not hasattr(nodefunctions, self.nodefunction_name): import nodefunctions as custom_nodefunctions from imp import reload reload(custom_nodefunctions) self.nodefunction = getattr(custom_nodefunctions, self.nodefunction_name)
def load_messages(themes, translations, default_lang): """ Load theme's messages into context. All the messages from parent themes are loaded, and "younger" themes have priority. """ messages = Functionary(dict, default_lang) oldpath = sys.path[:] for theme_name in themes[::-1]: msg_folder = os.path.join(get_theme_path(theme_name), 'messages') default_folder = os.path.join(get_theme_path('base'), 'messages') sys.path.insert(0, default_folder) sys.path.insert(0, msg_folder) english = __import__('messages_en') for lang in list(translations.keys()): # If we don't do the reload, the module is cached translation = __import__('messages_' + lang) reload(translation) if sorted(translation.MESSAGES.keys()) !=\ sorted(english.MESSAGES.keys()) and \ lang not in warned: warned.append(lang) LOGGER.warn("Incomplete translation for language " "'{0}'.".format(lang)) messages[lang].update(english.MESSAGES) messages[lang].update(translation.MESSAGES) del(translation) sys.path = oldpath return messages
def reset_all(reload_scripts=False): """ Sets the addon state based on the user preferences. """ import sys import imp # RELEASE SCRIPTS: official scripts distributed in Blender releases paths_list = paths() for path in paths_list: _bpy.utils._sys_path_ensure(path) for mod_name, mod_path in _bpy.path.module_names(path): is_enabled, is_loaded = check(mod_name) # first check if reload is needed before changing state. if reload_scripts: mod = sys.modules.get(mod_name) if mod: imp.reload(mod) if is_enabled == is_loaded: pass elif is_enabled: enable(mod_name) elif is_loaded: print("\taddon_utils.reset_all unloading", mod_name) disable(mod_name)
def start_window(): import import_from_xlsx if not hasattr(import_from_xlsx, 'load_state'): setattr(import_from_xlsx, 'load_state', True) else: reload(import_from_xlsx) ''' tag library ''' ''' each tag library corresponds to sqlite table name each tag corresponds to sqlite database column name ''' ''' config file ''' config = configparser.ConfigParser() config.read(controllers + 'config.ini', encoding='utf-8') def convert_to_db(): source = import_from_xlsx.import_xlsx_path.get_() destination = import_from_xlsx.destination_path.get_() convert_xlsx_to_db.convert_database(source, destination) import_from_xlsx.import_from_xlsx.destroy() import_from_xlsx.import_browse_button.settings(\ command=lambda: import_from_xlsx.import_xlsx_path.set(filedialog.askopenfile().name)) import_from_xlsx.time_browse_button.settings(\ command=lambda: import_from_xlsx.time_xlsx_path.set(filedialog.askopenfile().name)) import_from_xlsx.destination_browse_button.settings(\ command=lambda: import_from_xlsx.destination_path.set(filedialog.asksaveasfilename() + '.db')) import_from_xlsx.cancel_button.settings(command=import_from_xlsx.import_from_xlsx.destroy) import_from_xlsx.import_button.settings(command=convert_to_db)
def plugin_loaded(): from imp import reload # package control may not work correctly if SSL installed # so reload all Package Control modules to get SSL included # right print("(SSL) start reloading Package Control") import ssl # make sure http.client knows about ssl import http.client reload(http.client) # make sure urllib knows about ssl import urllib reload(urllib) import urllib.request reload(urllib.request) import urllib.response reload(urllib.response) # package Control udel ses SSL reload(sys.modules['Package Control.package_control.reloader'])
def on_plot_save(self, epoch, iter, logs={}): # import neuron sandbox # has to be here, can't be at the top, due to cyclical imports (??) # TODO: should just pass the function to compute the figures given the model and generator import neuron.sandbox as nrn_sandbox reload(nrn_sandbox) with timer.Timer('plot callback', self.verbose): if len(self.run.grid_size) == 3: collapse_2d = [0, 1, 2] else: collapse_2d = [2] exampl = nrn_sandbox.show_example_prediction_result(self.model, self.generator, self.run, self.data, test_batch_size=1, test_model_names=None, test_grid_size=self.run.grid_size, ccmap=None, collapse_2d=collapse_2d, slice_nr=None, plt_width=17, verbose=self.verbose) # save, then close figs = exampl[1:] for idx, fig in enumerate(figs): dirn = "dirn_%d" % idx slice_nr = 0 filename = self.savefilepath.format(epoch=epoch, iter=iter, axis=dirn, slice_nr=slice_nr) fig.savefig(filename) plt.close()
def test_should_work_even_without_zope_testbrowser(self): self.patch_driver("zope") from splinter import browser reload(browser) self.assertNotIn("zope.testbrowser", browser._DRIVERS) self.unpatch_driver(browser)
def test_attributes__windows(self): sys.platform = "win32" imp.reload(aeidon) for player in aeidon.players: assert hasattr(player, "command") assert hasattr(player, "command_utf_8") assert hasattr(player, "label")
def doprocesstestimport(self): print("[Importing Test Files]") imp.reload(guiimportraws) guiimportraws.importrawsdialog(self.test, projectfolder=self.fs, parent=self)
def reload(self, irc, msg, args, name): """<plugin> Unloads and subsequently reloads the plugin by name; use the 'list' command to see a list of the currently loaded plugins. """ callbacks = irc.removeCallback(name) if callbacks: module = sys.modules[callbacks[0].__module__] if hasattr(module, 'reload'): x = module.reload() try: module = plugin.loadPluginModule(name) if hasattr(module, 'reload') and 'x' in locals(): module.reload(x) if hasattr(module, 'config'): reload(module.config) for callback in callbacks: callback.die() del callback gc.collect() # This makes sure the callback is collected. callback = plugin.loadPluginClass(irc, module) irc.replySuccess() except ImportError: for callback in callbacks: irc.addCallback(callback) irc.error('No plugin %s exists.' % name) else: irc.error('There was no plugin %s.' % name)
def load_module(modname, quiet=False, **kwargs): '''load a module''' modpaths = ['MAVProxy.modules.mavproxy_%s' % modname, modname] for (m,pm) in mpstate.modules: if m.name == modname and not modname in mpstate.multi_instance: if not quiet: print("module %s already loaded" % modname) # don't report an error return True ex = None for modpath in modpaths: try: m = import_package(modpath) reload(m) module = m.init(mpstate, **kwargs) if isinstance(module, mp_module.MPModule): mpstate.modules.append((module, m)) if not quiet: if kwargs: print("Loaded module %s with kwargs = %s" % (modname, kwargs)) else: print("Loaded module %s" % (modname,)) return True else: ex = "%s.init did not return a MPModule instance" % modname break except ImportError as msg: ex = msg if mpstate.settings.moddebug > 1: import traceback print(traceback.format_exc()) print("Failed to load module: %s. Use 'set moddebug 3' in the MAVProxy console to enable traceback" % ex) return False
def load_hook_modules(self): """Loads any module in the hooks directory as hook handlers""" if not self.directory: return if not isdir(self.directory): logger.error("Hooks directory is not a directory: %s" % str(self.directory)) return with self._lock: for filename in next(walk(self.directory))[2]: if filename.endswith('.py'): module = filename[:-3] self.modules.add(module) else: logger.info("Ignoring %s" % filename) for m in self.modules: try: if m in sys.modules: logger.info("Reloading %s" % m) reload(sys.modules[m]) else: logger.info("Loading %s" % m) __import__(m) except: logger.error("Could not load hook: %s" % m) for m in self.modules - set(sys.modules.keys()): self.modules.remove(m)
def test_upgrade(self): """Make sure peep installing a GitHub-sourced tarball installs it, even if its version hasn't changed. """ try: activate('pip>=1.0.1') except RuntimeError: raise SkipTest("This version of pip is so old that #egg= parsing " "doesn't work right.") # Install an old version: self.install_from_string( """# sha256: Q7PVYWdV3NFZ3bkx5bNmUd74UTCe7jrwf2AeM4wUD1A {index_url}useless/1234567.zip#egg=useless""".format( index_url=self.index_url())) # Make sure it worked: import useless reload(useless) # in case another test imports it first eq_(useless.git_hash, '1234567') # Install the new version: self.install_from_string( """# sha256: JIAjkT1OSM1PIxLbvKk46W4iOTqH9yHASHTwvGVEC4k {index_url}useless/789abcd.zip#egg=useless""".format( index_url=self.index_url())) # Make sure the new version is really installed: reload(useless) eq_(useless.git_hash, '789abcd') # Clean up: run('pip uninstall -y useless')
def test_without_openssl_crypto(self): import imp imp_find_module = imp.find_module orig_sys_path = sys.path orig_isfile = os.path.isfile openssl_module = imp.find_module('OpenSSL') def find_module(module_name): if module_name == 'OpenSSL': return openssl_module raise ImportError('No module named %s' % module_name) try: for m in list(sys.modules): if m.startswith('OpenSSL'): sys.modules.pop(m) sys.path = [] imp.find_module = find_module os.path.isfile = lambda filename: False reload(crypt) self.assertRaises(NotImplementedError, crypt.pkcs12_key_as_pem, 'FOO', 'BAR') finally: sys.path = orig_sys_path imp.find_module = imp_find_module os.path.isfile = orig_isfile import OpenSSL.crypto reload(crypt)
def loadPlugins(self): if "plugins" in dir(self): self.saveSettings() self.help = {} self.commands = {} self.contentCommands = {} self.queryCommands = {} self.plugins = [] try: reload(__import__('plugins')) for i in __import__('plugins').__all__: try: plugin = __import__('plugins.%s' % i, fromlist=[None]) reload(plugin) if "mainclass" in dir(plugin): print("Loading", i) obj = plugin.mainclass(self) if self.config.has_section(plugin.__name__): conflist = self.config.items(plugin.__name__) conf = {} for c in conflist: conf[c[0]] = c[1] obj.setConfig(conf) else: print("No config for plugin %s" % (plugin.__name__)) self.plugins.append(obj) except: traceback.print_exc() except: traceback.print_exc()
def test_reload(self): """ reload has been moved to the imp module """ import imp imp.reload(imp) self.assertTrue(True)
def load_module(modname, quiet=False): '''load a module''' modpaths = ['MAVProxy.modules.mavproxy_%s' % modname, modname] for (m,pm) in mpstate.modules: if m.name == modname: if not quiet: print("module %s already loaded" % modname) return False for modpath in modpaths: try: m = import_package(modpath) import imp imp.reload(m) module = m.init(mpstate) if isinstance(module, mp_module.MPModule): mpstate.modules.append((module, m)) if not quiet: print("Loaded module %s" % (modname,)) return True else: ex = "%s.init did not return a MPModule instance" % modname break except ImportError as msg: ex = msg if mpstate.settings.moddebug > 1: import traceback print(traceback.format_exc()) print("Failed to load module: %s" % ex) return False
def reload(self): print 'RELOADING MODULES ..' self.choco.module.rules = [] self.choco.module.functions = {} for m in modules: imp.reload(m) print 'RELOAD COMPLETE !'
def test_cert_false_test(cleanUpEnv): os.environ['PUPPETDB_SSL_VERIFY'] = 'False' reload(docker_settings) assert docker_settings.PUPPETDB_SSL_VERIFY is False os.environ['PUPPETDB_SSL_VERIFY'] = 'false' reload(docker_settings) assert docker_settings.PUPPETDB_SSL_VERIFY is False
def setUp(self): reload(grant_types) # grant_types indirectly import common mock_validator = mock.MagicMock() auth_code = grant_types.AuthorizationCodeGrant(request_validator=mock_validator) auth_code.save_authorization_code = mock.MagicMock() implicit = grant_types.ImplicitGrant(request_validator=mock_validator) implicit.save_token = mock.MagicMock() response_types = { 'code': auth_code, 'token': implicit, } # TODO(ib-lundgren): Figure out where in the import order the monkey # patching of oauthlib.common.generate_token breaks. class MockToken(tokens.BearerToken): def __call__(self, request, refresh_token=False): token = super(MockToken, self).__call__(request, refresh_token=refresh_token) token['access_token'] = 'abc' return token token = MockToken() token.save_token = mock.MagicMock() self.endpoint = draft25.AuthorizationEndpoint( default_token=token, response_types=response_types)
def reload_django_settings(): mod = util.import_module(os.environ['DJANGO_SETTINGS_MODULE']) # reload module reload(mod) # reload settings. # USe code from django.settings.Settings module. # Settings that should be converted into tuples if they're mistakenly entered # as strings. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS") for setting in dir(mod): if setting == setting.upper(): setting_value = getattr(mod, setting) if setting in tuple_settings and type(setting_value) == str: setting_value = (setting_value,) # In case the user forgot the comma. setattr(settings, setting, setting_value) # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list # of all those apps. new_installed_apps = [] for app in settings.INSTALLED_APPS: if app.endswith('.*'): app_mod = util.import_module(app[:-2]) appdir = os.path.dirname(app_mod.__file__) app_subdirs = os.listdir(appdir) name_pattern = re.compile(r'[a-zA-Z]\w*') for d in sorted(app_subdirs): if (name_pattern.match(d) and os.path.isdir(os.path.join(appdir, d))): new_installed_apps.append('%s.%s' % (app[:-2], d)) else: new_installed_apps.append(app) setattr(settings, "INSTALLED_APPS", new_installed_apps) if hasattr(time, 'tzset') and settings.TIME_ZONE: # When we can, attempt to validate the timezone. If we can't find # this file, no check happens and it's harmless. zoneinfo_root = '/usr/share/zoneinfo' if (os.path.exists(zoneinfo_root) and not os.path.exists(os.path.join(zoneinfo_root, *(settings.TIME_ZONE.split('/'))))): raise ValueError("Incorrect timezone setting: %s" % settings.TIME_ZONE) # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ['TZ'] = settings.TIME_ZONE time.tzset() # Settings are configured, so we can set up the logger if required if getattr(settings, 'LOGGING_CONFIG', False): # First find the logging configuration function ... logging_config_path, logging_config_func_name = settings.LOGGING_CONFIG.rsplit('.', 1) logging_config_module = util.import_module(logging_config_path) logging_config_func = getattr(logging_config_module, logging_config_func_name) # ... then invoke it with the logging settings logging_config_func(settings.LOGGING)
def test_cert_true_test(cleanUpEnv): os.environ['PUPPETDB_SSL_VERIFY'] = 'True' reload(docker_settings) assert docker_settings.PUPPETDB_SSL_VERIFY is True os.environ['PUPPETDB_SSL_VERIFY'] = 'true' reload(docker_settings) assert docker_settings.PUPPETDB_SSL_VERIFY is True
def reload_module(moduleName): if py3k.IS_PY3K: import imp imp.reload(moduleName) else: reload(moduleName)
def get_rig_type(rig_type): """ Fetches a rig module by name, and returns it. """ #print("%s.%s.%s" % (__package__,RIG_DIR,rig_type)) submod = __import__(name="%s.%s.%s" % (MODULE_NAME, RIG_DIR, rig_type), fromlist=[rig_type]) imp.reload(submod) return submod
def cython_pyximport(self, line, cell): """Compile and import a Cython code cell using pyximport. The contents of the cell are written to a `.pyx` file in the current working directory, which is then imported using `pyximport`. This magic requires a module name to be passed:: %%cython_pyximport modulename def f(x): return 2.0*x The compiled module is then imported and all of its symbols are injected into the user's namespace. For most purposes, we recommend the usage of the `%%cython` magic. """ module_name = line.strip() if not module_name: raise ValueError("module name must be given") fname = module_name + ".pyx" with io.open(fname, "w", encoding="utf-8") as f: f.write(cell) if "pyximport" not in sys.modules or not self._pyximport_installed: import pyximport pyximport.install(reload_support=True) self._pyximport_installed = True if module_name in self._reloads: module = self._reloads[module_name] reload(module) else: __import__(module_name) module = sys.modules[module_name] self._reloads[module_name] = module self._import_all(module)
__author__ = ["Xembie","PhaethonH","Bob Holcomb","Damien McGinnes","Robert (Tr3B) Beckebans"] __version__ = '1.4' __url__ = ["www.blender.org","http://xreal.sourceforge.net","http://www.katsbits.com"] import math, time, os, imp, mathutils if "JAMd3Encode" in locals(): import imp imp.reload( JAMd3Encode ) else: from . import JAMd3Encode def message( log, msg ): if log: log.write( msg + "\n" ) else: print( msg ) class md3Settings: def __init__( self, savepath, name, logtype, dumpall = False, ignoreuvs = False, scale = 1.0, offsetx = 0.0, offsety = 0.0, offsetz = 0.0 ): self.savepath = savepath self.name = name
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import threading import time import requests import shutil, sys, os, math import random import uuid import copy if "bpy" in locals(): import imp imp.reload(paths) imp.reload(append_link) else: from blenderkit import paths, append_link, utils import bpy from bpy.props import ( IntProperty, FloatProperty, FloatVectorProperty, StringProperty, EnumProperty, BoolProperty, PointerProperty, ) from bpy.app.handlers import persistent
"\n\nInside of \"Installed Packages/\", rename " + "\"%s.sublime-package\" to " % installed_dir + "\"JoomlaPack.sublime-package\" ") message += "and restart Sublime Text." sublime.error_message(message) else: reloader_name = 'reloader' # ST3 loads each package as a module, so it needs an extra prefix if st_version == 3: reloader_name = 'JoomlaPack.' + reloader_name from imp import reload # Make sure all dependencies are reloaded on upgrade if reloader_name in sys.modules: reload(sys.modules[reloader_name]) try: # Python 3 from .commands import * from .lib import * from .lib.extensions import * from .lib.inflector import * except (ValueError): # Python 2 from commands import * from lib import * from lib.extensions import * from lib.inflector import * def plugin_loaded():
def main_func(): gettext.install("pkg", "/usr/share/locale", codeset=locale.getpreferredencoding()) repo_uri = os.getenv("PKG_REPO", None) show_usage = False global_settings.client_name = "pkgsend" try: opts, pargs = getopt.getopt(sys.argv[1:], "s:D:?", ["help", "debug="]) for opt, arg in opts: if opt == "-s": repo_uri = arg elif opt == "-D" or opt == "--debug": if arg == "allow-timestamp": key = arg value = True else: try: key, value = arg.split("=", 1) except (AttributeError, ValueError): usage( _("{opt} takes argument of form " "name=value, not {arg}").format(opt=opt, arg=arg)) DebugValues.set_value(key, value) elif opt in ("--help", "-?"): show_usage = True except getopt.GetoptError as e: usage(_("illegal global option -- {0}").format(e.opt)) if repo_uri and not repo_uri.startswith("null:"): repo_uri = misc.parse_uri(repo_uri) if DebugValues: reload(pkg.digest) subcommand = None if pargs: subcommand = pargs.pop(0) if subcommand == "help": show_usage = True if show_usage: usage(retcode=0) elif not subcommand: usage() if not repo_uri and subcommand not in ("create-repository", "generate", "publish"): usage(_("A destination package repository must be provided " "using -s."), cmd=subcommand) visitors = [SolarisBundleVisitor()] ret = 0 try: if subcommand == "create-repository": ret = trans_create_repository(repo_uri, pargs) elif subcommand == "open": ret = trans_open(repo_uri, pargs) elif subcommand == "append": ret = trans_append(repo_uri, pargs) elif subcommand == "close": ret = trans_close(repo_uri, pargs) elif subcommand == "add": ret = trans_add(repo_uri, pargs) elif subcommand == "import": ret = trans_import(repo_uri, pargs, visitors=visitors) elif subcommand == "include": ret = trans_include(repo_uri, pargs) elif subcommand == "publish": ret = trans_publish(repo_uri, pargs) elif subcommand == "generate": ret = trans_generate(pargs, visitors=visitors) elif subcommand == "refresh-index": ret = trans_refresh_index(repo_uri, pargs) else: usage(_("unknown subcommand '{0}'").format(subcommand)) printed_space = False for visitor in visitors: for warn in visitor.warnings: if not printed_space: print("") printed_space = True error(warn, cmd=subcommand) for err in visitor.errors: if not printed_space: print("") printed_space = True error(err, cmd=subcommand) ret = 1 except pkg.bundle.InvalidBundleException as e: error(e, cmd=subcommand) ret = 1 except getopt.GetoptError as e: usage( _("illegal {cmd} option -- {opt}").format(cmd=subcommand, opt=e.opt)) return ret
def _reload_constants(): # Reload defaults that can depend on environment variables and # current working directory reload(ansible.constants)
# Licensed under a 3-clause BSD style license - see LICENSE.rst from astropy.tests.helper import remote_data from ... import lamda import requests import imp imp.reload(requests) @remote_data def test_query(): result = lamda.Lamda.query(mol='co') assert [len(r) for r in result] == [2, 40, 41] collider_dict = result[0] assert set(collider_dict.keys()) == set(['PH2', 'OH2']) assert [len(collider_dict[r]) for r in collider_dict] == [820, 820]
Usage: Make a selection (or not), Choose NodeEval from the context menu and see the results in the console. ''' import sublime, sublime_plugin, os, time from functools import partial from subprocess import Popen, PIPE, STDOUT import subprocess import sys PY3 = sys.version_info[0] >= 3 if PY3: from imp import reload reload(sys) if not PY3: sys.setdefaultencoding('utf-8') if not PY3: import thread import threading ST3 = int(sublime.version()) >= 3000 # # Globals # g_enabled = False
import os import numpy as np import matplotlib.pyplot as plt import rnnSMAP import imp imp.reload(rnnSMAP) rnnSMAP.reload() hucCaseLst = [['16', '14', '12'], ['13', '15', '03'], ['02', '05', '18']] for hucStrLst in hucCaseLst: # hucStrLst = ['16', '14', '12'] # [ref, close, far] hucLst = np.asarray(hucStrLst, dtype=int)-1 saveFolder = os.path.join( rnnSMAP.kPath['dirResult'], 'weight', 'wp_huc') rootOut = rnnSMAP.kPath['OutSigma_L3_NA'] rootDB = rnnSMAP.kPath['DB_L3_NA'] nCase = len(hucStrLst) caseStr = ['train', 'close', 'far'] wOpt = 'wp' nPerm = 100 doOpt = [] doOpt.append('test') doOpt.append('plotBox') doOpt.append('plotVS') if 'test' in doOpt:
# v0.57 2010/12/03 Minor updates for Blender SVN maintenance. # v0.56 2010/11/19 Revised UI for property access/display. # V0.55 2010/11/15 Added stairs, improved shelf, fixed plan generation. # V0.54 2010/11/11 Changed version number to match sourceforge check-in, # basic shelf, and, some general cleanup. # V0.5 2010/10/31 Converted to Blender 2.5.4 # V0.4 2009/11/29 Converted to Blender 2.5 # V0.3 2009/11/28 Re-did much of the internals, everything works better, # especially edge finding. # V0.2 2008/03/?? Reworked nearly all the code, many new features # V0.1 2007/09/14 First release! if "bpy" in locals(): import imp imp.reload(Wallfactory) else: from add_mesh_walls import Wallfactory import bpy ################################################################################ ##### REGISTER ##### # Define "Wall" menu def add_mesh_wall_ops(self, context): self.layout.operator(Wallfactory.add_mesh_wallb.bl_idname, text="Block Wall", icon="MOD_BUILD") # self.layout.operator(Wallfactory.add_mesh_wallr.bl_idname, text="Rocks", icon="PLUGIN") # self.layout.operator(Wallfactory.add_mesh_column.bl_idname, text="Columns", icon="PLUGIN")
"author": "Martin Poirier", "version": (1, 8), "blender": (2, 60, 0), "location": "Render > Engine > Network Render", "description": "Distributed rendering for Blender", "warning": "Stable but still work in progress", "wiki_url": "http://wiki.blender.org/index.php/Doc:2.5/Manual/" "Render/Engines/Netrender", "tracker_url": "https://developer.blender.org/T36513", "category": "Render"} # To support reload properly, try to access a package var, if it's there, reload everything if "init_data" in locals(): import imp imp.reload(model) imp.reload(operators) imp.reload(client) imp.reload(slave) imp.reload(master) imp.reload(master_html) imp.reload(utils) imp.reload(balancing) imp.reload(ui) imp.reload(repath) imp.reload(versioning) imp.reload(baking) else: from netrender import model from netrender import operators from netrender import client
# -*- coding: utf-8 -*- ############################################################################## # # ############################################################################## from imp import reload from basic.publicw import DEBUG if DEBUG == '1': import admin.dl.BASE_DL reload(admin.dl.BASE_DL) from admin.dl.BASE_DL import cBASE_DL class cI001_dl(cBASE_DL): def init_data(self): self.part = self.GP('part', 'Localfrm') self.tab = self.GP("tab", "1") def get_local_data(self): """获取 local 表单的数据 """ #if self.tab == '1': sql = """ select appid, secret, wx_status, wxtoken,
"name": "BVH Madness", "author": "Campbell Barton", "blender": (2, 57, 0), "location": "File > Import-Export", "description": "Import-Export BVH from armature objects", "warning": "", "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/" "Scripts/Import-Export/MotionCapture_BVH", "tracker_url": "", "support": 'TESTING', "category": "Import-Export"} if "bpy" in locals(): import imp if "import_bvh" in locals(): imp.reload(import_bvh) if "export_bvh" in locals(): imp.reload(export_bvh) if "utils" in locals(): imp.reload(utils) if "cmu" in locals(): imp.reload(cmu) if "rescale" in locals(): imp.reload(rescale) if "import2selected" in locals(): imp.reload(import2selected) if "import2selected" in locals(): imp.reload(action_menu) if "posematch" in locals(): imp.reload(posematch)
"name": "Vray Render Panel", "author": "JuhaW", "version": (0, 1, 0), "blender": (2, 76, 0), "location": "Tools", "description": "Quick Render Settings", "warning": "beta", "wiki_url": "", "category": "", } if "bpy" in locals(): import imp if "Material" in locals(): imp.reload(Material) if "RenderPass" in locals(): imp.reload(RenderPass) else: import imp import sys from . Material import Material from . RenderPass import RenderPass as RP from . RenderPass import LightPass as LP # import bpy from math import log from bpy.props import * from bpy.props import IntProperty, IntVectorProperty, StringProperty, BoolProperty, PointerProperty, BoolVectorProperty from bpy.types import PropertyGroup
from maya import cmds import imp import gearCreatorV3 as gM imp.reload(gM) text_info = "This is Gear Creator v3.0 by Junru Tao 2021\n" \ "script adaption based on Dhruv's demo 2017" class WindowManager(object): """ This is the base class manages create and destroy a window wrapping maya cmd. [The global Params] these shall be override in the derived classes """ window_id = "Base_Window" window_title = "Editor" window_dim = (200, 100) def show(self): """ [Show Window]This function will be called by the this object and its children """ # preventing duplicated window showing up, note: window titles are different from window_id if cmds.window(self.window_id, exists=True): # note: -exists flag in MEL will ignore other flags cmds.deleteUI(self.window_id) # Creating the actual window(however window with same was tested) cmds.window(self.window_id) # Call the override functions here self.build_ui() # This is a post-adjustment measure, [post-edit] will make sure the window_size/title adjusted cmds.window(self.window_id, edit=True, title=self.window_title, widthHeight=self.window_dim)
# -*- coding: utf-8 -*- ############################################################################## # Copyright (c) wxmall.janedao.cn # Author:QQ173782910 #QQ group:528289471 ############################################################################## """ admin/vi/H002.py""" from imp import reload from basic.publicw import DEBUG if DEBUG == '1': import admin.vi.BASE_TPL reload(admin.vi.BASE_TPL) from admin.vi.BASE_TPL import cBASE_TPL class cH002(cBASE_TPL): def setClassName(self): #设定要实例的 dl类和TPL类,为空则继承基类,可以能过判断part的值来设置不同的类名 ''' if self.part == 'xxx': self.dl_name = 'xxx_dl' ''' self.dl_name = 'H002_dl' self.inframe = 1 def specialinit(self): pass def goPartList(self): self.assign('NL',self.dl.GNL)
else: ret = None # remember and return versionRedirectMap[key] = ret return ret #print "Rebuilding: ", major, minor module = MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance, bForDemand=bForDemand, bBuildHidden=bBuildHidden) # If we replaced something, reload it if bReloadNeeded: module = reload(module) AddModuleToCache(typelibCLSID, lcid, major, minor) return module def EnsureDispatch( prog_id, bForDemand=1): # New fn, so we default the new demand feature to on! """Given a COM prog_id, return an object that is using makepy support, building if necessary""" disp = win32com.client.Dispatch(prog_id) if not disp.__dict__.get( "CLSID"): # Eeek - no makepy support - try and build it. try: ti = disp._oleobj_.GetTypeInfo() disp_clsid = ti.GetTypeAttr()[0] tlb, index = ti.GetContainingTypeLib()
# -*- coding: utf-8 -*- ############################################################################## # Copyright (c) wxmall.janedao.cn # Author:QQ173782910 #QQ group:528289471 ############################################################################## """ manage/vi/J001.py""" from imp import reload from basic.publicw import DEBUG if DEBUG == '1': import manage.vi.BASE_TPL reload(manage.vi.BASE_TPL) from manage.vi.BASE_TPL import cBASE_TPL class cJ001(cBASE_TPL): def setClassName(self): self.dl_name = 'J001_dl' self.inframe = 1 def specialinit(self): pass def goPartList(self): self.assign('NL', self.dl.GNL) self.navTitle = '人员管理' self.getBreadcrumb() #获取面包屑 PL, L = self.dl.mRight()
:return: Preprocessed target data """ # Create a constant tensor with the 'go id'. go_id = tf.constant(target_vocab_to_int['<GO>'], shape=(batch_size,1), dtype=tf.int32) # Concatenate the vector without the last word id with the go ids vector processed_input = tf.concat([go_id,target_data[:,:-1]],1) return processed_input """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_process_encoding_input(process_decoder_input) #------------------------------------------------------------- from imp import reload reload(tests) def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size): """ Create encoding layer :param rnn_inputs: Inputs for the RNN :param rnn_size: RNN Size :param num_layers: Number of layers :param keep_prob: Dropout keep probability :param source_sequence_length: a list of the lengths of each sequence in the batch :param source_vocab_size: vocabulary size of source data :param encoding_embedding_size: embedding size of source data :return: tuple (RNN output, RNN state) """
bl_info = { "name": "Mesh Segmentation", "description": "Segments an object and applies an action on each segment", "category": "Mesh" } import bpy from mesh_segmentation import segmentation from mesh_segmentation import actions # developing purpose for reloading modules if already imported import imp imp.reload(segmentation) imp.reload(actions) class MeshSegmentation(bpy.types.Operator): """Segment a mesh""" bl_idname = "mesh.mesh_segmentation" bl_label = "Segment Mesh" bl_options = {'REGISTER', 'UNDO'} # parameters action = bpy.props.EnumProperty(name="Action", items=[ ('assignMaterials', "Assign materials", "Assigns a different material for " "each found segment") ], description="What to do with the " "segmentation",
#-*- coding: utf-8 -*- from flask_restful import Resource, Api from flask import Flask, redirect, url_for, request, render_template, send_file import json from flask_jsonpify import jsonify import gensim import sys import imp import matplotlib.pyplot as plt from wordcloud import WordCloud imp.reload(sys) app = Flask(__name__) @app.route('/success/<text>') def success_doc2vec(text): model = gensim.models.Doc2Vec.load( "/Users/seungeonlee/Desktop/capstone/2018-cap1-23/src/model/doc2vec.model" ) result = model.most_similar(text.strip(), topn=10) # wordcloud = WordCloud().generate(text) #test 중 # wordcloud.words_ # plt.figure(figsize=(5,5)) # plt.imshow(wordcloud, interpolation='bilinear') # fig = plt.gcf() # fig.savefig('/home/nlpserver/Desktop/Lee/2018-cap1-23/src/static/image/GG.png') output = [] for i in range(len(result)): output.append(result[i][0])
############################################################################## """celery_app/db_backup.py""" from flask import Flask, json # from flask_mail import Mail,Message from celery import Celery from celery_app import c import time app = Flask(__name__) import requests, json, os, random, traceback, oss2 from imp import reload import datetime from basic import public reload(public) db, ATTACH_ROOT, getToday = public.db, public.ATTACH_ROOT, public.getToday oUSER, oPT_GOODS, oMALL = public.oUSER, public.oPT_GOODS, public.oMALL from qiniu import Auth, put_stream, put_data, put_file, BucketManager from basic.wxbase import wx_minapp_login, WXBizDataCrypt, WxPay # app.config['MAIL_SERVER'] = '' # app.config['MAIL_PORT'] = 994 # app.config['MAIL_USE_SSL'] = True # app.config['MAIL_DEBUG'] = True # app.config['MAIL_DEFAULT_SENDER'] = '' # app.config['MAIL_USERNAME'] = '' # app.config['MAIL_PASSWORD'] = "" # mails=Mail(app)
#### Main file to import only one time the database #### then keeping the data and running the algo-script #### allowing fast re-running, avoiding long import time. import sys from imp import reload from mnist import get_data import class_algo part1Cache = None if __name__ == "__main__": while True: if not part1Cache: part1Cache = get_data() try: class_algo.main_classiffy(part1Cache) except Exception as e: print(e) print("Press enter to re-run the script, CTRL-C to exit") sys.stdin.readline() try: reload(class_algo) except Exception as e: print(e)
# Use this for the version of this plugin. You may wish to put a CVS keyword # in here if you're keeping the plugin in CVS or some similar system. __version__ = "%%VERSION%%" # XXX Replace this with an appropriate author or supybot.Author instance. __author__ = supybot.authors.jemfinch # This is a dictionary mapping supybot.Author instances to lists of # contributions. __contributors__ = { supybot.authors.skorobeus: ['contributors'], } from . import config # This had to be renamed because of stupid case-insensitivity issues. from . import plugin from imp import reload reload(plugin) # In case we're being reloaded. # Add more reloads here if you add third-party modules and want them to be # reloaded when this plugin is reloaded. Don't forget to import them as well! if world.testing: from . import test Class = plugin.Class configure = config.configure # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' this py can generate group graph configs ''' import sys import csv import imp import pipe_config imp.reload(pipe_config) def param_parse(params): '''param parse.''' if 'x' in params: res = params.split('x') if len(res) == 2 and res[0].isdigit() and res[1].isdigit(): return [int(res[0]), int(res[1])] return None return None def param_check(in_res, out_main, out_vf, line_num): '''param check.''' ret = True if in_res is None or out_main is None: print("line: %d, input and out_main error" % (line_num)) ret = False elif out_vf is None:
def _reload_urlconf(self): """ Helper method to reload url config.""" imp.reload(sys.modules[settings.ROOT_URLCONF]) clear_url_caches()
# __init__ Python Package Head # Rhorix: An interface between quantum chemical topology and the 3D graphics program Blender # This file causes Python to treat the directory as containing a package # The user interface and add-on info are placed here. # This provides support for reloading of the add-on when making changes # See https://wiki.blender.org/index.php/Dev:Py/Scripts/Cookbook/Code_snippets/Multi-File_packages if "bpy" in locals(): import imp imp.reload(ParseTopology) imp.reload(TopologyClasses) imp.reload(Mapping) imp.reload(Materials) imp.reload(Resources) imp.reload(World) else: from . import ParseTopology, TopologyClasses, Mapping, Materials, Resources, World import bpy import time import fnmatch # The following dict and 2 functions satisfy the requirements for contributed scripts # Be sure to also follow the PEP 8 Python conventions - see https://www.python.org/dev/peps/pep-0008/ # Script Meta-info: this Python dictionary is required by all Addon files # All possible keys are present in this dict - fill in wiki/tracker URLs later if needed # See https://wiki.blender.org/index.php/Dev:Py/Scripts/Guidelines/Addons/metainfo bl_info = {
# -*- coding: utf-8 -*- ############################################################################## # # # ############################################################################## from imp import reload import basic reload(basic) from basic import public DEBUG, CLIENT_NAME = public.DEBUG, public.CLIENT_NAME if DEBUG == '1': import admin.dl.BASE_DL reload(admin.dl.BASE_DL) from admin.dl.BASE_DL import cBASE_DL import hashlib, os, time, random class cA010_dl(cBASE_DL): def init_data(self): self.GNL = ['', '手机号码', '昵称', '类型', '收支', '变动积分', '剩余积分', '交易时间', '备注'] #在子类中重新定义 def myInit(self): self.src = 'A010' pass
# You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import bpy import os import sys import threading from bpy.app.handlers import persistent join = os.path.join if 'bpy' in locals(): import imp if 'gltf2_animate' in locals(): imp.reload(gltf2_animate) if 'gltf2_create' in locals(): imp.reload(gltf2_create) if 'gltf2_debug' in locals(): imp.reload(gltf2_debug) if 'gltf2_export' in locals(): imp.reload(gltf2_export) if 'gltf2_extract' in locals(): imp.reload(gltf2_extract) if 'gltf2_filter' in locals(): imp.reload(gltf2_filter) if 'gltf2_generate' in locals(): imp.reload(gltf2_generate) if 'gltf2_get' in locals(): imp.reload(gltf2_get)
from qiniu import Auth, put_stream, put_data, BucketManager from basic.publicw import DEBUG from wechatpy import WeChatClient from wechatpy.client.api import WeChatWxa from basic.wxbase import wx_minapp_login, WXBizDataCrypt, WxPay from werkzeug import secure_filename import hashlib, time, json, datetime from imp import reload if DEBUG == '1': import manage.mapi.VIEWS reload(manage.mapi.VIEWS) from manage.mapi.VIEWS import cVIEWS # { # -1: u'服务器内部错误', # 0: u'接口调用成功', # 403: u'禁止访问', # 405: u'错误的请求类型', # 501: u'数据库错误', # 502: u'并发异常,请重试', # 600: u'缺少参数', # 601: u'无权操作:缺少 token', # 602: u'签名错误', # 700: u'暂无数据', # 701: u'该功能暂未开通',
import q182 import q182 from imp import reload reload(q182) reload(q182) reload(q182) print("This is test module")