def render(self, length=None, progress=False):
"""
Render this signal into an numpy array of floats. Return the array.
:param length: The length to render, in seconds. Optional.
:param progress: Whether to show a progress bar for rendering
"""
if progress and not progressbar:
print('Install the progressbar module to see a progress bar for rendering')
progress = False
duration = self.duration if length is None else length * SAMPLE_RATE
if duration == float('inf'):
duration = 3*SAMPLE_RATE
else:
duration = int(duration)
out = numpy.empty((duration, 1))
pbar = progressbar.ProgressBar(widgets=['Rendering: ', progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.ETA()], maxval=duration-1).start() if progress else None
for i in range(duration):
out[i] = self.amplitude(i)
if pbar: pbar.update(i)
if pbar: pbar.finish()
return out
python类ETA的实例源码
def main():
uri, outfile, dataset = get_arguments()
fd = tempfile.NamedTemporaryFile()
progress = ProgressBar(widgets=[Percentage(), ' ', Bar(), ' ', ETA(), ' ', FileTransferSpeed()])
def update(count, blockSize, totalSize):
if progress.maxval is None:
progress.maxval = totalSize
progress.start()
progress.update(min(count * blockSize, totalSize))
urllib.urlretrieve(uri, fd.name, reporthook = update)
if dataset == 'zinc12':
df = pandas.read_csv(fd.name, delimiter = '\t')
df = df.rename(columns={'SMILES':'structure'})
df.to_hdf(outfile, 'table', format = 'table', data_columns = True)
elif dataset == 'chembl22':
df = pandas.read_table(fd.name,compression='gzip')
df = df.rename(columns={'canonical_smiles':'structure'})
df.to_hdf(outfile, 'table', format = 'table', data_columns = True)
pass
else:
df = pandas.read_csv(fd.name, delimiter = '\t')
df.to_hdf(outfile, 'table', format = 'table', data_columns = True)
def preprocess(self, questions: List[QASetting],
answers: Optional[List[List[Answer]]] = None,
is_eval: bool = False) -> List[XQAAnnotation]:
if answers is None:
answers = [None] * len(questions)
preprocessed = []
if len(questions) > 1000:
bar = progressbar.ProgressBar(
max_value=len(questions),
widgets=[' [', progressbar.Timer(), '] ', progressbar.Bar(), ' (', progressbar.ETA(), ') '])
for q, a in bar(zip(questions, answers)):
preprocessed.append(self.preprocess_instance(q, a))
else:
for q, a in zip(questions, answers):
preprocessed.append(self.preprocess_instance(q, a))
return preprocessed
def preprocess(self, questions: List[QASetting],
answers: Optional[List[List[Answer]]] = None,
is_eval: bool = False) -> List[MCAnnotation]:
if answers is None:
answers = [None] * len(questions)
preprocessed = []
if len(questions) > 1000:
bar = progressbar.ProgressBar(
max_value=len(questions),
widgets=[' [', progressbar.Timer(), '] ', progressbar.Bar(), ' (', progressbar.ETA(), ') '])
for i, (q, a) in bar(enumerate(zip(questions, answers))):
preprocessed.append(self.preprocess_instance(i, q, a))
else:
for i, (q, a) in enumerate(zip(questions, answers)):
preprocessed.append(self.preprocess_instance(i, q, a))
return preprocessed
def download(download_list, total_download_size):
progressbar_widgets = [
'[Downloading mails ] ',
progressbar.Percentage(),
progressbar.Bar(marker=progressbar.RotatingMarker()), ' ',
progressbar.ETA(), ' ',
bitmath.integrations.BitmathFileTransferSpeed()]
progressbar_instance = progressbar.ProgressBar(widgets=progressbar_widgets, maxval=int(total_download_size)).start()
downloaded_size = bitmath.Byte(0)
for folder, mails in download_list.items():
server.select_folder(folder, readonly=True)
for mailid, mailfilename, mailsize in mails:
#make parent directory
if not os.path.isdir(os.path.dirname(mailfilename)):
os.makedirs(os.path.dirname(mailfilename))
#download mail
with open(mailfilename, 'wb') as mailfile:
mailfile.write(server.fetch([mailid], ['RFC822'])[mailid][b'RFC822'])
#update progressbar
downloaded_size += mailsize
progressbar_instance.update(int(downloaded_size))
progressbar_instance.finish()
def progressbarize(iterable, progress=False):
"""Construct progressbar for loops if progressbar requested, otherwise return directly iterable.
:param iterable: iterable to use
:param progress: True if print progressbar
"""
if progress:
# The casting to list is due to possibly yielded value that prevents
# ProgressBar to compute overall ETA
return progressbar.ProgressBar(widgets=[
progressbar.Timer(), ', ',
progressbar.Percentage(), ', ',
progressbar.SimpleProgress(), ', ',
progressbar.ETA()
])(list(iterable))
return iterable
def __init__(self, *args, **kwargs):
self.dld = FileDownloader()
self.dld.stage(self.cmd_name)
load_continents()
load_oceans()
load_currencies()
load_languages()
self.widgets = [
MemoryUsage(),
progressbar.ETA(),
' |Processed: ',
progressbar.Counter(),
' |Done: ',
progressbar.Percentage(),
progressbar.Bar(),
]
return super().__init__(*args, **kwargs)
def deleteHostsByHostgroup(groupname):
hostgroup = zapi.hostgroup.get(output=['groupid'],filter={'name': groupname})
if hostgroup.__len__() != 1:
logger.error('Hostgroup not found: %s\n\tFound this: %s' % (groupname,hostgroup))
groupid = int(hostgroup[0]['groupid'])
hosts = zapi.host.get(output=['name','hostid'],groupids=groupid)
total = len(hosts)
logger.info('Hosts found: %d' % (total))
if ( args.run ):
x = 0
bar = ProgressBar(maxval=total,widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
logger.echo = False
for host in hosts:
x = x + 1
bar.update(x)
logger.debug('(%d/%d) >> Removing >> %s' % (x, total, host))
out = zapi.globo.deleteMonitors(host['name'])
bar.finish()
logger.echo = True
else:
logger.info('No host removed due to --no-run arg. Full list of hosts:')
for host in hosts:
logger.info('%s' % host['name'])
return
def hosts_disable_all():
"""
status de host 0 = enabled
status de host 1 = disabled
"""
logger.info('Disabling all hosts, in blocks of 1000')
hosts = zapi.host.get(output=[ 'hostid' ], search={ 'status': 0 })
maxval = int(ceil(hosts.__len__())/1000+1)
bar = ProgressBar(maxval=maxval,widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
i = 0
for i in xrange(maxval):
block = hosts[:1000]
del hosts[:1000]
result = zapi.host.massupdate(hosts=[ x for x in block ], status=1)
i += 1
bar.update(i)
bar.finish()
logger.info('Done')
return
def proxy_passive_to_active():
"""
status de prxy 5 = active
status de prxy 6 = passive
"""
logger.info('Change all proxys to active')
proxys = zapi.proxy.get(output=[ 'shorten', 'host' ],
filter={ 'status': 6 })
if ( proxys.__len__() == 0 ):
logger.info('Done')
return
bar = ProgressBar(maxval=proxys.__len__(),widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
i = 0
for x in proxys:
i += 1
proxyid = x['proxyid']
result = zapi.proxy.update(proxyid=proxyid, status=5)
logger.echo = False
logger.debug('Changed from passive to active proxy: %s' % (x['host']))
bar.update(i)
bar.finish()
logger.echo = True
logger.info('Done')
return
def getProgress(self, url, fileSize):
status = json.loads(urllib.urlopen(url).read())
if len(status["data"]) ==0 :
logger.info(url + " upload done ")
return True
widgets = ['Progress: ', Percentage(), ' ', Bar(
marker=RotatingMarker('>-=')), ' ', ETA(), ' ', FileTransferSpeed()]
pbar = ProgressBar(widgets=widgets, maxval=fileSize).start()
upload_size = 0
while upload_size < fileSize:
_response = self.doGet(url)
_data = json.loads(_response)
upload_size = long(_data["data"]["upload_size"])
total_size = long(_data["data"]["total_size"])
if upload_size == 0 and total_size == 0:
break
pbar.update(upload_size)
time.sleep(1)
pbar.finish()
logger.info(url + " upload done")
return True
"""
??????
"""
def scrape_mlb_odds_range(min_date=None, max_date=None):
min_date = min_date or datetime.datetime.today() - datetime.timedelta(days=1)
max_date = max_date or datetime.datetime.today()
if isinstance(min_date, basestring):
min_date = parser.parse(min_date)
if isinstance(max_date, basestring):
max_date = parser.parse(max_date)
date = min_date
pbar = progressbar.ProgressBar(widgets=[progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.ETA()],
maxval=int((max_date-min_date).total_seconds() / (60*60*24)) + 1)
pbar.start()
saved = 0
hit = 0
while date <= max_date:
day_odds = load_odds_for_day(date)
if day_odds is not None and len(day_odds) > 0:
save_sbr_odds_info('mlb', date, day_odds)
saved += 1
hit += 1
date += datetime.timedelta(days=1)
pbar.update(value=hit)
pbar.finish()
return saved
def scrape_nba_odds_range(min_date=None, max_date=None):
min_date = min_date or datetime.datetime.today() - datetime.timedelta(days=1)
max_date = max_date or datetime.datetime.today()
if isinstance(min_date, basestring):
min_date = parser.parse(min_date)
if isinstance(max_date, basestring):
max_date = parser.parse(max_date)
date = min_date
pbar = progressbar.ProgressBar(widgets=[progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.ETA()],
maxval=int((max_date-min_date).total_seconds() / (60*60*24)) + 1)
pbar.start()
saved = 0
hit = 0
while date <= max_date:
day_odds = load_odds_for_day(date)
if day_odds is not None and len(day_odds) > 0:
save_sbr_odds_info('nba', date, day_odds)
saved += 1
hit += 1
date += datetime.timedelta(days=1)
pbar.update(value=hit)
pbar.finish()
return saved
def __iter__(self):
if self.count != 0:
widgets = [
'%s: ' % (self.caption,),
progressbar.Percentage(),
' ',
progressbar.Bar(),
' ',
progressbar.ETA(),
]
pbar = progressbar.ProgressBar(widgets=widgets, maxval=self.count)
pbar.start()
for idx, item in enumerate(self.iterator):
yield item
pbar.update(idx)
pbar.finish()
def _setup_progress(self, options):
if options.progress:
if self.beanstalk:
# With Beanstalk C&C we don't know how many...
self.progress = progressbar.ProgressBar(
redirect_stdout=True,
redirect_stderr=True,
widgets=[
'Total: ',
progressbar.Counter(),
', ',
progressbar.Timer()
])
else:
self.progress = progressbar.ProgressBar(
redirect_stdout=True,
redirect_stderr=True,
widgets=[
progressbar.Percentage(),
progressbar.Bar(),
' (', progressbar.ETA(), ') ',
])
else:
self.progress = None
def __init__(self, options):
self.wildcards = []
self.options = options
self.domains = []
if options.domains:
self.domains += filter(None, options.domains.read().split("\n"))
self.domains += options.domain
self.domains = list(set(self.domains))
random.shuffle(self.domains)
self.resolvers = map(str.strip, filter(None, options.resolvers.read().split("\n")))
random.shuffle(self.resolvers)
self.names = [X for X in self._load_names(options.names)]
if options.progress:
self.progress = progressbar.ProgressBar(
redirect_stdout=True,
redirect_stderr=True,
widgets=[
progressbar.Percentage(),
progressbar.Bar(),
' (', progressbar.ETA(), ') ',
])
else:
self.progress = None
self.finished = 0
LOG.info("%d names, %d resolvers, %d domains",
len(self.names), len(self.resolvers), len(self.domains))
def download(number, save_dir='./'):
"""Download pre-trained word vector
:param number: integer, default ``None``
:param save_dir: str, default './'
:return: file path for downloaded file
"""
df = load_datasets()
row = df.iloc[[number]]
url = ''.join(row.URL)
if not url:
print('The word vector you specified was not found. Please specify correct name.')
widgets = ['Test: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA(), ' ', FileTransferSpeed()]
pbar = ProgressBar(widgets=widgets)
def dlProgress(count, blockSize, totalSize):
if pbar.max_value is None:
pbar.max_value = totalSize
pbar.start()
pbar.update(min(count * blockSize, totalSize))
file_name = url.split('/')[-1]
if not os.path.exists(save_dir):
os.makedirs(save_dir)
save_path = os.path.join(save_dir, file_name)
path, _ = urlretrieve(url, save_path, reporthook=dlProgress)
pbar.finish()
return path
def __enter__(self):
self.bar = progressbar.ProgressBar(
widgets=[
progressbar.Percentage(),
' ',
progressbar.Bar(),
progressbar.FileTransferSpeed(),
' ',
progressbar.ETA(),
],
max_value=self.max_value,
)
self.fd = open(self.output_path, 'wb')
return self
def train(self):
data = Data(self.train_dat, self.train_lab)
batch_num = self.length/self.batch_size if self.length%self.batch_size == 0 else self.length/self.batch_size + 1
model = self.add_model()
with self.sess as sess:
tf.initialize_all_variables().run()
for ite in range(self.iterations):
print "Iteration {}".format(ite)
cost = 0.
pbar = pb.ProgressBar(widgets=[pb.Percentage(), pb.Bar(), pb.ETA()], maxval=batch_num).start()
for i in range(batch_num):
batch_x, batch_y = data.next_batch(self.batch_size)
c, _ = self.sess.run([model['loss'], model['optimizer']], feed_dict={model['train_x']:batch_x, model['train_y']:batch_y, model['p_keep_dens']:0.75})
cost += c / batch_num
pbar.update(i+1)
pbar.finish()
print ">>cost: {}".format(cost)
t_acc, d_acc = self.eval(model, 3000)
# early stop
if t_acc >= 0.995 and d_acc >= 0.995:
break
self.predict(model)
def __tag__(self):
return "ETA"
def __call__(self, epoch):
if self._batches is None:
logger.info("Preparing evaluation data...")
self._batches = self.reader.input_module.batch_generator(self._dataset, self._batch_size, is_eval=True)
logger.info("Started evaluation %s" % self._info)
metrics = defaultdict(lambda: list())
bar = progressbar.ProgressBar(
max_value=len(self._dataset) // self._batch_size + 1,
widgets=[' [', progressbar.Timer(), '] ', progressbar.Bar(), ' (', progressbar.ETA(), ') '])
for i, batch in bar(enumerate(self._batches)):
inputs = self._dataset[i * self._batch_size:(i + 1) * self._batch_size]
predictions = self.reader.model_module(batch, self._ports)
m = self.apply_metrics(inputs, predictions)
for k in self._metrics:
metrics[k].append(m[k])
metrics = self.combine_metrics(metrics)
super().add_to_history(metrics, self._iter, epoch)
printmetrics = sorted(metrics.keys())
res = "Epoch %d\tIter %d\ttotal %d" % (epoch, self._iter, self._total)
for m in printmetrics:
res += '\t%s: %.3f' % (m, metrics[m])
self.update_summary(self._iter, self._info + '_' + m, metrics[m])
if self._write_metrics_to is not None:
with open(self._write_metrics_to, 'a') as f:
f.write("{0} {1} {2:.5}\n".format(datetime.now(), self._info + '_' + m,
np.round(metrics[m], 5)))
res += '\t' + self._info
logger.info(res)
if self._side_effect is not None:
self._side_effect_state = self._side_effect(metrics, self._side_effect_state)
def get_pbar(num, prefix=""):
assert isinstance(prefix, str)
pbar = pb.ProgressBar(widgets=[prefix, pb.Percentage(), pb.Bar(), pb.ETA()], maxval=num)
return pbar
def collect_mailinfos(server, folder_contents, outpath_format):
#construct progressbar
progressbar_widgets = [
'[Choosing mails for download ] ',
progressbar.Percentage(),
progressbar.Bar(marker=progressbar.RotatingMarker()), ' ', progressbar.ETA()]
total_count = 0
for folder, mailids in folder_contents.items():
total_count += len(mailids)
progressbar_instance = progressbar.ProgressBar(widgets=progressbar_widgets, maxval=total_count).start()
#collect all mailinfos
mailinfos = {}
mailinfo_count = 0
for folder, mailids in folder_contents.items():
mailinfos[folder] = []
#get mailinfo bit by bit
server.select_folder(folder, readonly=True)
for mailid in mailids:
#fetch mail information
mailinfo = server.fetch([mailid], ['ENVELOPE', 'INTERNALDATE', 'RFC822.SIZE'])[mailid]
mailsize = bitmath.Byte(mailinfo[b'RFC822.SIZE'])
mailfilename = construct_mailfilename(outpath_format, mailinfo, args.outdir, folder, mailid)
#only add if mailfilename can be constructed
if mailfilename:
mailinfos[folder].append((mailid, mailfilename, mailsize))
mailinfo_count += 1
progressbar_instance.update(mailinfo_count)
progressbar_instance.finish()
return mailinfos
def create_app(load_db=True, populate_qr_cache=True, progressbar=False):
# Set up logging
log_level = os.environ.get('AF_LOGGING_LEVEL', None)
if log_level is not None:
log_levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
if log_level.upper() in log_levels:
log_level = getattr(log, log_level)
log.basicConfig(level=log_level)
else:
log.warning('Invalid log level: {}'.format(log_level.upper()))
else:
log.warning('No log level set, using default level.')
log.info('Creating Flask application')
app = Flask(__name__)
app.register_blueprint(root)
# Now load the database if requested
if load_db:
from . import database_handler as dh
log.info('Loading database.')
dh.get_database() # This loads the database into memory.
log.info('Database loaded.')
if populate_qr_cache:
if progressbar:
from progressbar import ProgressBar, Bar, Timer, ETA
pbar = ProgressBar(widgets=['Populating QR cache: ', Bar(),
' ', Timer(), ' ', ETA()])
kwargs = {'pbar': pbar}
else:
log.info('Populating QR cache.')
kwargs = {}
from .cache_utils import populate_qr_cache
populate_qr_cache(**kwargs)
return app
def __init__(self, msg, maxval, widgets=None, extrapos=-1):
self.msg = msg
self.extrapos = extrapos
if not widgets:
widgets = [progressbar.Percentage(), ' ', progressbar.Bar(), ' ',
progressbar.ETA()]
self.extrapos = 4
try:
self._resize_default = signal.getsignal(signal.SIGWINCH)
except:
self._resize_default = None
progressbar.ProgressBar.__init__(self, maxval, [self.msg + ": "] + widgets, fd=sys.stdout)
style_transfer.py 文件源码
项目:deepdream-neural-style-transfer
作者: rdcolema
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def _create_pbar(self, max_iter):
"""
Creates a progress bar.
"""
self.grad_iter = 0
self.pbar = pb.ProgressBar()
self.pbar.widgets = ["Optimizing: ", pb.Percentage(),
" ", pb.Bar(marker=pb.AnimatedMarker()),
" ", pb.ETA()]
self.pbar.maxval = max_iter
def setup_progressbar(self):
from progressbar import ProgressBar, FileTransferSpeed, Bar, Percentage, ETA
return ProgressBar(widgets=[FileTransferSpeed(), ' <<<', Bar(), '>>> ', Percentage(), ' ', ETA()])
def __init__(self, widgets=None, **kwargs):
import progressbar as pb
logging.Handler.__init__(self)
if widgets is None:
class CommaProgress(pb.widgets.WidgetBase):
def __call__(self, progress, data):
return '{value:,} of {max_value:,}'.format(**data)
widgets = [' ', CommaProgress(), ' (', pb.Percentage(), ') ',
pb.Bar(), ' ', pb.ETA()]
self.pbar_args = {'widgets': widgets}
self.pbar_args.update(kwargs)
def _get_progress_widgets(self):
"""
Returns the progress widgets for a file download.
"""
format_custom_text = progressbar.FormatCustomText(
'Fetching [ %(file)s ] :: ', dict(file=self.remote_file_name),
)
widgets = [
format_custom_text,
progressbar.ETA(),
progressbar.Percentage(),
progressbar.Bar(),
]
return widgets
def transfer(self):
image_reshape = np.ndarray(shape=(self.pre_images.shape[0], self.output_rows, self.output_cols, 3),
dtype=np.float16)
widgets = ['Transfer: ', pbar.Percentage(), ' ', pbar.Bar('>'), ' ', pbar.ETA()]
image_bar = pbar.ProgressBar(widgets=widgets, maxval=self.pre_images.shape[0]).start()
for i in range(0, self.pre_images.shape[0]):
image = self.pre_images[i].reshape(self.pre_img_rows, self.pre_img_cols)
image = image.astype('uint8')
im = Image.fromarray(image) # monochromatic image
imrgb = im.convert('RGB')
imrgb = imrgb.resize((self.output_rows, self.output_cols), Image.ANTIALIAS)
im = np.array(imrgb, dtype=np.float16)
im[:, :, 0] -= imagenet_mean['R']
im[:, :, 1] -= imagenet_mean['G']
im[:, :, 2] -= imagenet_mean['B']
# 'RGB'->'BGR', historical reasons in OpenCV
im = im[:, :, ::-1]
image_reshape[i] = im
# test for correct convert!
# if i < 3:
# img = Image.fromarray(np.uint8(im))
# img.save(str(i) + '.jpeg', 'jpeg')
image_bar.update(i + 1)
image_bar.finish()
print('image_reshape:', image_reshape.shape)
return image_reshape