本文整理汇总了Python中config.py方法的典型用法代码示例。如果您正苦于以下问题:Python config.py方法的具体用法?Python config.py怎么用?Python config.py使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类config
的用法示例。
在下文中一共展示了config.py方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_fake_images
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def generate_fake_images(run_id, snapshot=None, grid_size=[1,1], num_pngs=1, image_shrink=1, png_prefix=None, random_seed=1000, minibatch_size=8):
network_pkl = misc.locate_network_pkl(run_id, snapshot)
if png_prefix is None:
png_prefix = misc.get_id_string_for_network_pkl(network_pkl) + '-'
random_state = np.random.RandomState(random_seed)
print('Loading network from "%s"...' % network_pkl)
G, D, Gs = misc.load_network_pkl(run_id, snapshot)
result_subdir = misc.create_result_subdir(config.result_dir, config.desc)
for png_idx in range(num_pngs):
print('Generating png %d / %d...' % (png_idx, num_pngs))
latents = misc.random_latents(np.prod(grid_size), Gs, random_state=random_state)
labels = np.zeros([latents.shape[0], 0], np.float32)
images = Gs.run(latents, labels, minibatch_size=minibatch_size, num_gpus=config.num_gpus, out_mul=127.5, out_add=127.5, out_shrink=image_shrink, out_dtype=np.uint8)
misc.save_image_grid(images, os.path.join(result_subdir, '%s%06d.png' % (png_prefix, png_idx)), [0,255], grid_size)
open(os.path.join(result_subdir, '_done.txt'), 'wt').close()
#----------------------------------------------------------------------------
# Generate MP4 video of random interpolations using a previously trained network.
# To run, uncomment the appropriate line in config.py and launch train.py.
示例2: show_version
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def show_version():
entries = []
entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info))
version_info = discord.version_info
entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info))
if version_info.releaselevel != 'final':
pkg = pkg_resources.get_distribution('discord.py')
if pkg:
entries.append(' - discord.py pkg_resources: v{0}'.format(pkg.version))
entries.append('- aiohttp v{0.__version__}'.format(aiohttp))
entries.append('- websockets v{0.__version__}'.format(websockets))
uname = platform.uname()
entries.append('- system info: {0.system} {0.release} {0.version}'.format(uname))
print('\n'.join(entries))
示例3: doImport
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def doImport(self, romCollections, isRescrape, scrapeInBackground, selectedRomCollection=None,
selectedScraper=None):
if scrapeInBackground:
path = os.path.join(self.Settings.getAddonInfo('path'), 'dbUpLauncher.py')
log.info('Launch external update script: %s' % path)
xbmc.executebuiltin("RunScript(%s, selectedRomCollection=%s, selectedScraper=%s)"
% (path, selectedRomCollection, selectedScraper))
#exit RCB
self.quit = True
self.exit()
else:
import dbupdate
progressDialog = dialogprogress.ProgressDialogGUI()
#32111 = Import Games...
progressDialog.create(util.localize(32111))
updater = dbupdate.DBUpdate()
updater.updateDB(self.gdb, progressDialog, romCollections, isRescrape)
del updater
progressDialog.writeMsg("", -1)
del progressDialog
示例4: __init__
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def __init__(self, local=True):
if local:
# Class instance connection to Mongo
self.connection = MongoClient()
if config.AUTH:
try:
self.connection.admin.authenticate(config.USERNAME, config.PASSWORD)
except:
print('Error: Authentication failed. Please check:\n1. MongoDB credentials in config.py\n2. MongoDB uses the correct authentication schema (MONGODB-CR)\nFor more info. see https://github.com/bitslabsyr/stack/wiki/Installation')
sys.exit(1)
# App-wide config file for project info access
self.config_db = self.connection.config
self.stack_config = self.config_db.config
else:
self.connection = MongoClient(config.CT_SERVER)
if config.CT_AUTH:
try:
self.connection.admin.authenticate(config.CT_USERNAME, config.CT_PASSWORD)
except:
print('Error: Authentication failed at the central server. Please check:\n1. MongoDB credentials in config.py\n2. MongoDB uses the correct authentication schema (MONGODB-CR)\nFor more info. see https://github.com/bitslabsyr/stack/wiki/Installation')
sys.exit(1)
示例5: get_current_theme_name
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def get_current_theme_name():
import config
import os
try:
name = config.THEME
if not name:
raise ValueError
path = os.sep.join([os.path.abspath(os.path.dirname(__file__)), '../themes', '{}.py'.format(name)])
if not os.path.isfile(path):
raise FileNotFoundError
return name
except AttributeError:
print_raw('Promptastic ERROR: the config.py file does not contain a THEME attribute.')
exit(1)
except ValueError:
print_raw('Promptastic ERROR: the THEME setting in the file config.py seems to be empty.')
exit(1)
except FileNotFoundError:
print_raw('Promptastic ERROR: {}.py is not a file in the themes directory.'.format(name))
exit(1)
示例6: generate_interpolation_video
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def generate_interpolation_video(run_id, snapshot=None, grid_size=[1,1], image_shrink=1, image_zoom=1, duration_sec=60.0, smoothing_sec=1.0, mp4=None, mp4_fps=30, mp4_codec='libx265', mp4_bitrate='16M', random_seed=1000, minibatch_size=8):
network_pkl = misc.locate_network_pkl(run_id, snapshot)
if mp4 is None:
mp4 = misc.get_id_string_for_network_pkl(network_pkl) + '-lerp.mp4'
num_frames = int(np.rint(duration_sec * mp4_fps))
random_state = np.random.RandomState(random_seed)
print('Loading network from "%s"...' % network_pkl)
G, D, Gs = misc.load_network_pkl(run_id, snapshot)
print('Generating latent vectors...')
shape = [num_frames, np.prod(grid_size)] + Gs.input_shape[1:] # [frame, image, channel, component]
all_latents = random_state.randn(*shape).astype(np.float32)
all_latents = scipy.ndimage.gaussian_filter(all_latents, [smoothing_sec * mp4_fps] + [0] * len(Gs.input_shape), mode='wrap')
all_latents /= np.sqrt(np.mean(np.square(all_latents)))
# Frame generation func for moviepy.
def make_frame(t):
frame_idx = int(np.clip(np.round(t * mp4_fps), 0, num_frames - 1))
latents = all_latents[frame_idx]
labels = np.zeros([latents.shape[0], 0], np.float32)
images = Gs.run(latents, labels, minibatch_size=minibatch_size, num_gpus=config.num_gpus, out_mul=127.5, out_add=127.5, out_shrink=image_shrink, out_dtype=np.uint8)
grid = misc.create_image_grid(images, grid_size).transpose(1, 2, 0) # HWC
if image_zoom > 1:
grid = scipy.ndimage.zoom(grid, [image_zoom, image_zoom, 1], order=0)
if grid.shape[2] == 1:
grid = grid.repeat(3, 2) # grayscale => RGB
return grid
# Generate video.
import moviepy.editor # pip install moviepy
result_subdir = misc.create_result_subdir(config.result_dir, config.desc)
moviepy.editor.VideoClip(make_frame, duration=duration_sec).write_videofile(os.path.join(result_subdir, mp4), fps=mp4_fps, codec='libx264', bitrate=mp4_bitrate)
open(os.path.join(result_subdir, '_done.txt'), 'wt').close()
#----------------------------------------------------------------------------
# Generate MP4 video of training progress for a previous training run.
# To run, uncomment the appropriate line in config.py and launch train.py.
示例7: newbot
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def newbot(parser, args):
new_directory = to_path(parser, args.directory) / to_path(parser, args.name)
# as a note exist_ok for Path is a 3.5+ only feature
# since we already checked above that we're >3.5
try:
new_directory.mkdir(exist_ok=True, parents=True)
except OSError as exc:
parser.error('could not create our bot directory ({})'.format(exc))
cogs = new_directory / 'cogs'
try:
cogs.mkdir(exist_ok=True)
init = cogs / '__init__.py'
init.touch()
except OSError as exc:
print('warning: could not create cogs directory ({})'.format(exc))
try:
with open(str(new_directory / 'config.py'), 'w', encoding='utf-8') as fp:
fp.write('token = "place your token here"\ncogs = []\n')
except OSError as exc:
parser.error('could not create config file ({})'.format(exc))
try:
with open(str(new_directory / 'bot.py'), 'w', encoding='utf-8') as fp:
base = 'Bot' if not args.sharded else 'AutoShardedBot'
fp.write(bot_template.format(base=base, prefix=args.prefix))
except OSError as exc:
parser.error('could not create bot file ({})'.format(exc))
if not args.no_git:
try:
with open(str(new_directory / '.gitignore'), 'w', encoding='utf-8') as fp:
fp.write(gitignore_template)
except OSError as exc:
print('warning: could not create .gitignore file ({})'.format(exc))
print('successfully made bot at', new_directory)
示例8: newcog
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def newcog(parser, args):
cog_dir = to_path(parser, args.directory)
try:
cog_dir.mkdir(exist_ok=True)
except OSError as exc:
print('warning: could not create cogs directory ({})'.format(exc))
directory = cog_dir / to_path(parser, args.name)
directory = directory.with_suffix('.py')
try:
with open(str(directory), 'w', encoding='utf-8') as fp:
attrs = ''
extra = cog_extras if args.full else ''
if args.class_name:
name = args.class_name
else:
name = str(directory.stem)
if '-' in name:
name = name.replace('-', ' ').title().replace(' ', '')
else:
name = name.title()
if args.display_name:
attrs += ', name="{}"'.format(args.display_name)
if args.hide_commands:
attrs += ', command_attrs=dict(hidden=True)'
fp.write(cog_template.format(name=name, extra=extra, attrs=attrs))
except OSError as exc:
parser.error('could not create cog file ({})'.format(exc))
else:
print('successfully made cog at', directory)
示例9: parse_args
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def parse_args():
parser = argparse.ArgumentParser(prog='discord', description='Tools for helping with discord.py')
parser.add_argument('-v', '--version', action='store_true', help='shows the library version')
parser.set_defaults(func=core)
subparser = parser.add_subparsers(dest='subcommand', title='subcommands')
add_newbot_args(subparser)
add_newcog_args(subparser)
return parser, parser.parse_args()
示例10: UseRemoteGCS
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def UseRemoteGCS():
"""Use remote GCS via a signed certificate."""
logging.debug('Using remote gcs.')
try:
from oauth2client.client import SignedJwtAssertionCredentials
except ImportError:
logging.error('For local testing with remote GCS, install pycrypto.')
return
http_object = httplib2.Http(timeout=60)
service_account = config.service_account
private_key_pem_file = config.private_key_pem_file
scope = 'https://www.googleapis.com/auth/devstorage.full_control'
private_key = file(private_key_pem_file, 'rb').read()
certificate = SignedJwtAssertionCredentials(service_account,
private_key,
scope)
certificate.refresh(http_object)
gcs_common.set_access_token(certificate.access_token)
# Do convolutions to speak to remote cloud storage even when on a local
# devserver. If you want to communicate to remote GCS, rather then use local
# GCS stubs, set this value in config.py to true. It requires setting:
# config.service_account and config.private_key_pem_file from a project service
# account.
#
示例11: writeToAliceConfigurationFile
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def writeToAliceConfigurationFile(self, confs: dict):
"""
Saves the given configuration into config.py
:param confs: the dict to save
"""
sort = dict(sorted(confs.items()))
# Only store "active", "version", "author", "conditions" value for skill config
misterProper = ['active', 'version', 'author', 'conditions']
# pop skills key so it gets added in the back
skills = sort.pop('skills')
skills = dict() if not isinstance(skills, dict) else skills
sort['skills'] = dict()
for skillName, setting in skills.items():
skillCleaned = {key: value for key, value in setting.items() if key in misterProper}
sort['skills'][skillName] = skillCleaned
self._aliceConfigurations = sort
try:
confString = json.dumps(sort, indent=4).replace('false', 'False').replace('true', 'True')
Path('config.py').write_text(f'settings = {confString}')
importlib.reload(config)
except Exception:
raise ConfigurationUpdateFailed()
示例12: _writeToSkillConfigurationFile
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def _writeToSkillConfigurationFile(self, skillName: str, confs: dict):
"""
Saves the given configuration into config.py of the Skill
:param skillName: the targeted skill
:param confs: the dict to save
"""
# Don't store "active", "version", "author", "conditions" value in skill config file
misterProper = ['active', 'version', 'author', 'conditions']
confsCleaned = {key: value for key, value in confs.items() if key not in misterProper}
skillConfigFile = Path(self.Commons.rootDir(), 'skills', skillName, 'config.json')
skillConfigFile.write_text(json.dumps(confsCleaned, indent=4))
示例13: __init__
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def __init__(self):
# connect the note file specified in config.py > config.bibleNotes
self.database = os.path.join(config.marvelData, config.bibleNotes)
self.connection = sqlite3.connect(self.database)
self.cursor = self.connection.cursor()
create = (
"CREATE TABLE IF NOT EXISTS ChapterNote (Book INT, Chapter INT, Note TEXT)",
"CREATE TABLE IF NOT EXISTS VerseNote (Book INT, Chapter INT, Verse INT, Note TEXT)",
)
for statement in create:
self.cursor.execute(statement)
self.connection.commit()
示例14: __init__
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def __init__(self):
"""
Pull all variables from config.py file.
"""
self.player = Player()
self.database = config.database
self.Max_point_tournament = config.Max_point_tournament
self.BotNet_update = config.BotNet_update
self.joinTournament = config.joinTournament
self.tournament_potator = config.tournament_potator
self.booster = config.booster
self.Use_netcoins = config.Use_netcoins
self.attacks_normal = config.attacks_normal
self.updates = config.updates
self.updatecount = config.updatecount
self.maxanti_normal = config.maxanti_normal
self.active_cluster_protection = config.active_cluster_protection
self.mode = config.mode
self.number_task = config.number_task
self.min_energy_botnet = config.minimal_energy_botnet_upgrade
self.stat = "0"
self.wait_load = config.wait_load
self.c = Console(self.player)
self.u = Update(self.player)
# disable botnet for > api v13
self.b = Botnet(self.player)
self.ddos = ddos.Ddos(self.player)
self.m = Mails(self.player)
self.init()
示例15: _init
# 需要导入模块: import config [as 别名]
# 或者: from config import py [as 别名]
def _init(self):
"""
{"id":"924198","money":"14501972","ip":"83.58.131.20",
"inet":"10","hdd":"10","cpu":"10","ram":"14","fw":"256","av":"410","sdk":"580","ipsp":"50","spam":"71","scan":"436","adw":"76",
"actadw":"","netcoins":"5550","energy":"212286963","score":"10015",
"urmail":"1","active":"1","elo":"2880","clusterID":null,"position":null,"syslog":null,
"lastcmsg":"0","rank":32022,"event":"3","bonus":"0","mystery":"0","vipleft":"OFF",
"hash":"91ec5ed746dfedc0a750d896a4e615c4",
"uhash":"9832f717079f8664109ac9854846e753282c72cdf42fe33fb33c734923e1931c","use":"0",
"tournamentActive":"2","boost":"294","actspyware":"0","tos":"1","unreadmsg":"0"}
:return:
"""
data = self.ut.requestString(self.username, self.password, self.uhash, "vh_update.php")
if len(data) == 1:
logging.warn('Username and password entered in config.py?')
sys.exit()
try:
j = json.loads(data)
self.setmoney(j['money'])
self.ip = j['ip']
self.score = j['score']
self.netcoins = j['netcoins']
self.localspyware = j['actspyware']
self.rank = j['rank']
self.boosters = j['boost']
self.remotespyware = j['actadw']
self.email = int(j['urmail'])
self.uhash = str(j['uhash'])
logger.info("\n Your profile :\n\n Your IP: {0}, Your Score: {1}, Your netcoins {2}, \n Your rank: {3}, Your Booster: {4}, Active Spyware {5} \n\n".format(j['ip'], j['score'], j['netcoins'], j['rank'], j['boost'], j['actspyware']))
except:
exit()