id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
235,700 | automl/HpBandSter | hpbandster/examples/plot_example_7_interactive_plot.py | realtime_learning_curves | def realtime_learning_curves(runs):
"""
example how to extract a different kind of learning curve.
The x values are now the time the runs finished, not the budget anymore.
We no longer plot the validation loss on the y axis, but now the test accuracy.
This is just to show how to get different information into the interactive plot.
"""
sr = sorted(runs, key=lambda r: r.budget)
lc = list(filter(lambda t: not t[1] is None, [(r.time_stamps['finished'], r.info['test accuracy']) for r in sr]))
return([lc,]) | python | def realtime_learning_curves(runs):
sr = sorted(runs, key=lambda r: r.budget)
lc = list(filter(lambda t: not t[1] is None, [(r.time_stamps['finished'], r.info['test accuracy']) for r in sr]))
return([lc,]) | [
"def",
"realtime_learning_curves",
"(",
"runs",
")",
":",
"sr",
"=",
"sorted",
"(",
"runs",
",",
"key",
"=",
"lambda",
"r",
":",
"r",
".",
"budget",
")",
"lc",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"t",
":",
"not",
"t",
"[",
"1",
"]",
"is",
... | example how to extract a different kind of learning curve.
The x values are now the time the runs finished, not the budget anymore.
We no longer plot the validation loss on the y axis, but now the test accuracy.
This is just to show how to get different information into the interactive plot. | [
"example",
"how",
"to",
"extract",
"a",
"different",
"kind",
"of",
"learning",
"curve",
".",
"The",
"x",
"values",
"are",
"now",
"the",
"time",
"the",
"runs",
"finished",
"not",
"the",
"budget",
"anymore",
".",
"We",
"no",
"longer",
"plot",
"the",
"valid... | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/examples/plot_example_7_interactive_plot.py#L39-L51 |
235,701 | automl/HpBandSter | hpbandster/core/worker.py | Worker.load_nameserver_credentials | def load_nameserver_credentials(self, working_directory, num_tries=60, interval=1):
"""
loads the nameserver credentials in cases where master and workers share a filesystem
Parameters
----------
working_directory: str
the working directory for the HPB run (see master)
num_tries: int
number of attempts to find the file (default 60)
interval: float
waiting period between the attempts
"""
fn = os.path.join(working_directory, 'HPB_run_%s_pyro.pkl'%self.run_id)
for i in range(num_tries):
try:
with open(fn, 'rb') as fh:
self.nameserver, self.nameserver_port = pickle.load(fh)
return
except FileNotFoundError:
self.logger.warning('config file %s not found (trail %i/%i)'%(fn, i+1, num_tries))
time.sleep(interval)
except:
raise
raise RuntimeError("Could not find the nameserver information, aborting!") | python | def load_nameserver_credentials(self, working_directory, num_tries=60, interval=1):
fn = os.path.join(working_directory, 'HPB_run_%s_pyro.pkl'%self.run_id)
for i in range(num_tries):
try:
with open(fn, 'rb') as fh:
self.nameserver, self.nameserver_port = pickle.load(fh)
return
except FileNotFoundError:
self.logger.warning('config file %s not found (trail %i/%i)'%(fn, i+1, num_tries))
time.sleep(interval)
except:
raise
raise RuntimeError("Could not find the nameserver information, aborting!") | [
"def",
"load_nameserver_credentials",
"(",
"self",
",",
"working_directory",
",",
"num_tries",
"=",
"60",
",",
"interval",
"=",
"1",
")",
":",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"working_directory",
",",
"'HPB_run_%s_pyro.pkl'",
"%",
"self",
"."... | loads the nameserver credentials in cases where master and workers share a filesystem
Parameters
----------
working_directory: str
the working directory for the HPB run (see master)
num_tries: int
number of attempts to find the file (default 60)
interval: float
waiting period between the attempts | [
"loads",
"the",
"nameserver",
"credentials",
"in",
"cases",
"where",
"master",
"and",
"workers",
"share",
"a",
"filesystem"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/worker.py#L70-L95 |
235,702 | automl/HpBandSter | hpbandster/core/master.py | Master.wait_for_workers | def wait_for_workers(self, min_n_workers=1):
"""
helper function to hold execution until some workers are active
Parameters
----------
min_n_workers: int
minimum number of workers present before the run starts
"""
self.logger.debug('wait_for_workers trying to get the condition')
with self.thread_cond:
while (self.dispatcher.number_of_workers() < min_n_workers):
self.logger.debug('HBMASTER: only %i worker(s) available, waiting for at least %i.'%(self.dispatcher.number_of_workers(), min_n_workers))
self.thread_cond.wait(1)
self.dispatcher.trigger_discover_worker()
self.logger.debug('Enough workers to start this run!') | python | def wait_for_workers(self, min_n_workers=1):
self.logger.debug('wait_for_workers trying to get the condition')
with self.thread_cond:
while (self.dispatcher.number_of_workers() < min_n_workers):
self.logger.debug('HBMASTER: only %i worker(s) available, waiting for at least %i.'%(self.dispatcher.number_of_workers(), min_n_workers))
self.thread_cond.wait(1)
self.dispatcher.trigger_discover_worker()
self.logger.debug('Enough workers to start this run!') | [
"def",
"wait_for_workers",
"(",
"self",
",",
"min_n_workers",
"=",
"1",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'wait_for_workers trying to get the condition'",
")",
"with",
"self",
".",
"thread_cond",
":",
"while",
"(",
"self",
".",
"dispatcher",
... | helper function to hold execution until some workers are active
Parameters
----------
min_n_workers: int
minimum number of workers present before the run starts | [
"helper",
"function",
"to",
"hold",
"execution",
"until",
"some",
"workers",
"are",
"active"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/master.py#L135-L152 |
235,703 | automl/HpBandSter | hpbandster/core/master.py | Master.run | def run(self, n_iterations=1, min_n_workers=1, iteration_kwargs = {},):
"""
run n_iterations of SuccessiveHalving
Parameters
----------
n_iterations: int
number of iterations to be performed in this run
min_n_workers: int
minimum number of workers before starting the run
"""
self.wait_for_workers(min_n_workers)
iteration_kwargs.update({'result_logger': self.result_logger})
if self.time_ref is None:
self.time_ref = time.time()
self.config['time_ref'] = self.time_ref
self.logger.info('HBMASTER: starting run at %s'%(str(self.time_ref)))
self.thread_cond.acquire()
while True:
self._queue_wait()
next_run = None
# find a new run to schedule
for i in self.active_iterations():
next_run = self.iterations[i].get_next_run()
if not next_run is None: break
if not next_run is None:
self.logger.debug('HBMASTER: schedule new run for iteration %i'%i)
self._submit_job(*next_run)
continue
else:
if n_iterations > 0: #we might be able to start the next iteration
self.iterations.append(self.get_next_iteration(len(self.iterations), iteration_kwargs))
n_iterations -= 1
continue
# at this point there is no imediate run that can be scheduled,
# so wait for some job to finish if there are active iterations
if self.active_iterations():
self.thread_cond.wait()
else:
break
self.thread_cond.release()
for i in self.warmstart_iteration:
i.fix_timestamps(self.time_ref)
ws_data = [i.data for i in self.warmstart_iteration]
return Result([copy.deepcopy(i.data) for i in self.iterations] + ws_data, self.config) | python | def run(self, n_iterations=1, min_n_workers=1, iteration_kwargs = {},):
self.wait_for_workers(min_n_workers)
iteration_kwargs.update({'result_logger': self.result_logger})
if self.time_ref is None:
self.time_ref = time.time()
self.config['time_ref'] = self.time_ref
self.logger.info('HBMASTER: starting run at %s'%(str(self.time_ref)))
self.thread_cond.acquire()
while True:
self._queue_wait()
next_run = None
# find a new run to schedule
for i in self.active_iterations():
next_run = self.iterations[i].get_next_run()
if not next_run is None: break
if not next_run is None:
self.logger.debug('HBMASTER: schedule new run for iteration %i'%i)
self._submit_job(*next_run)
continue
else:
if n_iterations > 0: #we might be able to start the next iteration
self.iterations.append(self.get_next_iteration(len(self.iterations), iteration_kwargs))
n_iterations -= 1
continue
# at this point there is no imediate run that can be scheduled,
# so wait for some job to finish if there are active iterations
if self.active_iterations():
self.thread_cond.wait()
else:
break
self.thread_cond.release()
for i in self.warmstart_iteration:
i.fix_timestamps(self.time_ref)
ws_data = [i.data for i in self.warmstart_iteration]
return Result([copy.deepcopy(i.data) for i in self.iterations] + ws_data, self.config) | [
"def",
"run",
"(",
"self",
",",
"n_iterations",
"=",
"1",
",",
"min_n_workers",
"=",
"1",
",",
"iteration_kwargs",
"=",
"{",
"}",
",",
")",
":",
"self",
".",
"wait_for_workers",
"(",
"min_n_workers",
")",
"iteration_kwargs",
".",
"update",
"(",
"{",
"'re... | run n_iterations of SuccessiveHalving
Parameters
----------
n_iterations: int
number of iterations to be performed in this run
min_n_workers: int
minimum number of workers before starting the run | [
"run",
"n_iterations",
"of",
"SuccessiveHalving"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/master.py#L176-L233 |
235,704 | automl/HpBandSter | hpbandster/core/master.py | Master.job_callback | def job_callback(self, job):
"""
method to be called when a job has finished
this will do some book keeping and call the user defined
new_result_callback if one was specified
"""
self.logger.debug('job_callback for %s started'%str(job.id))
with self.thread_cond:
self.logger.debug('job_callback for %s got condition'%str(job.id))
self.num_running_jobs -= 1
if not self.result_logger is None:
self.result_logger(job)
self.iterations[job.id[0]].register_result(job)
self.config_generator.new_result(job)
if self.num_running_jobs <= self.job_queue_sizes[0]:
self.logger.debug("HBMASTER: Trying to run another job!")
self.thread_cond.notify()
self.logger.debug('job_callback for %s finished'%str(job.id)) | python | def job_callback(self, job):
self.logger.debug('job_callback for %s started'%str(job.id))
with self.thread_cond:
self.logger.debug('job_callback for %s got condition'%str(job.id))
self.num_running_jobs -= 1
if not self.result_logger is None:
self.result_logger(job)
self.iterations[job.id[0]].register_result(job)
self.config_generator.new_result(job)
if self.num_running_jobs <= self.job_queue_sizes[0]:
self.logger.debug("HBMASTER: Trying to run another job!")
self.thread_cond.notify()
self.logger.debug('job_callback for %s finished'%str(job.id)) | [
"def",
"job_callback",
"(",
"self",
",",
"job",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'job_callback for %s started'",
"%",
"str",
"(",
"job",
".",
"id",
")",
")",
"with",
"self",
".",
"thread_cond",
":",
"self",
".",
"logger",
".",
"debu... | method to be called when a job has finished
this will do some book keeping and call the user defined
new_result_callback if one was specified | [
"method",
"to",
"be",
"called",
"when",
"a",
"job",
"has",
"finished"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/master.py#L248-L269 |
235,705 | automl/HpBandSter | hpbandster/core/master.py | Master._submit_job | def _submit_job(self, config_id, config, budget):
"""
hidden function to submit a new job to the dispatcher
This function handles the actual submission in a
(hopefully) thread save way
"""
self.logger.debug('HBMASTER: trying submitting job %s to dispatcher'%str(config_id))
with self.thread_cond:
self.logger.debug('HBMASTER: submitting job %s to dispatcher'%str(config_id))
self.dispatcher.submit_job(config_id, config=config, budget=budget, working_directory=self.working_directory)
self.num_running_jobs += 1
#shouldn't the next line be executed while holding the condition?
self.logger.debug("HBMASTER: job %s submitted to dispatcher"%str(config_id)) | python | def _submit_job(self, config_id, config, budget):
self.logger.debug('HBMASTER: trying submitting job %s to dispatcher'%str(config_id))
with self.thread_cond:
self.logger.debug('HBMASTER: submitting job %s to dispatcher'%str(config_id))
self.dispatcher.submit_job(config_id, config=config, budget=budget, working_directory=self.working_directory)
self.num_running_jobs += 1
#shouldn't the next line be executed while holding the condition?
self.logger.debug("HBMASTER: job %s submitted to dispatcher"%str(config_id)) | [
"def",
"_submit_job",
"(",
"self",
",",
"config_id",
",",
"config",
",",
"budget",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'HBMASTER: trying submitting job %s to dispatcher'",
"%",
"str",
"(",
"config_id",
")",
")",
"with",
"self",
".",
"thread_co... | hidden function to submit a new job to the dispatcher
This function handles the actual submission in a
(hopefully) thread save way | [
"hidden",
"function",
"to",
"submit",
"a",
"new",
"job",
"to",
"the",
"dispatcher"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/master.py#L281-L295 |
235,706 | automl/HpBandSter | hpbandster/optimizers/learning_curve_models/lcnet.py | LCNetWrapper.fit | def fit(self, times, losses, configs=None):
"""
function to train the model on the observed data
Parameters:
-----------
times: list
list of numpy arrays of the timesteps for each curve
losses: list
list of numpy arrays of the loss (the actual learning curve)
configs: list or None
list of the configurations for each sample. Each element
has to be a numpy array. Set to None, if no configuration
information is available.
"""
assert np.all(times > 0) and np.all(times <= self.max_num_epochs)
train = None
targets = None
for i in range(len(configs)):
t_idx = times[i] / self.max_num_epochs
x = np.repeat(np.array(configs[i])[None, :], t_idx.shape[0], axis=0)
x = np.concatenate((x, t_idx[:, None]), axis=1)
# LCNet assumes increasing curves, if we feed in losses here we have to flip the curves
lc = [1 - l for l in losses[i]]
if train is None:
train = x
targets = lc
else:
train = np.concatenate((train, x), 0)
targets = np.concatenate((targets, lc), 0)
self.model.train(train, targets) | python | def fit(self, times, losses, configs=None):
assert np.all(times > 0) and np.all(times <= self.max_num_epochs)
train = None
targets = None
for i in range(len(configs)):
t_idx = times[i] / self.max_num_epochs
x = np.repeat(np.array(configs[i])[None, :], t_idx.shape[0], axis=0)
x = np.concatenate((x, t_idx[:, None]), axis=1)
# LCNet assumes increasing curves, if we feed in losses here we have to flip the curves
lc = [1 - l for l in losses[i]]
if train is None:
train = x
targets = lc
else:
train = np.concatenate((train, x), 0)
targets = np.concatenate((targets, lc), 0)
self.model.train(train, targets) | [
"def",
"fit",
"(",
"self",
",",
"times",
",",
"losses",
",",
"configs",
"=",
"None",
")",
":",
"assert",
"np",
".",
"all",
"(",
"times",
">",
"0",
")",
"and",
"np",
".",
"all",
"(",
"times",
"<=",
"self",
".",
"max_num_epochs",
")",
"train",
"=",... | function to train the model on the observed data
Parameters:
-----------
times: list
list of numpy arrays of the timesteps for each curve
losses: list
list of numpy arrays of the loss (the actual learning curve)
configs: list or None
list of the configurations for each sample. Each element
has to be a numpy array. Set to None, if no configuration
information is available. | [
"function",
"to",
"train",
"the",
"model",
"on",
"the",
"observed",
"data"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/learning_curve_models/lcnet.py#L24-L63 |
235,707 | automl/HpBandSter | hpbandster/optimizers/learning_curve_models/lcnet.py | LCNetWrapper.predict_unseen | def predict_unseen(self, times, config):
"""
predict the loss of an unseen configuration
Parameters:
-----------
times: numpy array
times where to predict the loss
config: numpy array
the numerical representation of the config
Returns:
--------
mean and variance prediction at input times for the given config
"""
assert np.all(times > 0) and np.all(times <= self.max_num_epochs)
x = np.array(config)[None, :]
idx = times / self.max_num_epochs
x = np.repeat(x, idx.shape[0], axis=0)
x = np.concatenate((x, idx[:, None]), axis=1)
mean, var = self.model.predict(x)
return 1 - mean, var | python | def predict_unseen(self, times, config):
assert np.all(times > 0) and np.all(times <= self.max_num_epochs)
x = np.array(config)[None, :]
idx = times / self.max_num_epochs
x = np.repeat(x, idx.shape[0], axis=0)
x = np.concatenate((x, idx[:, None]), axis=1)
mean, var = self.model.predict(x)
return 1 - mean, var | [
"def",
"predict_unseen",
"(",
"self",
",",
"times",
",",
"config",
")",
":",
"assert",
"np",
".",
"all",
"(",
"times",
">",
"0",
")",
"and",
"np",
".",
"all",
"(",
"times",
"<=",
"self",
".",
"max_num_epochs",
")",
"x",
"=",
"np",
".",
"array",
"... | predict the loss of an unseen configuration
Parameters:
-----------
times: numpy array
times where to predict the loss
config: numpy array
the numerical representation of the config
Returns:
--------
mean and variance prediction at input times for the given config | [
"predict",
"the",
"loss",
"of",
"an",
"unseen",
"configuration"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/learning_curve_models/lcnet.py#L65-L93 |
235,708 | automl/HpBandSter | hpbandster/optimizers/learning_curve_models/lcnet.py | LCNetWrapper.extend_partial | def extend_partial(self, times, obs_times, obs_losses, config=None):
"""
extends a partially observed curve
Parameters:
-----------
times: numpy array
times where to predict the loss
obs_times: numpy array
times where the curve has already been observed
obs_losses: numpy array
corresponding observed losses
config: numpy array
numerical reperesentation of the config; None if no config
information is available
Returns:
--------
mean and variance prediction at input times
"""
return self.predict_unseen(times, config) | python | def extend_partial(self, times, obs_times, obs_losses, config=None):
return self.predict_unseen(times, config) | [
"def",
"extend_partial",
"(",
"self",
",",
"times",
",",
"obs_times",
",",
"obs_losses",
",",
"config",
"=",
"None",
")",
":",
"return",
"self",
".",
"predict_unseen",
"(",
"times",
",",
"config",
")"
] | extends a partially observed curve
Parameters:
-----------
times: numpy array
times where to predict the loss
obs_times: numpy array
times where the curve has already been observed
obs_losses: numpy array
corresponding observed losses
config: numpy array
numerical reperesentation of the config; None if no config
information is available
Returns:
--------
mean and variance prediction at input times | [
"extends",
"a",
"partially",
"observed",
"curve"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/learning_curve_models/lcnet.py#L95-L119 |
235,709 | automl/HpBandSter | hpbandster/core/base_config_generator.py | base_config_generator.new_result | def new_result(self, job, update_model=True):
"""
registers finished runs
Every time a run has finished, this function should be called
to register it with the result logger. If overwritten, make
sure to call this method from the base class to ensure proper
logging.
Parameters
----------
job: instance of hpbandster.distributed.dispatcher.Job
contains all necessary information about the job
update_model: boolean
determines whether a model inside the config_generator should be updated
"""
if not job.exception is None:
self.logger.warning("job {} failed with exception\n{}".format(job.id, job.exception)) | python | def new_result(self, job, update_model=True):
if not job.exception is None:
self.logger.warning("job {} failed with exception\n{}".format(job.id, job.exception)) | [
"def",
"new_result",
"(",
"self",
",",
"job",
",",
"update_model",
"=",
"True",
")",
":",
"if",
"not",
"job",
".",
"exception",
"is",
"None",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"job {} failed with exception\\n{}\"",
".",
"format",
"(",
"job... | registers finished runs
Every time a run has finished, this function should be called
to register it with the result logger. If overwritten, make
sure to call this method from the base class to ensure proper
logging.
Parameters
----------
job: instance of hpbandster.distributed.dispatcher.Job
contains all necessary information about the job
update_model: boolean
determines whether a model inside the config_generator should be updated | [
"registers",
"finished",
"runs"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_config_generator.py#L47-L65 |
235,710 | automl/HpBandSter | hpbandster/optimizers/learning_curve_models/arif.py | ARIF.invert_differencing | def invert_differencing(self, initial_part, differenced_rest, order=None):
"""
function to invert the differencing
"""
if order is None: order = self.diff_order
# compute the differenced values of the initial part:
starting_points = [ self.apply_differencing(initial_part, order=order)[-1] for order in range(self.diff_order)]
actual_predictions = differenced_rest
import pdb
pdb.set_trace()
for s in starting_points[::-1]:
actual_predictions = np.cumsum(np.hstack([s, actual_predictions]))[1:]
return(actual_predictions) | python | def invert_differencing(self, initial_part, differenced_rest, order=None):
if order is None: order = self.diff_order
# compute the differenced values of the initial part:
starting_points = [ self.apply_differencing(initial_part, order=order)[-1] for order in range(self.diff_order)]
actual_predictions = differenced_rest
import pdb
pdb.set_trace()
for s in starting_points[::-1]:
actual_predictions = np.cumsum(np.hstack([s, actual_predictions]))[1:]
return(actual_predictions) | [
"def",
"invert_differencing",
"(",
"self",
",",
"initial_part",
",",
"differenced_rest",
",",
"order",
"=",
"None",
")",
":",
"if",
"order",
"is",
"None",
":",
"order",
"=",
"self",
".",
"diff_order",
"# compute the differenced values of the initial part:",
"startin... | function to invert the differencing | [
"function",
"to",
"invert",
"the",
"differencing"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/learning_curve_models/arif.py#L38-L54 |
235,711 | automl/HpBandSter | hpbandster/core/nameserver.py | nic_name_to_host | def nic_name_to_host(nic_name):
""" helper function to translate the name of a network card into a valid host name"""
from netifaces import ifaddresses, AF_INET
host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr']
return(host) | python | def nic_name_to_host(nic_name):
from netifaces import ifaddresses, AF_INET
host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr']
return(host) | [
"def",
"nic_name_to_host",
"(",
"nic_name",
")",
":",
"from",
"netifaces",
"import",
"ifaddresses",
",",
"AF_INET",
"host",
"=",
"ifaddresses",
"(",
"nic_name",
")",
".",
"setdefault",
"(",
"AF_INET",
",",
"[",
"{",
"'addr'",
":",
"'No IP addr'",
"}",
"]",
... | helper function to translate the name of a network card into a valid host name | [
"helper",
"function",
"to",
"translate",
"the",
"name",
"of",
"a",
"network",
"card",
"into",
"a",
"valid",
"host",
"name"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/nameserver.py#L9-L13 |
235,712 | automl/HpBandSter | hpbandster/core/base_iteration.py | BaseIteration.register_result | def register_result(self, job, skip_sanity_checks=False):
"""
function to register the result of a job
This function is called from HB_master, don't call this from
your script.
"""
if self.is_finished:
raise RuntimeError("This HB iteration is finished, you can't register more results!")
config_id = job.id
config = job.kwargs['config']
budget = job.kwargs['budget']
timestamps = job.timestamps
result = job.result
exception = job.exception
d = self.data[config_id]
if not skip_sanity_checks:
assert d.config == config, 'Configurations differ!'
assert d.status == 'RUNNING', "Configuration wasn't scheduled for a run."
assert d.budget == budget, 'Budgets differ (%f != %f)!'%(self.data[config_id]['budget'], budget)
d.time_stamps[budget] = timestamps
d.results[budget] = result
if (not job.result is None) and np.isfinite(result['loss']):
d.status = 'REVIEW'
else:
d.status = 'CRASHED'
d.exceptions[budget] = exception
self.num_running -= 1 | python | def register_result(self, job, skip_sanity_checks=False):
if self.is_finished:
raise RuntimeError("This HB iteration is finished, you can't register more results!")
config_id = job.id
config = job.kwargs['config']
budget = job.kwargs['budget']
timestamps = job.timestamps
result = job.result
exception = job.exception
d = self.data[config_id]
if not skip_sanity_checks:
assert d.config == config, 'Configurations differ!'
assert d.status == 'RUNNING', "Configuration wasn't scheduled for a run."
assert d.budget == budget, 'Budgets differ (%f != %f)!'%(self.data[config_id]['budget'], budget)
d.time_stamps[budget] = timestamps
d.results[budget] = result
if (not job.result is None) and np.isfinite(result['loss']):
d.status = 'REVIEW'
else:
d.status = 'CRASHED'
d.exceptions[budget] = exception
self.num_running -= 1 | [
"def",
"register_result",
"(",
"self",
",",
"job",
",",
"skip_sanity_checks",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_finished",
":",
"raise",
"RuntimeError",
"(",
"\"This HB iteration is finished, you can't register more results!\"",
")",
"config_id",
"=",
"jo... | function to register the result of a job
This function is called from HB_master, don't call this from
your script. | [
"function",
"to",
"register",
"the",
"result",
"of",
"a",
"job"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_iteration.py#L105-L139 |
235,713 | automl/HpBandSter | hpbandster/core/base_iteration.py | BaseIteration.get_next_run | def get_next_run(self):
"""
function to return the next configuration and budget to run.
This function is called from HB_master, don't call this from
your script.
It returns None if this run of SH is finished or there are
pending jobs that need to finish to progress to the next stage.
If there are empty slots to be filled in the current SH stage
(which never happens in the original SH version), a new
configuration will be sampled and scheduled to run next.
"""
if self.is_finished:
return(None)
for k,v in self.data.items():
if v.status == 'QUEUED':
assert v.budget == self.budgets[self.stage], 'Configuration budget does not align with current stage!'
v.status = 'RUNNING'
self.num_running += 1
return(k, v.config, v.budget)
# check if there are still slots to fill in the current stage and return that
if (self.actual_num_configs[self.stage] < self.num_configs[self.stage]):
self.add_configuration()
return(self.get_next_run())
if self.num_running == 0:
# at this point a stage is completed
self.process_results()
return(self.get_next_run())
return(None) | python | def get_next_run(self):
if self.is_finished:
return(None)
for k,v in self.data.items():
if v.status == 'QUEUED':
assert v.budget == self.budgets[self.stage], 'Configuration budget does not align with current stage!'
v.status = 'RUNNING'
self.num_running += 1
return(k, v.config, v.budget)
# check if there are still slots to fill in the current stage and return that
if (self.actual_num_configs[self.stage] < self.num_configs[self.stage]):
self.add_configuration()
return(self.get_next_run())
if self.num_running == 0:
# at this point a stage is completed
self.process_results()
return(self.get_next_run())
return(None) | [
"def",
"get_next_run",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_finished",
":",
"return",
"(",
"None",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"if",
"v",
".",
"status",
"==",
"'QUEUED'",
":",
"asser... | function to return the next configuration and budget to run.
This function is called from HB_master, don't call this from
your script.
It returns None if this run of SH is finished or there are
pending jobs that need to finish to progress to the next stage.
If there are empty slots to be filled in the current SH stage
(which never happens in the original SH version), a new
configuration will be sampled and scheduled to run next. | [
"function",
"to",
"return",
"the",
"next",
"configuration",
"and",
"budget",
"to",
"run",
"."
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_iteration.py#L141-L176 |
235,714 | automl/HpBandSter | hpbandster/core/base_iteration.py | BaseIteration.process_results | def process_results(self):
"""
function that is called when a stage is completed and
needs to be analyzed befor further computations.
The code here implements the original SH algorithms by
advancing the k-best (lowest loss) configurations at the current
budget. k is defined by the num_configs list (see __init__)
and the current stage value.
For more advanced methods like resampling after each stage,
overload this function only.
"""
self.stage += 1
# collect all config_ids that need to be compared
config_ids = list(filter(lambda cid: self.data[cid].status == 'REVIEW', self.data.keys()))
if (self.stage >= len(self.num_configs)):
self.finish_up()
return
budgets = [self.data[cid].budget for cid in config_ids]
if len(set(budgets)) > 1:
raise RuntimeError('Not all configurations have the same budget!')
budget = self.budgets[self.stage-1]
losses = np.array([self.data[cid].results[budget]['loss'] for cid in config_ids])
advance = self._advance_to_next_stage(config_ids, losses)
for i, a in enumerate(advance):
if a:
self.logger.debug('ITERATION: Advancing config %s to next budget %f'%(config_ids[i], self.budgets[self.stage]))
for i, cid in enumerate(config_ids):
if advance[i]:
self.data[cid].status = 'QUEUED'
self.data[cid].budget = self.budgets[self.stage]
self.actual_num_configs[self.stage] += 1
else:
self.data[cid].status = 'TERMINATED' | python | def process_results(self):
self.stage += 1
# collect all config_ids that need to be compared
config_ids = list(filter(lambda cid: self.data[cid].status == 'REVIEW', self.data.keys()))
if (self.stage >= len(self.num_configs)):
self.finish_up()
return
budgets = [self.data[cid].budget for cid in config_ids]
if len(set(budgets)) > 1:
raise RuntimeError('Not all configurations have the same budget!')
budget = self.budgets[self.stage-1]
losses = np.array([self.data[cid].results[budget]['loss'] for cid in config_ids])
advance = self._advance_to_next_stage(config_ids, losses)
for i, a in enumerate(advance):
if a:
self.logger.debug('ITERATION: Advancing config %s to next budget %f'%(config_ids[i], self.budgets[self.stage]))
for i, cid in enumerate(config_ids):
if advance[i]:
self.data[cid].status = 'QUEUED'
self.data[cid].budget = self.budgets[self.stage]
self.actual_num_configs[self.stage] += 1
else:
self.data[cid].status = 'TERMINATED' | [
"def",
"process_results",
"(",
"self",
")",
":",
"self",
".",
"stage",
"+=",
"1",
"# collect all config_ids that need to be compared",
"config_ids",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"cid",
":",
"self",
".",
"data",
"[",
"cid",
"]",
".",
"status",
"... | function that is called when a stage is completed and
needs to be analyzed befor further computations.
The code here implements the original SH algorithms by
advancing the k-best (lowest loss) configurations at the current
budget. k is defined by the num_configs list (see __init__)
and the current stage value.
For more advanced methods like resampling after each stage,
overload this function only. | [
"function",
"that",
"is",
"called",
"when",
"a",
"stage",
"is",
"completed",
"and",
"needs",
"to",
"be",
"analyzed",
"befor",
"further",
"computations",
"."
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_iteration.py#L201-L242 |
235,715 | automl/HpBandSter | hpbandster/core/base_iteration.py | WarmStartIteration.fix_timestamps | def fix_timestamps(self, time_ref):
"""
manipulates internal time stamps such that the last run ends at time 0
"""
for k,v in self.data.items():
for kk, vv in v.time_stamps.items():
for kkk,vvv in vv.items():
self.data[k].time_stamps[kk][kkk] += time_ref | python | def fix_timestamps(self, time_ref):
for k,v in self.data.items():
for kk, vv in v.time_stamps.items():
for kkk,vvv in vv.items():
self.data[k].time_stamps[kk][kkk] += time_ref | [
"def",
"fix_timestamps",
"(",
"self",
",",
"time_ref",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"for",
"kk",
",",
"vv",
"in",
"v",
".",
"time_stamps",
".",
"items",
"(",
")",
":",
"for",
"kkk",
","... | manipulates internal time stamps such that the last run ends at time 0 | [
"manipulates",
"internal",
"time",
"stamps",
"such",
"that",
"the",
"last",
"run",
"ends",
"at",
"time",
"0"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_iteration.py#L290-L298 |
235,716 | automl/HpBandSter | hpbandster/optimizers/config_generators/lcnet.py | LCNetWrapper.get_config | def get_config(self, budget):
"""
function to sample a new configuration
This function is called inside Hyperband to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
returns: config
should return a valid configuration
"""
self.lock.acquire()
if not self.is_trained:
c = self.config_space.sample_configuration().get_array()
else:
candidates = np.array([self.config_space.sample_configuration().get_array()
for _ in range(self.n_candidates)])
# We are only interested on the asymptotic value
projected_candidates = np.concatenate((candidates, np.ones([self.n_candidates, 1])), axis=1)
# Compute the upper confidence bound of the function at the asymptote
m, v = self.model.predict(projected_candidates)
ucb_values = m + self.delta * np.sqrt(v)
print(ucb_values)
# Sample a configuration based on the ucb values
p = np.ones(self.n_candidates) * (ucb_values / np.sum(ucb_values))
idx = np.random.choice(self.n_candidates, 1, False, p)
c = candidates[idx][0]
config = ConfigSpace.Configuration(self.config_space, vector=c)
self.lock.release()
return config.get_dictionary(), {} | python | def get_config(self, budget):
self.lock.acquire()
if not self.is_trained:
c = self.config_space.sample_configuration().get_array()
else:
candidates = np.array([self.config_space.sample_configuration().get_array()
for _ in range(self.n_candidates)])
# We are only interested on the asymptotic value
projected_candidates = np.concatenate((candidates, np.ones([self.n_candidates, 1])), axis=1)
# Compute the upper confidence bound of the function at the asymptote
m, v = self.model.predict(projected_candidates)
ucb_values = m + self.delta * np.sqrt(v)
print(ucb_values)
# Sample a configuration based on the ucb values
p = np.ones(self.n_candidates) * (ucb_values / np.sum(ucb_values))
idx = np.random.choice(self.n_candidates, 1, False, p)
c = candidates[idx][0]
config = ConfigSpace.Configuration(self.config_space, vector=c)
self.lock.release()
return config.get_dictionary(), {} | [
"def",
"get_config",
"(",
"self",
",",
"budget",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"if",
"not",
"self",
".",
"is_trained",
":",
"c",
"=",
"self",
".",
"config_space",
".",
"sample_configuration",
"(",
")",
".",
"get_array",
"(",
... | function to sample a new configuration
This function is called inside Hyperband to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
returns: config
should return a valid configuration | [
"function",
"to",
"sample",
"a",
"new",
"configuration"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/config_generators/lcnet.py#L63-L103 |
235,717 | automl/HpBandSter | hpbandster/core/result.py | extract_HBS_learning_curves | def extract_HBS_learning_curves(runs):
"""
function to get the hyperband learning curves
This is an example function showing the interface to use the
HB_result.get_learning_curves method.
Parameters
----------
runs: list of HB_result.run objects
the performed runs for an unspecified config
Returns
-------
list of learning curves: list of lists of tuples
An individual learning curve is a list of (t, x_t) tuples.
This function must return a list of these. One could think
of cases where one could extract multiple learning curves
from these runs, e.g. if each run is an independent training
run of a neural network on the data.
"""
sr = sorted(runs, key=lambda r: r.budget)
lc = list(filter(lambda t: not t[1] is None, [(r.budget, r.loss) for r in sr]))
return([lc,]) | python | def extract_HBS_learning_curves(runs):
sr = sorted(runs, key=lambda r: r.budget)
lc = list(filter(lambda t: not t[1] is None, [(r.budget, r.loss) for r in sr]))
return([lc,]) | [
"def",
"extract_HBS_learning_curves",
"(",
"runs",
")",
":",
"sr",
"=",
"sorted",
"(",
"runs",
",",
"key",
"=",
"lambda",
"r",
":",
"r",
".",
"budget",
")",
"lc",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"t",
":",
"not",
"t",
"[",
"1",
"]",
"is... | function to get the hyperband learning curves
This is an example function showing the interface to use the
HB_result.get_learning_curves method.
Parameters
----------
runs: list of HB_result.run objects
the performed runs for an unspecified config
Returns
-------
list of learning curves: list of lists of tuples
An individual learning curve is a list of (t, x_t) tuples.
This function must return a list of these. One could think
of cases where one could extract multiple learning curves
from these runs, e.g. if each run is an independent training
run of a neural network on the data. | [
"function",
"to",
"get",
"the",
"hyperband",
"learning",
"curves"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L35-L61 |
235,718 | automl/HpBandSter | hpbandster/core/result.py | logged_results_to_HBS_result | def logged_results_to_HBS_result(directory):
"""
function to import logged 'live-results' and return a HB_result object
You can load live run results with this function and the returned
HB_result object gives you access to the results the same way
a finished run would.
Parameters
----------
directory: str
the directory containing the results.json and config.json files
Returns
-------
hpbandster.core.result.Result: :object:
TODO
"""
data = {}
time_ref = float('inf')
budget_set = set()
with open(os.path.join(directory, 'configs.json')) as fh:
for line in fh:
line = json.loads(line)
if len(line) == 3:
config_id, config, config_info = line
if len(line) == 2:
config_id, config, = line
config_info = 'N/A'
data[tuple(config_id)] = Datum(config=config, config_info=config_info)
with open(os.path.join(directory, 'results.json')) as fh:
for line in fh:
config_id, budget,time_stamps, result, exception = json.loads(line)
id = tuple(config_id)
data[id].time_stamps[budget] = time_stamps
data[id].results[budget] = result
data[id].exceptions[budget] = exception
budget_set.add(budget)
time_ref = min(time_ref, time_stamps['submitted'])
# infer the hyperband configuration from the data
budget_list = sorted(list(budget_set))
HB_config = {
'eta' : None if len(budget_list) < 2 else budget_list[1]/budget_list[0],
'min_budget' : min(budget_set),
'max_budget' : max(budget_set),
'budgets' : budget_list,
'max_SH_iter': len(budget_set),
'time_ref' : time_ref
}
return(Result([data], HB_config)) | python | def logged_results_to_HBS_result(directory):
data = {}
time_ref = float('inf')
budget_set = set()
with open(os.path.join(directory, 'configs.json')) as fh:
for line in fh:
line = json.loads(line)
if len(line) == 3:
config_id, config, config_info = line
if len(line) == 2:
config_id, config, = line
config_info = 'N/A'
data[tuple(config_id)] = Datum(config=config, config_info=config_info)
with open(os.path.join(directory, 'results.json')) as fh:
for line in fh:
config_id, budget,time_stamps, result, exception = json.loads(line)
id = tuple(config_id)
data[id].time_stamps[budget] = time_stamps
data[id].results[budget] = result
data[id].exceptions[budget] = exception
budget_set.add(budget)
time_ref = min(time_ref, time_stamps['submitted'])
# infer the hyperband configuration from the data
budget_list = sorted(list(budget_set))
HB_config = {
'eta' : None if len(budget_list) < 2 else budget_list[1]/budget_list[0],
'min_budget' : min(budget_set),
'max_budget' : max(budget_set),
'budgets' : budget_list,
'max_SH_iter': len(budget_set),
'time_ref' : time_ref
}
return(Result([data], HB_config)) | [
"def",
"logged_results_to_HBS_result",
"(",
"directory",
")",
":",
"data",
"=",
"{",
"}",
"time_ref",
"=",
"float",
"(",
"'inf'",
")",
"budget_set",
"=",
"set",
"(",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'con... | function to import logged 'live-results' and return a HB_result object
You can load live run results with this function and the returned
HB_result object gives you access to the results the same way
a finished run would.
Parameters
----------
directory: str
the directory containing the results.json and config.json files
Returns
-------
hpbandster.core.result.Result: :object:
TODO | [
"function",
"to",
"import",
"logged",
"live",
"-",
"results",
"and",
"return",
"a",
"HB_result",
"object"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L139-L200 |
235,719 | automl/HpBandSter | hpbandster/core/result.py | Result.get_incumbent_id | def get_incumbent_id(self):
"""
Find the config_id of the incumbent.
The incumbent here is the configuration with the smallest loss
among all runs on the maximum budget! If no run finishes on the
maximum budget, None is returned!
"""
tmp_list = []
for k,v in self.data.items():
try:
# only things run for the max budget are considered
res = v.results[self.HB_config['max_budget']]
if not res is None:
tmp_list.append((res['loss'], k))
except KeyError as e:
pass
except:
raise
if len(tmp_list) > 0:
return(min(tmp_list)[1])
return(None) | python | def get_incumbent_id(self):
tmp_list = []
for k,v in self.data.items():
try:
# only things run for the max budget are considered
res = v.results[self.HB_config['max_budget']]
if not res is None:
tmp_list.append((res['loss'], k))
except KeyError as e:
pass
except:
raise
if len(tmp_list) > 0:
return(min(tmp_list)[1])
return(None) | [
"def",
"get_incumbent_id",
"(",
"self",
")",
":",
"tmp_list",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"try",
":",
"# only things run for the max budget are considered",
"res",
"=",
"v",
".",
"results",
... | Find the config_id of the incumbent.
The incumbent here is the configuration with the smallest loss
among all runs on the maximum budget! If no run finishes on the
maximum budget, None is returned! | [
"Find",
"the",
"config_id",
"of",
"the",
"incumbent",
"."
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L219-L241 |
235,720 | automl/HpBandSter | hpbandster/core/result.py | Result.get_runs_by_id | def get_runs_by_id(self, config_id):
"""
returns a list of runs for a given config id
The runs are sorted by ascending budget, so '-1' will give
the longest run for this config.
"""
d = self.data[config_id]
runs = []
for b in d.results.keys():
try:
err_logs = d.exceptions.get(b, None)
if d.results[b] is None:
r = Run(config_id, b, None, None , d.time_stamps[b], err_logs)
else:
r = Run(config_id, b, d.results[b]['loss'], d.results[b]['info'] , d.time_stamps[b], err_logs)
runs.append(r)
except:
raise
runs.sort(key=lambda r: r.budget)
return(runs) | python | def get_runs_by_id(self, config_id):
d = self.data[config_id]
runs = []
for b in d.results.keys():
try:
err_logs = d.exceptions.get(b, None)
if d.results[b] is None:
r = Run(config_id, b, None, None , d.time_stamps[b], err_logs)
else:
r = Run(config_id, b, d.results[b]['loss'], d.results[b]['info'] , d.time_stamps[b], err_logs)
runs.append(r)
except:
raise
runs.sort(key=lambda r: r.budget)
return(runs) | [
"def",
"get_runs_by_id",
"(",
"self",
",",
"config_id",
")",
":",
"d",
"=",
"self",
".",
"data",
"[",
"config_id",
"]",
"runs",
"=",
"[",
"]",
"for",
"b",
"in",
"d",
".",
"results",
".",
"keys",
"(",
")",
":",
"try",
":",
"err_logs",
"=",
"d",
... | returns a list of runs for a given config id
The runs are sorted by ascending budget, so '-1' will give
the longest run for this config. | [
"returns",
"a",
"list",
"of",
"runs",
"for",
"a",
"given",
"config",
"id"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L319-L341 |
235,721 | automl/HpBandSter | hpbandster/core/result.py | Result.get_learning_curves | def get_learning_curves(self, lc_extractor=extract_HBS_learning_curves, config_ids=None):
"""
extracts all learning curves from all run configurations
Parameters
----------
lc_extractor: callable
a function to return a list of learning_curves.
defaults to hpbanster.HB_result.extract_HP_learning_curves
config_ids: list of valid config ids
if only a subset of the config ids is wanted
Returns
-------
dict
a dictionary with the config_ids as keys and the
learning curves as values
"""
config_ids = self.data.keys() if config_ids is None else config_ids
lc_dict = {}
for id in config_ids:
runs = self.get_runs_by_id(id)
lc_dict[id] = lc_extractor(runs)
return(lc_dict) | python | def get_learning_curves(self, lc_extractor=extract_HBS_learning_curves, config_ids=None):
config_ids = self.data.keys() if config_ids is None else config_ids
lc_dict = {}
for id in config_ids:
runs = self.get_runs_by_id(id)
lc_dict[id] = lc_extractor(runs)
return(lc_dict) | [
"def",
"get_learning_curves",
"(",
"self",
",",
"lc_extractor",
"=",
"extract_HBS_learning_curves",
",",
"config_ids",
"=",
"None",
")",
":",
"config_ids",
"=",
"self",
".",
"data",
".",
"keys",
"(",
")",
"if",
"config_ids",
"is",
"None",
"else",
"config_ids",... | extracts all learning curves from all run configurations
Parameters
----------
lc_extractor: callable
a function to return a list of learning_curves.
defaults to hpbanster.HB_result.extract_HP_learning_curves
config_ids: list of valid config ids
if only a subset of the config ids is wanted
Returns
-------
dict
a dictionary with the config_ids as keys and the
learning curves as values | [
"extracts",
"all",
"learning",
"curves",
"from",
"all",
"run",
"configurations"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L344-L371 |
235,722 | automl/HpBandSter | hpbandster/core/result.py | Result.get_all_runs | def get_all_runs(self, only_largest_budget=False):
"""
returns all runs performed
Parameters
----------
only_largest_budget: boolean
if True, only the largest budget for each configuration
is returned. This makes sense if the runs are continued
across budgets and the info field contains the information
you care about. If False, all runs of a configuration
are returned
"""
all_runs = []
for k in self.data.keys():
runs = self.get_runs_by_id(k)
if len(runs) > 0:
if only_largest_budget:
all_runs.append(runs[-1])
else:
all_runs.extend(runs)
return(all_runs) | python | def get_all_runs(self, only_largest_budget=False):
all_runs = []
for k in self.data.keys():
runs = self.get_runs_by_id(k)
if len(runs) > 0:
if only_largest_budget:
all_runs.append(runs[-1])
else:
all_runs.extend(runs)
return(all_runs) | [
"def",
"get_all_runs",
"(",
"self",
",",
"only_largest_budget",
"=",
"False",
")",
":",
"all_runs",
"=",
"[",
"]",
"for",
"k",
"in",
"self",
".",
"data",
".",
"keys",
"(",
")",
":",
"runs",
"=",
"self",
".",
"get_runs_by_id",
"(",
"k",
")",
"if",
"... | returns all runs performed
Parameters
----------
only_largest_budget: boolean
if True, only the largest budget for each configuration
is returned. This makes sense if the runs are continued
across budgets and the info field contains the information
you care about. If False, all runs of a configuration
are returned | [
"returns",
"all",
"runs",
"performed"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L374-L398 |
235,723 | automl/HpBandSter | hpbandster/core/result.py | Result.get_id2config_mapping | def get_id2config_mapping(self):
"""
returns a dict where the keys are the config_ids and the values
are the actual configurations
"""
new_dict = {}
for k, v in self.data.items():
new_dict[k] = {}
new_dict[k]['config'] = copy.deepcopy(v.config)
try:
new_dict[k]['config_info'] = copy.deepcopy(v.config_info)
except:
pass
return(new_dict) | python | def get_id2config_mapping(self):
new_dict = {}
for k, v in self.data.items():
new_dict[k] = {}
new_dict[k]['config'] = copy.deepcopy(v.config)
try:
new_dict[k]['config_info'] = copy.deepcopy(v.config_info)
except:
pass
return(new_dict) | [
"def",
"get_id2config_mapping",
"(",
"self",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"new_dict",
"[",
"k",
"]",
"=",
"{",
"}",
"new_dict",
"[",
"k",
"]",
"[",
"'config'",
... | returns a dict where the keys are the config_ids and the values
are the actual configurations | [
"returns",
"a",
"dict",
"where",
"the",
"keys",
"are",
"the",
"config_ids",
"and",
"the",
"values",
"are",
"the",
"actual",
"configurations"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L400-L413 |
235,724 | automl/HpBandSter | hpbandster/core/result.py | Result._merge_results | def _merge_results(self):
"""
hidden function to merge the list of results into one
dictionary and 'normalize' the time stamps
"""
new_dict = {}
for it in self.data:
new_dict.update(it)
for k,v in new_dict.items():
for kk, vv in v.time_stamps.items():
for kkk,vvv in vv.items():
new_dict[k].time_stamps[kk][kkk] = vvv - self.HB_config['time_ref']
self.data = new_dict | python | def _merge_results(self):
new_dict = {}
for it in self.data:
new_dict.update(it)
for k,v in new_dict.items():
for kk, vv in v.time_stamps.items():
for kkk,vvv in vv.items():
new_dict[k].time_stamps[kk][kkk] = vvv - self.HB_config['time_ref']
self.data = new_dict | [
"def",
"_merge_results",
"(",
"self",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"it",
"in",
"self",
".",
"data",
":",
"new_dict",
".",
"update",
"(",
"it",
")",
"for",
"k",
",",
"v",
"in",
"new_dict",
".",
"items",
"(",
")",
":",
"for",
"kk",
... | hidden function to merge the list of results into one
dictionary and 'normalize' the time stamps | [
"hidden",
"function",
"to",
"merge",
"the",
"list",
"of",
"results",
"into",
"one",
"dictionary",
"and",
"normalize",
"the",
"time",
"stamps"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L415-L429 |
235,725 | Koed00/django-q | django_q/core_signing.py | TimestampSigner.unsign | def unsign(self, value, max_age=None):
"""
Retrieve original value and check it wasn't signed more
than max_age seconds ago.
"""
result = super(TimestampSigner, self).unsign(value)
value, timestamp = result.rsplit(self.sep, 1)
timestamp = baseconv.base62.decode(timestamp)
if max_age is not None:
if isinstance(max_age, datetime.timedelta):
max_age = max_age.total_seconds()
# Check timestamp is not older than max_age
age = time.time() - timestamp
if age > max_age:
raise SignatureExpired(
'Signature age %s > %s seconds' % (age, max_age))
return value | python | def unsign(self, value, max_age=None):
result = super(TimestampSigner, self).unsign(value)
value, timestamp = result.rsplit(self.sep, 1)
timestamp = baseconv.base62.decode(timestamp)
if max_age is not None:
if isinstance(max_age, datetime.timedelta):
max_age = max_age.total_seconds()
# Check timestamp is not older than max_age
age = time.time() - timestamp
if age > max_age:
raise SignatureExpired(
'Signature age %s > %s seconds' % (age, max_age))
return value | [
"def",
"unsign",
"(",
"self",
",",
"value",
",",
"max_age",
"=",
"None",
")",
":",
"result",
"=",
"super",
"(",
"TimestampSigner",
",",
"self",
")",
".",
"unsign",
"(",
"value",
")",
"value",
",",
"timestamp",
"=",
"result",
".",
"rsplit",
"(",
"self... | Retrieve original value and check it wasn't signed more
than max_age seconds ago. | [
"Retrieve",
"original",
"value",
"and",
"check",
"it",
"wasn",
"t",
"signed",
"more",
"than",
"max_age",
"seconds",
"ago",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/core_signing.py#L63-L79 |
235,726 | Koed00/django-q | django_q/humanhash.py | HumanHasher.humanize | def humanize(self, hexdigest, words=4, separator='-'):
"""
Humanize a given hexadecimal digest.
Change the number of words output by specifying `words`. Change the
word separator with `separator`.
>>> digest = '60ad8d0d871b6095808297'
>>> HumanHasher().humanize(digest)
'sodium-magnesium-nineteen-hydrogen'
"""
# Gets a list of byte values between 0-255.
bytes = [int(x, 16) for x in list(map(''.join, list(zip(hexdigest[::2], hexdigest[1::2]))))]
# Compress an arbitrary number of bytes to `words`.
compressed = self.compress(bytes, words)
# Map the compressed byte values through the word list.
return separator.join(self.wordlist[byte] for byte in compressed) | python | def humanize(self, hexdigest, words=4, separator='-'):
# Gets a list of byte values between 0-255.
bytes = [int(x, 16) for x in list(map(''.join, list(zip(hexdigest[::2], hexdigest[1::2]))))]
# Compress an arbitrary number of bytes to `words`.
compressed = self.compress(bytes, words)
# Map the compressed byte values through the word list.
return separator.join(self.wordlist[byte] for byte in compressed) | [
"def",
"humanize",
"(",
"self",
",",
"hexdigest",
",",
"words",
"=",
"4",
",",
"separator",
"=",
"'-'",
")",
":",
"# Gets a list of byte values between 0-255.",
"bytes",
"=",
"[",
"int",
"(",
"x",
",",
"16",
")",
"for",
"x",
"in",
"list",
"(",
"map",
"... | Humanize a given hexadecimal digest.
Change the number of words output by specifying `words`. Change the
word separator with `separator`.
>>> digest = '60ad8d0d871b6095808297'
>>> HumanHasher().humanize(digest)
'sodium-magnesium-nineteen-hydrogen' | [
"Humanize",
"a",
"given",
"hexadecimal",
"digest",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/humanhash.py#L73-L91 |
235,727 | Koed00/django-q | django_q/humanhash.py | HumanHasher.compress | def compress(bytes, target):
"""
Compress a list of byte values to a fixed target length.
>>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151]
>>> HumanHasher.compress(bytes, 4)
[205, 128, 156, 96]
Attempting to compress a smaller number of bytes to a larger number is
an error:
>>> HumanHasher.compress(bytes, 15) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Fewer input bytes than requested output
"""
length = len(bytes)
if target > length:
raise ValueError("Fewer input bytes than requested output")
# Split `bytes` into `target` segments.
seg_size = length // target
segments = [bytes[i * seg_size:(i + 1) * seg_size]
for i in range(target)]
# Catch any left-over bytes in the last segment.
segments[-1].extend(bytes[target * seg_size:])
# Use a simple XOR checksum-like function for compression.
checksum = lambda bytes: reduce(operator.xor, bytes, 0)
checksums = list(map(checksum, segments))
return checksums | python | def compress(bytes, target):
length = len(bytes)
if target > length:
raise ValueError("Fewer input bytes than requested output")
# Split `bytes` into `target` segments.
seg_size = length // target
segments = [bytes[i * seg_size:(i + 1) * seg_size]
for i in range(target)]
# Catch any left-over bytes in the last segment.
segments[-1].extend(bytes[target * seg_size:])
# Use a simple XOR checksum-like function for compression.
checksum = lambda bytes: reduce(operator.xor, bytes, 0)
checksums = list(map(checksum, segments))
return checksums | [
"def",
"compress",
"(",
"bytes",
",",
"target",
")",
":",
"length",
"=",
"len",
"(",
"bytes",
")",
"if",
"target",
">",
"length",
":",
"raise",
"ValueError",
"(",
"\"Fewer input bytes than requested output\"",
")",
"# Split `bytes` into `target` segments.",
"seg_siz... | Compress a list of byte values to a fixed target length.
>>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151]
>>> HumanHasher.compress(bytes, 4)
[205, 128, 156, 96]
Attempting to compress a smaller number of bytes to a larger number is
an error:
>>> HumanHasher.compress(bytes, 15) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Fewer input bytes than requested output | [
"Compress",
"a",
"list",
"of",
"byte",
"values",
"to",
"a",
"fixed",
"target",
"length",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/humanhash.py#L94-L126 |
235,728 | Koed00/django-q | django_q/humanhash.py | HumanHasher.uuid | def uuid(self, **params):
"""
Generate a UUID with a human-readable representation.
Returns `(human_repr, full_digest)`. Accepts the same keyword arguments
as :meth:`humanize` (they'll be passed straight through).
"""
digest = str(uuidlib.uuid4()).replace('-', '')
return self.humanize(digest, **params), digest | python | def uuid(self, **params):
digest = str(uuidlib.uuid4()).replace('-', '')
return self.humanize(digest, **params), digest | [
"def",
"uuid",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"digest",
"=",
"str",
"(",
"uuidlib",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"return",
"self",
".",
"humanize",
"(",
"digest",
",",
"*",
"*",
"para... | Generate a UUID with a human-readable representation.
Returns `(human_repr, full_digest)`. Accepts the same keyword arguments
as :meth:`humanize` (they'll be passed straight through). | [
"Generate",
"a",
"UUID",
"with",
"a",
"human",
"-",
"readable",
"representation",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/humanhash.py#L128-L138 |
235,729 | Koed00/django-q | django_q/tasks.py | async_task | def async_task(func, *args, **kwargs):
"""Queue a task for the cluster."""
keywords = kwargs.copy()
opt_keys = (
'hook', 'group', 'save', 'sync', 'cached', 'ack_failure', 'iter_count', 'iter_cached', 'chain', 'broker')
q_options = keywords.pop('q_options', {})
# get an id
tag = uuid()
# build the task package
task = {'id': tag[1],
'name': keywords.pop('task_name', None) or q_options.pop('task_name', None) or tag[0],
'func': func,
'args': args}
# push optionals
for key in opt_keys:
if q_options and key in q_options:
task[key] = q_options[key]
elif key in keywords:
task[key] = keywords.pop(key)
# don't serialize the broker
broker = task.pop('broker', get_broker())
# overrides
if 'cached' not in task and Conf.CACHED:
task['cached'] = Conf.CACHED
if 'sync' not in task and Conf.SYNC:
task['sync'] = Conf.SYNC
if 'ack_failure' not in task and Conf.ACK_FAILURES:
task['ack_failure'] = Conf.ACK_FAILURES
# finalize
task['kwargs'] = keywords
task['started'] = timezone.now()
# signal it
pre_enqueue.send(sender="django_q", task=task)
# sign it
pack = SignedPackage.dumps(task)
if task.get('sync', False):
return _sync(pack)
# push it
enqueue_id = broker.enqueue(pack)
logger.info('Enqueued {}'.format(enqueue_id))
logger.debug('Pushed {}'.format(tag))
return task['id'] | python | def async_task(func, *args, **kwargs):
keywords = kwargs.copy()
opt_keys = (
'hook', 'group', 'save', 'sync', 'cached', 'ack_failure', 'iter_count', 'iter_cached', 'chain', 'broker')
q_options = keywords.pop('q_options', {})
# get an id
tag = uuid()
# build the task package
task = {'id': tag[1],
'name': keywords.pop('task_name', None) or q_options.pop('task_name', None) or tag[0],
'func': func,
'args': args}
# push optionals
for key in opt_keys:
if q_options and key in q_options:
task[key] = q_options[key]
elif key in keywords:
task[key] = keywords.pop(key)
# don't serialize the broker
broker = task.pop('broker', get_broker())
# overrides
if 'cached' not in task and Conf.CACHED:
task['cached'] = Conf.CACHED
if 'sync' not in task and Conf.SYNC:
task['sync'] = Conf.SYNC
if 'ack_failure' not in task and Conf.ACK_FAILURES:
task['ack_failure'] = Conf.ACK_FAILURES
# finalize
task['kwargs'] = keywords
task['started'] = timezone.now()
# signal it
pre_enqueue.send(sender="django_q", task=task)
# sign it
pack = SignedPackage.dumps(task)
if task.get('sync', False):
return _sync(pack)
# push it
enqueue_id = broker.enqueue(pack)
logger.info('Enqueued {}'.format(enqueue_id))
logger.debug('Pushed {}'.format(tag))
return task['id'] | [
"def",
"async_task",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"keywords",
"=",
"kwargs",
".",
"copy",
"(",
")",
"opt_keys",
"=",
"(",
"'hook'",
",",
"'group'",
",",
"'save'",
",",
"'sync'",
",",
"'cached'",
",",
"'ack_failure... | Queue a task for the cluster. | [
"Queue",
"a",
"task",
"for",
"the",
"cluster",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L21-L62 |
235,730 | Koed00/django-q | django_q/tasks.py | schedule | def schedule(func, *args, **kwargs):
"""
Create a schedule.
:param func: function to schedule.
:param args: function arguments.
:param name: optional name for the schedule.
:param hook: optional result hook function.
:type schedule_type: Schedule.TYPE
:param repeats: how many times to repeat. 0=never, -1=always.
:param next_run: Next scheduled run.
:type next_run: datetime.datetime
:param kwargs: function keyword arguments.
:return: the schedule object.
:rtype: Schedule
"""
name = kwargs.pop('name', None)
hook = kwargs.pop('hook', None)
schedule_type = kwargs.pop('schedule_type', Schedule.ONCE)
minutes = kwargs.pop('minutes', None)
repeats = kwargs.pop('repeats', -1)
next_run = kwargs.pop('next_run', timezone.now())
# check for name duplicates instead of am unique constraint
if name and Schedule.objects.filter(name=name).exists():
raise IntegrityError("A schedule with the same name already exists.")
# create and return the schedule
return Schedule.objects.create(name=name,
func=func,
hook=hook,
args=args,
kwargs=kwargs,
schedule_type=schedule_type,
minutes=minutes,
repeats=repeats,
next_run=next_run
) | python | def schedule(func, *args, **kwargs):
name = kwargs.pop('name', None)
hook = kwargs.pop('hook', None)
schedule_type = kwargs.pop('schedule_type', Schedule.ONCE)
minutes = kwargs.pop('minutes', None)
repeats = kwargs.pop('repeats', -1)
next_run = kwargs.pop('next_run', timezone.now())
# check for name duplicates instead of am unique constraint
if name and Schedule.objects.filter(name=name).exists():
raise IntegrityError("A schedule with the same name already exists.")
# create and return the schedule
return Schedule.objects.create(name=name,
func=func,
hook=hook,
args=args,
kwargs=kwargs,
schedule_type=schedule_type,
minutes=minutes,
repeats=repeats,
next_run=next_run
) | [
"def",
"schedule",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"None",
")",
"hook",
"=",
"kwargs",
".",
"pop",
"(",
"'hook'",
",",
"None",
")",
"schedule_type",
"=",
"kw... | Create a schedule.
:param func: function to schedule.
:param args: function arguments.
:param name: optional name for the schedule.
:param hook: optional result hook function.
:type schedule_type: Schedule.TYPE
:param repeats: how many times to repeat. 0=never, -1=always.
:param next_run: Next scheduled run.
:type next_run: datetime.datetime
:param kwargs: function keyword arguments.
:return: the schedule object.
:rtype: Schedule | [
"Create",
"a",
"schedule",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L65-L102 |
235,731 | Koed00/django-q | django_q/tasks.py | result | def result(task_id, wait=0, cached=Conf.CACHED):
"""
Return the result of the named task.
:type task_id: str or uuid
:param task_id: the task name or uuid
:type wait: int
:param wait: number of milliseconds to wait for a result
:param bool cached: run this against the cache backend
:return: the result object of this task
:rtype: object
"""
if cached:
return result_cached(task_id, wait)
start = time()
while True:
r = Task.get_result(task_id)
if r:
return r
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | python | def result(task_id, wait=0, cached=Conf.CACHED):
if cached:
return result_cached(task_id, wait)
start = time()
while True:
r = Task.get_result(task_id)
if r:
return r
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | [
"def",
"result",
"(",
"task_id",
",",
"wait",
"=",
"0",
",",
"cached",
"=",
"Conf",
".",
"CACHED",
")",
":",
"if",
"cached",
":",
"return",
"result_cached",
"(",
"task_id",
",",
"wait",
")",
"start",
"=",
"time",
"(",
")",
"while",
"True",
":",
"r"... | Return the result of the named task.
:type task_id: str or uuid
:param task_id: the task name or uuid
:type wait: int
:param wait: number of milliseconds to wait for a result
:param bool cached: run this against the cache backend
:return: the result object of this task
:rtype: object | [
"Return",
"the",
"result",
"of",
"the",
"named",
"task",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L105-L126 |
235,732 | Koed00/django-q | django_q/tasks.py | result_cached | def result_cached(task_id, wait=0, broker=None):
"""
Return the result from the cache backend
"""
if not broker:
broker = get_broker()
start = time()
while True:
r = broker.cache.get('{}:{}'.format(broker.list_key, task_id))
if r:
return SignedPackage.loads(r)['result']
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | python | def result_cached(task_id, wait=0, broker=None):
if not broker:
broker = get_broker()
start = time()
while True:
r = broker.cache.get('{}:{}'.format(broker.list_key, task_id))
if r:
return SignedPackage.loads(r)['result']
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | [
"def",
"result_cached",
"(",
"task_id",
",",
"wait",
"=",
"0",
",",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"broker",
":",
"broker",
"=",
"get_broker",
"(",
")",
"start",
"=",
"time",
"(",
")",
"while",
"True",
":",
"r",
"=",
"broker",
".",
... | Return the result from the cache backend | [
"Return",
"the",
"result",
"from",
"the",
"cache",
"backend"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L129-L142 |
235,733 | Koed00/django-q | django_q/tasks.py | result_group | def result_group(group_id, failures=False, wait=0, count=None, cached=Conf.CACHED):
"""
Return a list of results for a task group.
:param str group_id: the group id
:param bool failures: set to True to include failures
:param int count: Block until there are this many results in the group
:param bool cached: run this against the cache backend
:return: list or results
"""
if cached:
return result_group_cached(group_id, failures, wait, count)
start = time()
if count:
while True:
if count_group(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01)
while True:
r = Task.get_result_group(group_id, failures)
if r:
return r
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | python | def result_group(group_id, failures=False, wait=0, count=None, cached=Conf.CACHED):
if cached:
return result_group_cached(group_id, failures, wait, count)
start = time()
if count:
while True:
if count_group(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01)
while True:
r = Task.get_result_group(group_id, failures)
if r:
return r
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | [
"def",
"result_group",
"(",
"group_id",
",",
"failures",
"=",
"False",
",",
"wait",
"=",
"0",
",",
"count",
"=",
"None",
",",
"cached",
"=",
"Conf",
".",
"CACHED",
")",
":",
"if",
"cached",
":",
"return",
"result_group_cached",
"(",
"group_id",
",",
"f... | Return a list of results for a task group.
:param str group_id: the group id
:param bool failures: set to True to include failures
:param int count: Block until there are this many results in the group
:param bool cached: run this against the cache backend
:return: list or results | [
"Return",
"a",
"list",
"of",
"results",
"for",
"a",
"task",
"group",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L145-L169 |
235,734 | Koed00/django-q | django_q/tasks.py | result_group_cached | def result_group_cached(group_id, failures=False, wait=0, count=None, broker=None):
"""
Return a list of results for a task group from the cache backend
"""
if not broker:
broker = get_broker()
start = time()
if count:
while True:
if count_group_cached(group_id) == count or wait and (time() - start) * 1000 >= wait > 0:
break
sleep(0.01)
while True:
group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id))
if group_list:
result_list = []
for task_key in group_list:
task = SignedPackage.loads(broker.cache.get(task_key))
if task['success'] or failures:
result_list.append(task['result'])
return result_list
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | python | def result_group_cached(group_id, failures=False, wait=0, count=None, broker=None):
if not broker:
broker = get_broker()
start = time()
if count:
while True:
if count_group_cached(group_id) == count or wait and (time() - start) * 1000 >= wait > 0:
break
sleep(0.01)
while True:
group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id))
if group_list:
result_list = []
for task_key in group_list:
task = SignedPackage.loads(broker.cache.get(task_key))
if task['success'] or failures:
result_list.append(task['result'])
return result_list
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | [
"def",
"result_group_cached",
"(",
"group_id",
",",
"failures",
"=",
"False",
",",
"wait",
"=",
"0",
",",
"count",
"=",
"None",
",",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"broker",
":",
"broker",
"=",
"get_broker",
"(",
")",
"start",
"=",
"ti... | Return a list of results for a task group from the cache backend | [
"Return",
"a",
"list",
"of",
"results",
"for",
"a",
"task",
"group",
"from",
"the",
"cache",
"backend"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L172-L195 |
235,735 | Koed00/django-q | django_q/tasks.py | fetch | def fetch(task_id, wait=0, cached=Conf.CACHED):
"""
Return the processed task.
:param task_id: the task name or uuid
:type task_id: str or uuid
:param wait: the number of milliseconds to wait for a result
:type wait: int
:param bool cached: run this against the cache backend
:return: the full task object
:rtype: Task
"""
if cached:
return fetch_cached(task_id, wait)
start = time()
while True:
t = Task.get_task(task_id)
if t:
return t
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | python | def fetch(task_id, wait=0, cached=Conf.CACHED):
if cached:
return fetch_cached(task_id, wait)
start = time()
while True:
t = Task.get_task(task_id)
if t:
return t
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | [
"def",
"fetch",
"(",
"task_id",
",",
"wait",
"=",
"0",
",",
"cached",
"=",
"Conf",
".",
"CACHED",
")",
":",
"if",
"cached",
":",
"return",
"fetch_cached",
"(",
"task_id",
",",
"wait",
")",
"start",
"=",
"time",
"(",
")",
"while",
"True",
":",
"t",
... | Return the processed task.
:param task_id: the task name or uuid
:type task_id: str or uuid
:param wait: the number of milliseconds to wait for a result
:type wait: int
:param bool cached: run this against the cache backend
:return: the full task object
:rtype: Task | [
"Return",
"the",
"processed",
"task",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L198-L219 |
235,736 | Koed00/django-q | django_q/tasks.py | fetch_cached | def fetch_cached(task_id, wait=0, broker=None):
"""
Return the processed task from the cache backend
"""
if not broker:
broker = get_broker()
start = time()
while True:
r = broker.cache.get('{}:{}'.format(broker.list_key, task_id))
if r:
task = SignedPackage.loads(r)
t = Task(id=task['id'],
name=task['name'],
func=task['func'],
hook=task.get('hook'),
args=task['args'],
kwargs=task['kwargs'],
started=task['started'],
stopped=task['stopped'],
result=task['result'],
success=task['success'])
return t
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | python | def fetch_cached(task_id, wait=0, broker=None):
if not broker:
broker = get_broker()
start = time()
while True:
r = broker.cache.get('{}:{}'.format(broker.list_key, task_id))
if r:
task = SignedPackage.loads(r)
t = Task(id=task['id'],
name=task['name'],
func=task['func'],
hook=task.get('hook'),
args=task['args'],
kwargs=task['kwargs'],
started=task['started'],
stopped=task['stopped'],
result=task['result'],
success=task['success'])
return t
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | [
"def",
"fetch_cached",
"(",
"task_id",
",",
"wait",
"=",
"0",
",",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"broker",
":",
"broker",
"=",
"get_broker",
"(",
")",
"start",
"=",
"time",
"(",
")",
"while",
"True",
":",
"r",
"=",
"broker",
".",
... | Return the processed task from the cache backend | [
"Return",
"the",
"processed",
"task",
"from",
"the",
"cache",
"backend"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L222-L246 |
235,737 | Koed00/django-q | django_q/tasks.py | fetch_group | def fetch_group(group_id, failures=True, wait=0, count=None, cached=Conf.CACHED):
"""
Return a list of Tasks for a task group.
:param str group_id: the group id
:param bool failures: set to False to exclude failures
:param bool cached: run this against the cache backend
:return: list of Tasks
"""
if cached:
return fetch_group_cached(group_id, failures, wait, count)
start = time()
if count:
while True:
if count_group(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01)
while True:
r = Task.get_task_group(group_id, failures)
if r:
return r
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | python | def fetch_group(group_id, failures=True, wait=0, count=None, cached=Conf.CACHED):
if cached:
return fetch_group_cached(group_id, failures, wait, count)
start = time()
if count:
while True:
if count_group(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01)
while True:
r = Task.get_task_group(group_id, failures)
if r:
return r
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | [
"def",
"fetch_group",
"(",
"group_id",
",",
"failures",
"=",
"True",
",",
"wait",
"=",
"0",
",",
"count",
"=",
"None",
",",
"cached",
"=",
"Conf",
".",
"CACHED",
")",
":",
"if",
"cached",
":",
"return",
"fetch_group_cached",
"(",
"group_id",
",",
"fail... | Return a list of Tasks for a task group.
:param str group_id: the group id
:param bool failures: set to False to exclude failures
:param bool cached: run this against the cache backend
:return: list of Tasks | [
"Return",
"a",
"list",
"of",
"Tasks",
"for",
"a",
"task",
"group",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L249-L272 |
235,738 | Koed00/django-q | django_q/tasks.py | fetch_group_cached | def fetch_group_cached(group_id, failures=True, wait=0, count=None, broker=None):
"""
Return a list of Tasks for a task group in the cache backend
"""
if not broker:
broker = get_broker()
start = time()
if count:
while True:
if count_group_cached(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01)
while True:
group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id))
if group_list:
task_list = []
for task_key in group_list:
task = SignedPackage.loads(broker.cache.get(task_key))
if task['success'] or failures:
t = Task(id=task['id'],
name=task['name'],
func=task['func'],
hook=task.get('hook'),
args=task['args'],
kwargs=task['kwargs'],
started=task['started'],
stopped=task['stopped'],
result=task['result'],
group=task.get('group'),
success=task['success'])
task_list.append(t)
return task_list
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | python | def fetch_group_cached(group_id, failures=True, wait=0, count=None, broker=None):
if not broker:
broker = get_broker()
start = time()
if count:
while True:
if count_group_cached(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01)
while True:
group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id))
if group_list:
task_list = []
for task_key in group_list:
task = SignedPackage.loads(broker.cache.get(task_key))
if task['success'] or failures:
t = Task(id=task['id'],
name=task['name'],
func=task['func'],
hook=task.get('hook'),
args=task['args'],
kwargs=task['kwargs'],
started=task['started'],
stopped=task['stopped'],
result=task['result'],
group=task.get('group'),
success=task['success'])
task_list.append(t)
return task_list
if (time() - start) * 1000 >= wait >= 0:
break
sleep(0.01) | [
"def",
"fetch_group_cached",
"(",
"group_id",
",",
"failures",
"=",
"True",
",",
"wait",
"=",
"0",
",",
"count",
"=",
"None",
",",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"broker",
":",
"broker",
"=",
"get_broker",
"(",
")",
"start",
"=",
"time... | Return a list of Tasks for a task group in the cache backend | [
"Return",
"a",
"list",
"of",
"Tasks",
"for",
"a",
"task",
"group",
"in",
"the",
"cache",
"backend"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L275-L309 |
235,739 | Koed00/django-q | django_q/tasks.py | count_group | def count_group(group_id, failures=False, cached=Conf.CACHED):
"""
Count the results in a group.
:param str group_id: the group id
:param bool failures: Returns failure count if True
:param bool cached: run this against the cache backend
:return: the number of tasks/results in a group
:rtype: int
"""
if cached:
return count_group_cached(group_id, failures)
return Task.get_group_count(group_id, failures) | python | def count_group(group_id, failures=False, cached=Conf.CACHED):
if cached:
return count_group_cached(group_id, failures)
return Task.get_group_count(group_id, failures) | [
"def",
"count_group",
"(",
"group_id",
",",
"failures",
"=",
"False",
",",
"cached",
"=",
"Conf",
".",
"CACHED",
")",
":",
"if",
"cached",
":",
"return",
"count_group_cached",
"(",
"group_id",
",",
"failures",
")",
"return",
"Task",
".",
"get_group_count",
... | Count the results in a group.
:param str group_id: the group id
:param bool failures: Returns failure count if True
:param bool cached: run this against the cache backend
:return: the number of tasks/results in a group
:rtype: int | [
"Count",
"the",
"results",
"in",
"a",
"group",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L312-L324 |
235,740 | Koed00/django-q | django_q/tasks.py | count_group_cached | def count_group_cached(group_id, failures=False, broker=None):
"""
Count the results in a group in the cache backend
"""
if not broker:
broker = get_broker()
group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id))
if group_list:
if not failures:
return len(group_list)
failure_count = 0
for task_key in group_list:
task = SignedPackage.loads(broker.cache.get(task_key))
if not task['success']:
failure_count += 1
return failure_count | python | def count_group_cached(group_id, failures=False, broker=None):
if not broker:
broker = get_broker()
group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id))
if group_list:
if not failures:
return len(group_list)
failure_count = 0
for task_key in group_list:
task = SignedPackage.loads(broker.cache.get(task_key))
if not task['success']:
failure_count += 1
return failure_count | [
"def",
"count_group_cached",
"(",
"group_id",
",",
"failures",
"=",
"False",
",",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"broker",
":",
"broker",
"=",
"get_broker",
"(",
")",
"group_list",
"=",
"broker",
".",
"cache",
".",
"get",
"(",
"'{}:{}:keys... | Count the results in a group in the cache backend | [
"Count",
"the",
"results",
"in",
"a",
"group",
"in",
"the",
"cache",
"backend"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L327-L342 |
235,741 | Koed00/django-q | django_q/tasks.py | delete_group_cached | def delete_group_cached(group_id, broker=None):
"""
Delete a group from the cache backend
"""
if not broker:
broker = get_broker()
group_key = '{}:{}:keys'.format(broker.list_key, group_id)
group_list = broker.cache.get(group_key)
broker.cache.delete_many(group_list)
broker.cache.delete(group_key) | python | def delete_group_cached(group_id, broker=None):
if not broker:
broker = get_broker()
group_key = '{}:{}:keys'.format(broker.list_key, group_id)
group_list = broker.cache.get(group_key)
broker.cache.delete_many(group_list)
broker.cache.delete(group_key) | [
"def",
"delete_group_cached",
"(",
"group_id",
",",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"broker",
":",
"broker",
"=",
"get_broker",
"(",
")",
"group_key",
"=",
"'{}:{}:keys'",
".",
"format",
"(",
"broker",
".",
"list_key",
",",
"group_id",
")",
... | Delete a group from the cache backend | [
"Delete",
"a",
"group",
"from",
"the",
"cache",
"backend"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L360-L369 |
235,742 | Koed00/django-q | django_q/tasks.py | delete_cached | def delete_cached(task_id, broker=None):
"""
Delete a task from the cache backend
"""
if not broker:
broker = get_broker()
return broker.cache.delete('{}:{}'.format(broker.list_key, task_id)) | python | def delete_cached(task_id, broker=None):
if not broker:
broker = get_broker()
return broker.cache.delete('{}:{}'.format(broker.list_key, task_id)) | [
"def",
"delete_cached",
"(",
"task_id",
",",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"broker",
":",
"broker",
"=",
"get_broker",
"(",
")",
"return",
"broker",
".",
"cache",
".",
"delete",
"(",
"'{}:{}'",
".",
"format",
"(",
"broker",
".",
"list_k... | Delete a task from the cache backend | [
"Delete",
"a",
"task",
"from",
"the",
"cache",
"backend"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L372-L378 |
235,743 | Koed00/django-q | django_q/tasks.py | async_iter | def async_iter(func, args_iter, **kwargs):
"""
enqueues a function with iterable arguments
"""
iter_count = len(args_iter)
iter_group = uuid()[1]
# clean up the kwargs
options = kwargs.get('q_options', kwargs)
options.pop('hook', None)
options['broker'] = options.get('broker', get_broker())
options['group'] = iter_group
options['iter_count'] = iter_count
if options.get('cached', None):
options['iter_cached'] = options['cached']
options['cached'] = True
# save the original arguments
broker = options['broker']
broker.cache.set('{}:{}:args'.format(broker.list_key, iter_group), SignedPackage.dumps(args_iter))
for args in args_iter:
if not isinstance(args, tuple):
args = (args,)
async_task(func, *args, **options)
return iter_group | python | def async_iter(func, args_iter, **kwargs):
iter_count = len(args_iter)
iter_group = uuid()[1]
# clean up the kwargs
options = kwargs.get('q_options', kwargs)
options.pop('hook', None)
options['broker'] = options.get('broker', get_broker())
options['group'] = iter_group
options['iter_count'] = iter_count
if options.get('cached', None):
options['iter_cached'] = options['cached']
options['cached'] = True
# save the original arguments
broker = options['broker']
broker.cache.set('{}:{}:args'.format(broker.list_key, iter_group), SignedPackage.dumps(args_iter))
for args in args_iter:
if not isinstance(args, tuple):
args = (args,)
async_task(func, *args, **options)
return iter_group | [
"def",
"async_iter",
"(",
"func",
",",
"args_iter",
",",
"*",
"*",
"kwargs",
")",
":",
"iter_count",
"=",
"len",
"(",
"args_iter",
")",
"iter_group",
"=",
"uuid",
"(",
")",
"[",
"1",
"]",
"# clean up the kwargs",
"options",
"=",
"kwargs",
".",
"get",
"... | enqueues a function with iterable arguments | [
"enqueues",
"a",
"function",
"with",
"iterable",
"arguments"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L395-L417 |
235,744 | Koed00/django-q | django_q/tasks.py | _sync | def _sync(pack):
"""Simulate a package travelling through the cluster."""
task_queue = Queue()
result_queue = Queue()
task = SignedPackage.loads(pack)
task_queue.put(task)
task_queue.put('STOP')
worker(task_queue, result_queue, Value('f', -1))
result_queue.put('STOP')
monitor(result_queue)
task_queue.close()
task_queue.join_thread()
result_queue.close()
result_queue.join_thread()
return task['id'] | python | def _sync(pack):
task_queue = Queue()
result_queue = Queue()
task = SignedPackage.loads(pack)
task_queue.put(task)
task_queue.put('STOP')
worker(task_queue, result_queue, Value('f', -1))
result_queue.put('STOP')
monitor(result_queue)
task_queue.close()
task_queue.join_thread()
result_queue.close()
result_queue.join_thread()
return task['id'] | [
"def",
"_sync",
"(",
"pack",
")",
":",
"task_queue",
"=",
"Queue",
"(",
")",
"result_queue",
"=",
"Queue",
"(",
")",
"task",
"=",
"SignedPackage",
".",
"loads",
"(",
"pack",
")",
"task_queue",
".",
"put",
"(",
"task",
")",
"task_queue",
".",
"put",
"... | Simulate a package travelling through the cluster. | [
"Simulate",
"a",
"package",
"travelling",
"through",
"the",
"cluster",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L677-L691 |
235,745 | Koed00/django-q | django_q/tasks.py | Iter.append | def append(self, *args):
"""
add arguments to the set
"""
self.args.append(args)
if self.started:
self.started = False
return self.length() | python | def append(self, *args):
self.args.append(args)
if self.started:
self.started = False
return self.length() | [
"def",
"append",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"args",
".",
"append",
"(",
"args",
")",
"if",
"self",
".",
"started",
":",
"self",
".",
"started",
"=",
"False",
"return",
"self",
".",
"length",
"(",
")"
] | add arguments to the set | [
"add",
"arguments",
"to",
"the",
"set"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L460-L467 |
235,746 | Koed00/django-q | django_q/admin.py | retry_failed | def retry_failed(FailAdmin, request, queryset):
"""Submit selected tasks back to the queue."""
for task in queryset:
async_task(task.func, *task.args or (), hook=task.hook, **task.kwargs or {})
task.delete() | python | def retry_failed(FailAdmin, request, queryset):
for task in queryset:
async_task(task.func, *task.args or (), hook=task.hook, **task.kwargs or {})
task.delete() | [
"def",
"retry_failed",
"(",
"FailAdmin",
",",
"request",
",",
"queryset",
")",
":",
"for",
"task",
"in",
"queryset",
":",
"async_task",
"(",
"task",
".",
"func",
",",
"*",
"task",
".",
"args",
"or",
"(",
")",
",",
"hook",
"=",
"task",
".",
"hook",
... | Submit selected tasks back to the queue. | [
"Submit",
"selected",
"tasks",
"back",
"to",
"the",
"queue",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/admin.py#L40-L44 |
235,747 | Koed00/django-q | django_q/admin.py | TaskAdmin.get_queryset | def get_queryset(self, request):
"""Only show successes."""
qs = super(TaskAdmin, self).get_queryset(request)
return qs.filter(success=True) | python | def get_queryset(self, request):
qs = super(TaskAdmin, self).get_queryset(request)
return qs.filter(success=True) | [
"def",
"get_queryset",
"(",
"self",
",",
"request",
")",
":",
"qs",
"=",
"super",
"(",
"TaskAdmin",
",",
"self",
")",
".",
"get_queryset",
"(",
"request",
")",
"return",
"qs",
".",
"filter",
"(",
"success",
"=",
"True",
")"
] | Only show successes. | [
"Only",
"show",
"successes",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/admin.py#L26-L29 |
235,748 | Koed00/django-q | django_q/admin.py | TaskAdmin.get_readonly_fields | def get_readonly_fields(self, request, obj=None):
"""Set all fields readonly."""
return list(self.readonly_fields) + [field.name for field in obj._meta.fields] | python | def get_readonly_fields(self, request, obj=None):
return list(self.readonly_fields) + [field.name for field in obj._meta.fields] | [
"def",
"get_readonly_fields",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"return",
"list",
"(",
"self",
".",
"readonly_fields",
")",
"+",
"[",
"field",
".",
"name",
"for",
"field",
"in",
"obj",
".",
"_meta",
".",
"fields",
"]"
] | Set all fields readonly. | [
"Set",
"all",
"fields",
"readonly",
"."
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/admin.py#L35-L37 |
235,749 | Koed00/django-q | django_q/cluster.py | save_task | def save_task(task, broker):
"""
Saves the task package to Django or the cache
"""
# SAVE LIMIT < 0 : Don't save success
if not task.get('save', Conf.SAVE_LIMIT >= 0) and task['success']:
return
# enqueues next in a chain
if task.get('chain', None):
django_q.tasks.async_chain(task['chain'], group=task['group'], cached=task['cached'], sync=task['sync'], broker=broker)
# SAVE LIMIT > 0: Prune database, SAVE_LIMIT 0: No pruning
db.close_old_connections()
try:
if task['success'] and 0 < Conf.SAVE_LIMIT <= Success.objects.count():
Success.objects.last().delete()
# check if this task has previous results
if Task.objects.filter(id=task['id'], name=task['name']).exists():
existing_task = Task.objects.get(id=task['id'], name=task['name'])
# only update the result if it hasn't succeeded yet
if not existing_task.success:
existing_task.stopped = task['stopped']
existing_task.result = task['result']
existing_task.success = task['success']
existing_task.save()
else:
Task.objects.create(id=task['id'],
name=task['name'],
func=task['func'],
hook=task.get('hook'),
args=task['args'],
kwargs=task['kwargs'],
started=task['started'],
stopped=task['stopped'],
result=task['result'],
group=task.get('group'),
success=task['success']
)
except Exception as e:
logger.error(e) | python | def save_task(task, broker):
# SAVE LIMIT < 0 : Don't save success
if not task.get('save', Conf.SAVE_LIMIT >= 0) and task['success']:
return
# enqueues next in a chain
if task.get('chain', None):
django_q.tasks.async_chain(task['chain'], group=task['group'], cached=task['cached'], sync=task['sync'], broker=broker)
# SAVE LIMIT > 0: Prune database, SAVE_LIMIT 0: No pruning
db.close_old_connections()
try:
if task['success'] and 0 < Conf.SAVE_LIMIT <= Success.objects.count():
Success.objects.last().delete()
# check if this task has previous results
if Task.objects.filter(id=task['id'], name=task['name']).exists():
existing_task = Task.objects.get(id=task['id'], name=task['name'])
# only update the result if it hasn't succeeded yet
if not existing_task.success:
existing_task.stopped = task['stopped']
existing_task.result = task['result']
existing_task.success = task['success']
existing_task.save()
else:
Task.objects.create(id=task['id'],
name=task['name'],
func=task['func'],
hook=task.get('hook'),
args=task['args'],
kwargs=task['kwargs'],
started=task['started'],
stopped=task['stopped'],
result=task['result'],
group=task.get('group'),
success=task['success']
)
except Exception as e:
logger.error(e) | [
"def",
"save_task",
"(",
"task",
",",
"broker",
")",
":",
"# SAVE LIMIT < 0 : Don't save success",
"if",
"not",
"task",
".",
"get",
"(",
"'save'",
",",
"Conf",
".",
"SAVE_LIMIT",
">=",
"0",
")",
"and",
"task",
"[",
"'success'",
"]",
":",
"return",
"# enque... | Saves the task package to Django or the cache | [
"Saves",
"the",
"task",
"package",
"to",
"Django",
"or",
"the",
"cache"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/cluster.py#L400-L438 |
235,750 | Koed00/django-q | django_q/cluster.py | scheduler | def scheduler(broker=None):
"""
Creates a task from a schedule at the scheduled time and schedules next run
"""
if not broker:
broker = get_broker()
db.close_old_connections()
try:
for s in Schedule.objects.exclude(repeats=0).filter(next_run__lt=timezone.now()):
args = ()
kwargs = {}
# get args, kwargs and hook
if s.kwargs:
try:
# eval should be safe here because dict()
kwargs = eval('dict({})'.format(s.kwargs))
except SyntaxError:
kwargs = {}
if s.args:
args = ast.literal_eval(s.args)
# single value won't eval to tuple, so:
if type(args) != tuple:
args = (args,)
q_options = kwargs.get('q_options', {})
if s.hook:
q_options['hook'] = s.hook
# set up the next run time
if not s.schedule_type == s.ONCE:
next_run = arrow.get(s.next_run)
while True:
if s.schedule_type == s.MINUTES:
next_run = next_run.replace(minutes=+(s.minutes or 1))
elif s.schedule_type == s.HOURLY:
next_run = next_run.replace(hours=+1)
elif s.schedule_type == s.DAILY:
next_run = next_run.replace(days=+1)
elif s.schedule_type == s.WEEKLY:
next_run = next_run.replace(weeks=+1)
elif s.schedule_type == s.MONTHLY:
next_run = next_run.replace(months=+1)
elif s.schedule_type == s.QUARTERLY:
next_run = next_run.replace(months=+3)
elif s.schedule_type == s.YEARLY:
next_run = next_run.replace(years=+1)
if Conf.CATCH_UP or next_run > arrow.utcnow():
break
s.next_run = next_run.datetime
s.repeats += -1
# send it to the cluster
q_options['broker'] = broker
q_options['group'] = q_options.get('group', s.name or s.id)
kwargs['q_options'] = q_options
s.task = django_q.tasks.async_task(s.func, *args, **kwargs)
# log it
if not s.task:
logger.error(
_('{} failed to create a task from schedule [{}]').format(current_process().name,
s.name or s.id))
else:
logger.info(
_('{} created a task from schedule [{}]').format(current_process().name, s.name or s.id))
# default behavior is to delete a ONCE schedule
if s.schedule_type == s.ONCE:
if s.repeats < 0:
s.delete()
continue
# but not if it has a positive repeats
s.repeats = 0
# save the schedule
s.save()
except Exception as e:
logger.error(e) | python | def scheduler(broker=None):
if not broker:
broker = get_broker()
db.close_old_connections()
try:
for s in Schedule.objects.exclude(repeats=0).filter(next_run__lt=timezone.now()):
args = ()
kwargs = {}
# get args, kwargs and hook
if s.kwargs:
try:
# eval should be safe here because dict()
kwargs = eval('dict({})'.format(s.kwargs))
except SyntaxError:
kwargs = {}
if s.args:
args = ast.literal_eval(s.args)
# single value won't eval to tuple, so:
if type(args) != tuple:
args = (args,)
q_options = kwargs.get('q_options', {})
if s.hook:
q_options['hook'] = s.hook
# set up the next run time
if not s.schedule_type == s.ONCE:
next_run = arrow.get(s.next_run)
while True:
if s.schedule_type == s.MINUTES:
next_run = next_run.replace(minutes=+(s.minutes or 1))
elif s.schedule_type == s.HOURLY:
next_run = next_run.replace(hours=+1)
elif s.schedule_type == s.DAILY:
next_run = next_run.replace(days=+1)
elif s.schedule_type == s.WEEKLY:
next_run = next_run.replace(weeks=+1)
elif s.schedule_type == s.MONTHLY:
next_run = next_run.replace(months=+1)
elif s.schedule_type == s.QUARTERLY:
next_run = next_run.replace(months=+3)
elif s.schedule_type == s.YEARLY:
next_run = next_run.replace(years=+1)
if Conf.CATCH_UP or next_run > arrow.utcnow():
break
s.next_run = next_run.datetime
s.repeats += -1
# send it to the cluster
q_options['broker'] = broker
q_options['group'] = q_options.get('group', s.name or s.id)
kwargs['q_options'] = q_options
s.task = django_q.tasks.async_task(s.func, *args, **kwargs)
# log it
if not s.task:
logger.error(
_('{} failed to create a task from schedule [{}]').format(current_process().name,
s.name or s.id))
else:
logger.info(
_('{} created a task from schedule [{}]').format(current_process().name, s.name or s.id))
# default behavior is to delete a ONCE schedule
if s.schedule_type == s.ONCE:
if s.repeats < 0:
s.delete()
continue
# but not if it has a positive repeats
s.repeats = 0
# save the schedule
s.save()
except Exception as e:
logger.error(e) | [
"def",
"scheduler",
"(",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"broker",
":",
"broker",
"=",
"get_broker",
"(",
")",
"db",
".",
"close_old_connections",
"(",
")",
"try",
":",
"for",
"s",
"in",
"Schedule",
".",
"objects",
".",
"exclude",
"(",
... | Creates a task from a schedule at the scheduled time and schedules next run | [
"Creates",
"a",
"task",
"from",
"a",
"schedule",
"at",
"the",
"scheduled",
"time",
"and",
"schedules",
"next",
"run"
] | c84fd11a67c9a47d821786dfcdc189bb258c6f54 | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/cluster.py#L486-L557 |
235,751 | google/python-adb | adb/adb_commands.py | AdbCommands._get_service_connection | def _get_service_connection(self, service, service_command=None, create=True, timeout_ms=None):
"""
Based on the service, get the AdbConnection for that service or create one if it doesnt exist
:param service:
:param service_command: Additional service parameters to append
:param create: If False, dont create a connection if it does not exist
:return:
"""
connection = self._service_connections.get(service, None)
if connection:
return connection
if not connection and not create:
return None
if service_command:
destination_str = b'%s:%s' % (service, service_command)
else:
destination_str = service
connection = self.protocol_handler.Open(
self._handle, destination=destination_str, timeout_ms=timeout_ms)
self._service_connections.update({service: connection})
return connection | python | def _get_service_connection(self, service, service_command=None, create=True, timeout_ms=None):
connection = self._service_connections.get(service, None)
if connection:
return connection
if not connection and not create:
return None
if service_command:
destination_str = b'%s:%s' % (service, service_command)
else:
destination_str = service
connection = self.protocol_handler.Open(
self._handle, destination=destination_str, timeout_ms=timeout_ms)
self._service_connections.update({service: connection})
return connection | [
"def",
"_get_service_connection",
"(",
"self",
",",
"service",
",",
"service_command",
"=",
"None",
",",
"create",
"=",
"True",
",",
"timeout_ms",
"=",
"None",
")",
":",
"connection",
"=",
"self",
".",
"_service_connections",
".",
"get",
"(",
"service",
",",... | Based on the service, get the AdbConnection for that service or create one if it doesnt exist
:param service:
:param service_command: Additional service parameters to append
:param create: If False, dont create a connection if it does not exist
:return: | [
"Based",
"on",
"the",
"service",
"get",
"the",
"AdbConnection",
"for",
"that",
"service",
"or",
"create",
"one",
"if",
"it",
"doesnt",
"exist"
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L71-L99 |
235,752 | google/python-adb | adb/adb_commands.py | AdbCommands.ConnectDevice | def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, **kwargs):
"""Convenience function to setup a transport handle for the adb device from
usb path or serial then connect to it.
Args:
port_path: The filename of usb port to use.
serial: The serial number of the device to use.
default_timeout_ms: The default timeout in milliseconds to use.
kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle)
banner: Connection banner to pass to the remote device
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
If serial specifies a TCP address:port, then a TCP connection is
used instead of a USB connection.
"""
# If there isnt a handle override (used by tests), build one here
if 'handle' in kwargs:
self._handle = kwargs.pop('handle')
else:
# if necessary, convert serial to a unicode string
if isinstance(serial, (bytes, bytearray)):
serial = serial.decode('utf-8')
if serial and ':' in serial:
self._handle = common.TcpHandle(serial, timeout_ms=default_timeout_ms)
else:
self._handle = common.UsbHandle.FindAndOpen(
DeviceIsAvailable, port_path=port_path, serial=serial,
timeout_ms=default_timeout_ms)
self._Connect(**kwargs)
return self | python | def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, **kwargs):
# If there isnt a handle override (used by tests), build one here
if 'handle' in kwargs:
self._handle = kwargs.pop('handle')
else:
# if necessary, convert serial to a unicode string
if isinstance(serial, (bytes, bytearray)):
serial = serial.decode('utf-8')
if serial and ':' in serial:
self._handle = common.TcpHandle(serial, timeout_ms=default_timeout_ms)
else:
self._handle = common.UsbHandle.FindAndOpen(
DeviceIsAvailable, port_path=port_path, serial=serial,
timeout_ms=default_timeout_ms)
self._Connect(**kwargs)
return self | [
"def",
"ConnectDevice",
"(",
"self",
",",
"port_path",
"=",
"None",
",",
"serial",
"=",
"None",
",",
"default_timeout_ms",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# If there isnt a handle override (used by tests), build one here",
"if",
"'handle'",
"in",
... | Convenience function to setup a transport handle for the adb device from
usb path or serial then connect to it.
Args:
port_path: The filename of usb port to use.
serial: The serial number of the device to use.
default_timeout_ms: The default timeout in milliseconds to use.
kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle)
banner: Connection banner to pass to the remote device
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
If serial specifies a TCP address:port, then a TCP connection is
used instead of a USB connection. | [
"Convenience",
"function",
"to",
"setup",
"a",
"transport",
"handle",
"for",
"the",
"adb",
"device",
"from",
"usb",
"path",
"or",
"serial",
"then",
"connect",
"to",
"it",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L101-L144 |
235,753 | google/python-adb | adb/adb_commands.py | AdbCommands.Install | def Install(self, apk_path, destination_dir='', replace_existing=True,
grant_permissions=False, timeout_ms=None, transfer_progress_callback=None):
"""Install an apk to the device.
Doesn't support verifier file, instead allows destination directory to be
overridden.
Args:
apk_path: Local path to apk to install.
destination_dir: Optional destination directory. Use /system/app/ for
persistent applications.
replace_existing: whether to replace existing application
grant_permissions: If True, grant all permissions to the app specified in its manifest
timeout_ms: Expected timeout for pushing and installing.
transfer_progress_callback: callback method that accepts filename, bytes_written and total_bytes of APK transfer
Returns:
The pm install output.
"""
if not destination_dir:
destination_dir = '/data/local/tmp/'
basename = os.path.basename(apk_path)
destination_path = posixpath.join(destination_dir, basename)
self.Push(apk_path, destination_path, timeout_ms=timeout_ms, progress_callback=transfer_progress_callback)
cmd = ['pm install']
if grant_permissions:
cmd.append('-g')
if replace_existing:
cmd.append('-r')
cmd.append('"{}"'.format(destination_path))
ret = self.Shell(' '.join(cmd), timeout_ms=timeout_ms)
# Remove the apk
rm_cmd = ['rm', destination_path]
rmret = self.Shell(' '.join(rm_cmd), timeout_ms=timeout_ms)
return ret | python | def Install(self, apk_path, destination_dir='', replace_existing=True,
grant_permissions=False, timeout_ms=None, transfer_progress_callback=None):
if not destination_dir:
destination_dir = '/data/local/tmp/'
basename = os.path.basename(apk_path)
destination_path = posixpath.join(destination_dir, basename)
self.Push(apk_path, destination_path, timeout_ms=timeout_ms, progress_callback=transfer_progress_callback)
cmd = ['pm install']
if grant_permissions:
cmd.append('-g')
if replace_existing:
cmd.append('-r')
cmd.append('"{}"'.format(destination_path))
ret = self.Shell(' '.join(cmd), timeout_ms=timeout_ms)
# Remove the apk
rm_cmd = ['rm', destination_path]
rmret = self.Shell(' '.join(rm_cmd), timeout_ms=timeout_ms)
return ret | [
"def",
"Install",
"(",
"self",
",",
"apk_path",
",",
"destination_dir",
"=",
"''",
",",
"replace_existing",
"=",
"True",
",",
"grant_permissions",
"=",
"False",
",",
"timeout_ms",
"=",
"None",
",",
"transfer_progress_callback",
"=",
"None",
")",
":",
"if",
"... | Install an apk to the device.
Doesn't support verifier file, instead allows destination directory to be
overridden.
Args:
apk_path: Local path to apk to install.
destination_dir: Optional destination directory. Use /system/app/ for
persistent applications.
replace_existing: whether to replace existing application
grant_permissions: If True, grant all permissions to the app specified in its manifest
timeout_ms: Expected timeout for pushing and installing.
transfer_progress_callback: callback method that accepts filename, bytes_written and total_bytes of APK transfer
Returns:
The pm install output. | [
"Install",
"an",
"apk",
"to",
"the",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L192-L230 |
235,754 | google/python-adb | adb/adb_commands.py | AdbCommands.Uninstall | def Uninstall(self, package_name, keep_data=False, timeout_ms=None):
"""Removes a package from the device.
Args:
package_name: Package name of target package.
keep_data: whether to keep the data and cache directories
timeout_ms: Expected timeout for pushing and installing.
Returns:
The pm uninstall output.
"""
cmd = ['pm uninstall']
if keep_data:
cmd.append('-k')
cmd.append('"%s"' % package_name)
return self.Shell(' '.join(cmd), timeout_ms=timeout_ms) | python | def Uninstall(self, package_name, keep_data=False, timeout_ms=None):
cmd = ['pm uninstall']
if keep_data:
cmd.append('-k')
cmd.append('"%s"' % package_name)
return self.Shell(' '.join(cmd), timeout_ms=timeout_ms) | [
"def",
"Uninstall",
"(",
"self",
",",
"package_name",
",",
"keep_data",
"=",
"False",
",",
"timeout_ms",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'pm uninstall'",
"]",
"if",
"keep_data",
":",
"cmd",
".",
"append",
"(",
"'-k'",
")",
"cmd",
".",
"append"... | Removes a package from the device.
Args:
package_name: Package name of target package.
keep_data: whether to keep the data and cache directories
timeout_ms: Expected timeout for pushing and installing.
Returns:
The pm uninstall output. | [
"Removes",
"a",
"package",
"from",
"the",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L232-L248 |
235,755 | google/python-adb | adb/adb_commands.py | AdbCommands.Push | def Push(self, source_file, device_filename, mtime='0', timeout_ms=None, progress_callback=None, st_mode=None):
"""Push a file or directory to the device.
Args:
source_file: Either a filename, a directory or file-like object to push to
the device.
device_filename: Destination on the device to write to.
mtime: Optional, modification time to set on the file.
timeout_ms: Expected timeout for any part of the push.
st_mode: stat mode for filename
progress_callback: callback method that accepts filename, bytes_written and total_bytes,
total_bytes will be -1 for file-like objects
"""
if isinstance(source_file, str):
if os.path.isdir(source_file):
self.Shell("mkdir " + device_filename)
for f in os.listdir(source_file):
self.Push(os.path.join(source_file, f), device_filename + '/' + f,
progress_callback=progress_callback)
return
source_file = open(source_file, "rb")
with source_file:
connection = self.protocol_handler.Open(
self._handle, destination=b'sync:', timeout_ms=timeout_ms)
kwargs={}
if st_mode is not None:
kwargs['st_mode'] = st_mode
self.filesync_handler.Push(connection, source_file, device_filename,
mtime=int(mtime), progress_callback=progress_callback, **kwargs)
connection.Close() | python | def Push(self, source_file, device_filename, mtime='0', timeout_ms=None, progress_callback=None, st_mode=None):
if isinstance(source_file, str):
if os.path.isdir(source_file):
self.Shell("mkdir " + device_filename)
for f in os.listdir(source_file):
self.Push(os.path.join(source_file, f), device_filename + '/' + f,
progress_callback=progress_callback)
return
source_file = open(source_file, "rb")
with source_file:
connection = self.protocol_handler.Open(
self._handle, destination=b'sync:', timeout_ms=timeout_ms)
kwargs={}
if st_mode is not None:
kwargs['st_mode'] = st_mode
self.filesync_handler.Push(connection, source_file, device_filename,
mtime=int(mtime), progress_callback=progress_callback, **kwargs)
connection.Close() | [
"def",
"Push",
"(",
"self",
",",
"source_file",
",",
"device_filename",
",",
"mtime",
"=",
"'0'",
",",
"timeout_ms",
"=",
"None",
",",
"progress_callback",
"=",
"None",
",",
"st_mode",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"source_file",
",",
"... | Push a file or directory to the device.
Args:
source_file: Either a filename, a directory or file-like object to push to
the device.
device_filename: Destination on the device to write to.
mtime: Optional, modification time to set on the file.
timeout_ms: Expected timeout for any part of the push.
st_mode: stat mode for filename
progress_callback: callback method that accepts filename, bytes_written and total_bytes,
total_bytes will be -1 for file-like objects | [
"Push",
"a",
"file",
"or",
"directory",
"to",
"the",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L250-L281 |
235,756 | google/python-adb | adb/adb_commands.py | AdbCommands.Pull | def Pull(self, device_filename, dest_file=None, timeout_ms=None, progress_callback=None):
"""Pull a file from the device.
Args:
device_filename: Filename on the device to pull.
dest_file: If set, a filename or writable file-like object.
timeout_ms: Expected timeout for any part of the pull.
progress_callback: callback method that accepts filename, bytes_written and total_bytes,
total_bytes will be -1 for file-like objects
Returns:
The file data if dest_file is not set. Otherwise, True if the destination file exists
"""
if not dest_file:
dest_file = io.BytesIO()
elif isinstance(dest_file, str):
dest_file = open(dest_file, 'wb')
elif isinstance(dest_file, file):
pass
else:
raise ValueError("destfile is of unknown type")
conn = self.protocol_handler.Open(
self._handle, destination=b'sync:', timeout_ms=timeout_ms)
self.filesync_handler.Pull(conn, device_filename, dest_file, progress_callback)
conn.Close()
if isinstance(dest_file, io.BytesIO):
return dest_file.getvalue()
else:
dest_file.close()
if hasattr(dest_file, 'name'):
return os.path.exists(dest_file.name)
# We don't know what the path is, so we just assume it exists.
return True | python | def Pull(self, device_filename, dest_file=None, timeout_ms=None, progress_callback=None):
if not dest_file:
dest_file = io.BytesIO()
elif isinstance(dest_file, str):
dest_file = open(dest_file, 'wb')
elif isinstance(dest_file, file):
pass
else:
raise ValueError("destfile is of unknown type")
conn = self.protocol_handler.Open(
self._handle, destination=b'sync:', timeout_ms=timeout_ms)
self.filesync_handler.Pull(conn, device_filename, dest_file, progress_callback)
conn.Close()
if isinstance(dest_file, io.BytesIO):
return dest_file.getvalue()
else:
dest_file.close()
if hasattr(dest_file, 'name'):
return os.path.exists(dest_file.name)
# We don't know what the path is, so we just assume it exists.
return True | [
"def",
"Pull",
"(",
"self",
",",
"device_filename",
",",
"dest_file",
"=",
"None",
",",
"timeout_ms",
"=",
"None",
",",
"progress_callback",
"=",
"None",
")",
":",
"if",
"not",
"dest_file",
":",
"dest_file",
"=",
"io",
".",
"BytesIO",
"(",
")",
"elif",
... | Pull a file from the device.
Args:
device_filename: Filename on the device to pull.
dest_file: If set, a filename or writable file-like object.
timeout_ms: Expected timeout for any part of the pull.
progress_callback: callback method that accepts filename, bytes_written and total_bytes,
total_bytes will be -1 for file-like objects
Returns:
The file data if dest_file is not set. Otherwise, True if the destination file exists | [
"Pull",
"a",
"file",
"from",
"the",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L283-L318 |
235,757 | google/python-adb | adb/adb_commands.py | AdbCommands.List | def List(self, device_path):
"""Return a directory listing of the given path.
Args:
device_path: Directory to list.
"""
connection = self.protocol_handler.Open(self._handle, destination=b'sync:')
listing = self.filesync_handler.List(connection, device_path)
connection.Close()
return listing | python | def List(self, device_path):
connection = self.protocol_handler.Open(self._handle, destination=b'sync:')
listing = self.filesync_handler.List(connection, device_path)
connection.Close()
return listing | [
"def",
"List",
"(",
"self",
",",
"device_path",
")",
":",
"connection",
"=",
"self",
".",
"protocol_handler",
".",
"Open",
"(",
"self",
".",
"_handle",
",",
"destination",
"=",
"b'sync:'",
")",
"listing",
"=",
"self",
".",
"filesync_handler",
".",
"List",
... | Return a directory listing of the given path.
Args:
device_path: Directory to list. | [
"Return",
"a",
"directory",
"listing",
"of",
"the",
"given",
"path",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L328-L337 |
235,758 | google/python-adb | adb/adb_commands.py | AdbCommands.Shell | def Shell(self, command, timeout_ms=None):
"""Run command on the device, returning the output.
Args:
command: Shell command to run
timeout_ms: Maximum time to allow the command to run.
"""
return self.protocol_handler.Command(
self._handle, service=b'shell', command=command,
timeout_ms=timeout_ms) | python | def Shell(self, command, timeout_ms=None):
return self.protocol_handler.Command(
self._handle, service=b'shell', command=command,
timeout_ms=timeout_ms) | [
"def",
"Shell",
"(",
"self",
",",
"command",
",",
"timeout_ms",
"=",
"None",
")",
":",
"return",
"self",
".",
"protocol_handler",
".",
"Command",
"(",
"self",
".",
"_handle",
",",
"service",
"=",
"b'shell'",
",",
"command",
"=",
"command",
",",
"timeout_... | Run command on the device, returning the output.
Args:
command: Shell command to run
timeout_ms: Maximum time to allow the command to run. | [
"Run",
"command",
"on",
"the",
"device",
"returning",
"the",
"output",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L367-L376 |
235,759 | google/python-adb | adb/adb_commands.py | AdbCommands.StreamingShell | def StreamingShell(self, command, timeout_ms=None):
"""Run command on the device, yielding each line of output.
Args:
command: Command to run on the target.
timeout_ms: Maximum time to allow the command to run.
Yields:
The responses from the shell command.
"""
return self.protocol_handler.StreamingCommand(
self._handle, service=b'shell', command=command,
timeout_ms=timeout_ms) | python | def StreamingShell(self, command, timeout_ms=None):
return self.protocol_handler.StreamingCommand(
self._handle, service=b'shell', command=command,
timeout_ms=timeout_ms) | [
"def",
"StreamingShell",
"(",
"self",
",",
"command",
",",
"timeout_ms",
"=",
"None",
")",
":",
"return",
"self",
".",
"protocol_handler",
".",
"StreamingCommand",
"(",
"self",
".",
"_handle",
",",
"service",
"=",
"b'shell'",
",",
"command",
"=",
"command",
... | Run command on the device, yielding each line of output.
Args:
command: Command to run on the target.
timeout_ms: Maximum time to allow the command to run.
Yields:
The responses from the shell command. | [
"Run",
"command",
"on",
"the",
"device",
"yielding",
"each",
"line",
"of",
"output",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L378-L390 |
235,760 | google/python-adb | adb/adb_commands.py | AdbCommands.InteractiveShell | def InteractiveShell(self, cmd=None, strip_cmd=True, delim=None, strip_delim=True):
"""Get stdout from the currently open interactive shell and optionally run a command
on the device, returning all output.
Args:
cmd: Optional. Command to run on the target.
strip_cmd: Optional (default True). Strip command name from stdout.
delim: Optional. Delimiter to look for in the output to know when to stop expecting more output
(usually the shell prompt)
strip_delim: Optional (default True): Strip the provided delimiter from the output
Returns:
The stdout from the shell command.
"""
conn = self._get_service_connection(b'shell:')
return self.protocol_handler.InteractiveShellCommand(
conn, cmd=cmd, strip_cmd=strip_cmd,
delim=delim, strip_delim=strip_delim) | python | def InteractiveShell(self, cmd=None, strip_cmd=True, delim=None, strip_delim=True):
conn = self._get_service_connection(b'shell:')
return self.protocol_handler.InteractiveShellCommand(
conn, cmd=cmd, strip_cmd=strip_cmd,
delim=delim, strip_delim=strip_delim) | [
"def",
"InteractiveShell",
"(",
"self",
",",
"cmd",
"=",
"None",
",",
"strip_cmd",
"=",
"True",
",",
"delim",
"=",
"None",
",",
"strip_delim",
"=",
"True",
")",
":",
"conn",
"=",
"self",
".",
"_get_service_connection",
"(",
"b'shell:'",
")",
"return",
"s... | Get stdout from the currently open interactive shell and optionally run a command
on the device, returning all output.
Args:
cmd: Optional. Command to run on the target.
strip_cmd: Optional (default True). Strip command name from stdout.
delim: Optional. Delimiter to look for in the output to know when to stop expecting more output
(usually the shell prompt)
strip_delim: Optional (default True): Strip the provided delimiter from the output
Returns:
The stdout from the shell command. | [
"Get",
"stdout",
"from",
"the",
"currently",
"open",
"interactive",
"shell",
"and",
"optionally",
"run",
"a",
"command",
"on",
"the",
"device",
"returning",
"all",
"output",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L401-L419 |
235,761 | google/python-adb | adb/common.py | InterfaceMatcher | def InterfaceMatcher(clazz, subclass, protocol):
"""Returns a matcher that returns the setting with the given interface."""
interface = (clazz, subclass, protocol)
def Matcher(device):
for setting in device.iterSettings():
if GetInterface(setting) == interface:
return setting
return Matcher | python | def InterfaceMatcher(clazz, subclass, protocol):
interface = (clazz, subclass, protocol)
def Matcher(device):
for setting in device.iterSettings():
if GetInterface(setting) == interface:
return setting
return Matcher | [
"def",
"InterfaceMatcher",
"(",
"clazz",
",",
"subclass",
",",
"protocol",
")",
":",
"interface",
"=",
"(",
"clazz",
",",
"subclass",
",",
"protocol",
")",
"def",
"Matcher",
"(",
"device",
")",
":",
"for",
"setting",
"in",
"device",
".",
"iterSettings",
... | Returns a matcher that returns the setting with the given interface. | [
"Returns",
"a",
"matcher",
"that",
"returns",
"the",
"setting",
"with",
"the",
"given",
"interface",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L40-L49 |
235,762 | google/python-adb | adb/common.py | UsbHandle.Open | def Open(self):
"""Opens the USB device for this setting, and claims the interface."""
# Make sure we close any previous handle open to this usb device.
port_path = tuple(self.port_path)
with self._HANDLE_CACHE_LOCK:
old_handle = self._HANDLE_CACHE.get(port_path)
if old_handle is not None:
old_handle.Close()
self._read_endpoint = None
self._write_endpoint = None
for endpoint in self._setting.iterEndpoints():
address = endpoint.getAddress()
if address & libusb1.USB_ENDPOINT_DIR_MASK:
self._read_endpoint = address
self._max_read_packet_len = endpoint.getMaxPacketSize()
else:
self._write_endpoint = address
assert self._read_endpoint is not None
assert self._write_endpoint is not None
handle = self._device.open()
iface_number = self._setting.getNumber()
try:
if (platform.system() != 'Windows'
and handle.kernelDriverActive(iface_number)):
handle.detachKernelDriver(iface_number)
except libusb1.USBError as e:
if e.value == libusb1.LIBUSB_ERROR_NOT_FOUND:
_LOG.warning('Kernel driver not found for interface: %s.', iface_number)
else:
raise
handle.claimInterface(iface_number)
self._handle = handle
self._interface_number = iface_number
with self._HANDLE_CACHE_LOCK:
self._HANDLE_CACHE[port_path] = self
# When this object is deleted, make sure it's closed.
weakref.ref(self, self.Close) | python | def Open(self):
# Make sure we close any previous handle open to this usb device.
port_path = tuple(self.port_path)
with self._HANDLE_CACHE_LOCK:
old_handle = self._HANDLE_CACHE.get(port_path)
if old_handle is not None:
old_handle.Close()
self._read_endpoint = None
self._write_endpoint = None
for endpoint in self._setting.iterEndpoints():
address = endpoint.getAddress()
if address & libusb1.USB_ENDPOINT_DIR_MASK:
self._read_endpoint = address
self._max_read_packet_len = endpoint.getMaxPacketSize()
else:
self._write_endpoint = address
assert self._read_endpoint is not None
assert self._write_endpoint is not None
handle = self._device.open()
iface_number = self._setting.getNumber()
try:
if (platform.system() != 'Windows'
and handle.kernelDriverActive(iface_number)):
handle.detachKernelDriver(iface_number)
except libusb1.USBError as e:
if e.value == libusb1.LIBUSB_ERROR_NOT_FOUND:
_LOG.warning('Kernel driver not found for interface: %s.', iface_number)
else:
raise
handle.claimInterface(iface_number)
self._handle = handle
self._interface_number = iface_number
with self._HANDLE_CACHE_LOCK:
self._HANDLE_CACHE[port_path] = self
# When this object is deleted, make sure it's closed.
weakref.ref(self, self.Close) | [
"def",
"Open",
"(",
"self",
")",
":",
"# Make sure we close any previous handle open to this usb device.",
"port_path",
"=",
"tuple",
"(",
"self",
".",
"port_path",
")",
"with",
"self",
".",
"_HANDLE_CACHE_LOCK",
":",
"old_handle",
"=",
"self",
".",
"_HANDLE_CACHE",
... | Opens the USB device for this setting, and claims the interface. | [
"Opens",
"the",
"USB",
"device",
"for",
"this",
"setting",
"and",
"claims",
"the",
"interface",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L94-L135 |
235,763 | google/python-adb | adb/common.py | UsbHandle.PortPathMatcher | def PortPathMatcher(cls, port_path):
"""Returns a device matcher for the given port path."""
if isinstance(port_path, str):
# Convert from sysfs path to port_path.
port_path = [int(part) for part in SYSFS_PORT_SPLIT_RE.split(port_path)]
return lambda device: device.port_path == port_path | python | def PortPathMatcher(cls, port_path):
if isinstance(port_path, str):
# Convert from sysfs path to port_path.
port_path = [int(part) for part in SYSFS_PORT_SPLIT_RE.split(port_path)]
return lambda device: device.port_path == port_path | [
"def",
"PortPathMatcher",
"(",
"cls",
",",
"port_path",
")",
":",
"if",
"isinstance",
"(",
"port_path",
",",
"str",
")",
":",
"# Convert from sysfs path to port_path.",
"port_path",
"=",
"[",
"int",
"(",
"part",
")",
"for",
"part",
"in",
"SYSFS_PORT_SPLIT_RE",
... | Returns a device matcher for the given port path. | [
"Returns",
"a",
"device",
"matcher",
"for",
"the",
"given",
"port",
"path",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L203-L208 |
235,764 | google/python-adb | adb/common.py | UsbHandle.Find | def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):
"""Gets the first device that matches according to the keyword args."""
if port_path:
device_matcher = cls.PortPathMatcher(port_path)
usb_info = port_path
elif serial:
device_matcher = cls.SerialMatcher(serial)
usb_info = serial
else:
device_matcher = None
usb_info = 'first'
return cls.FindFirst(setting_matcher, device_matcher,
usb_info=usb_info, timeout_ms=timeout_ms) | python | def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):
if port_path:
device_matcher = cls.PortPathMatcher(port_path)
usb_info = port_path
elif serial:
device_matcher = cls.SerialMatcher(serial)
usb_info = serial
else:
device_matcher = None
usb_info = 'first'
return cls.FindFirst(setting_matcher, device_matcher,
usb_info=usb_info, timeout_ms=timeout_ms) | [
"def",
"Find",
"(",
"cls",
",",
"setting_matcher",
",",
"port_path",
"=",
"None",
",",
"serial",
"=",
"None",
",",
"timeout_ms",
"=",
"None",
")",
":",
"if",
"port_path",
":",
"device_matcher",
"=",
"cls",
".",
"PortPathMatcher",
"(",
"port_path",
")",
"... | Gets the first device that matches according to the keyword args. | [
"Gets",
"the",
"first",
"device",
"that",
"matches",
"according",
"to",
"the",
"keyword",
"args",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L226-L238 |
235,765 | google/python-adb | adb/common.py | UsbHandle.FindFirst | def FindFirst(cls, setting_matcher, device_matcher=None, **kwargs):
"""Find and return the first matching device.
Args:
setting_matcher: See cls.FindDevices.
device_matcher: See cls.FindDevices.
**kwargs: See cls.FindDevices.
Returns:
An instance of UsbHandle.
Raises:
DeviceNotFoundError: Raised if the device is not available.
"""
try:
return next(cls.FindDevices(
setting_matcher, device_matcher=device_matcher, **kwargs))
except StopIteration:
raise usb_exceptions.DeviceNotFoundError(
'No device available, or it is in the wrong configuration.') | python | def FindFirst(cls, setting_matcher, device_matcher=None, **kwargs):
try:
return next(cls.FindDevices(
setting_matcher, device_matcher=device_matcher, **kwargs))
except StopIteration:
raise usb_exceptions.DeviceNotFoundError(
'No device available, or it is in the wrong configuration.') | [
"def",
"FindFirst",
"(",
"cls",
",",
"setting_matcher",
",",
"device_matcher",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"next",
"(",
"cls",
".",
"FindDevices",
"(",
"setting_matcher",
",",
"device_matcher",
"=",
"device_matcher",... | Find and return the first matching device.
Args:
setting_matcher: See cls.FindDevices.
device_matcher: See cls.FindDevices.
**kwargs: See cls.FindDevices.
Returns:
An instance of UsbHandle.
Raises:
DeviceNotFoundError: Raised if the device is not available. | [
"Find",
"and",
"return",
"the",
"first",
"matching",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L241-L260 |
235,766 | google/python-adb | adb/common.py | UsbHandle.FindDevices | def FindDevices(cls, setting_matcher, device_matcher=None,
usb_info='', timeout_ms=None):
"""Find and yield the devices that match.
Args:
setting_matcher: Function that returns the setting to use given a
usb1.USBDevice, or None if the device doesn't have a valid setting.
device_matcher: Function that returns True if the given UsbHandle is
valid. None to match any device.
usb_info: Info string describing device(s).
timeout_ms: Default timeout of commands in milliseconds.
Yields:
UsbHandle instances
"""
ctx = usb1.USBContext()
for device in ctx.getDeviceList(skip_on_error=True):
setting = setting_matcher(device)
if setting is None:
continue
handle = cls(device, setting, usb_info=usb_info, timeout_ms=timeout_ms)
if device_matcher is None or device_matcher(handle):
yield handle | python | def FindDevices(cls, setting_matcher, device_matcher=None,
usb_info='', timeout_ms=None):
ctx = usb1.USBContext()
for device in ctx.getDeviceList(skip_on_error=True):
setting = setting_matcher(device)
if setting is None:
continue
handle = cls(device, setting, usb_info=usb_info, timeout_ms=timeout_ms)
if device_matcher is None or device_matcher(handle):
yield handle | [
"def",
"FindDevices",
"(",
"cls",
",",
"setting_matcher",
",",
"device_matcher",
"=",
"None",
",",
"usb_info",
"=",
"''",
",",
"timeout_ms",
"=",
"None",
")",
":",
"ctx",
"=",
"usb1",
".",
"USBContext",
"(",
")",
"for",
"device",
"in",
"ctx",
".",
"get... | Find and yield the devices that match.
Args:
setting_matcher: Function that returns the setting to use given a
usb1.USBDevice, or None if the device doesn't have a valid setting.
device_matcher: Function that returns True if the given UsbHandle is
valid. None to match any device.
usb_info: Info string describing device(s).
timeout_ms: Default timeout of commands in milliseconds.
Yields:
UsbHandle instances | [
"Find",
"and",
"yield",
"the",
"devices",
"that",
"match",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L263-L286 |
235,767 | google/python-adb | adb/adb_protocol.py | _AdbConnection.Write | def Write(self, data):
"""Write a packet and expect an Ack."""
self._Send(b'WRTE', arg0=self.local_id, arg1=self.remote_id, data=data)
# Expect an ack in response.
cmd, okay_data = self.ReadUntil(b'OKAY')
if cmd != b'OKAY':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', okay_data)
raise InvalidCommandError(
'Expected an OKAY in response to a WRITE, got %s (%s)',
cmd, okay_data)
return len(data) | python | def Write(self, data):
self._Send(b'WRTE', arg0=self.local_id, arg1=self.remote_id, data=data)
# Expect an ack in response.
cmd, okay_data = self.ReadUntil(b'OKAY')
if cmd != b'OKAY':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', okay_data)
raise InvalidCommandError(
'Expected an OKAY in response to a WRITE, got %s (%s)',
cmd, okay_data)
return len(data) | [
"def",
"Write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_Send",
"(",
"b'WRTE'",
",",
"arg0",
"=",
"self",
".",
"local_id",
",",
"arg1",
"=",
"self",
".",
"remote_id",
",",
"data",
"=",
"data",
")",
"# Expect an ack in response.",
"cmd",
",",
... | Write a packet and expect an Ack. | [
"Write",
"a",
"packet",
"and",
"expect",
"an",
"Ack",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L109-L121 |
235,768 | google/python-adb | adb/adb_protocol.py | _AdbConnection.ReadUntil | def ReadUntil(self, *expected_cmds):
"""Read a packet, Ack any write packets."""
cmd, remote_id, local_id, data = AdbMessage.Read(
self.usb, expected_cmds, self.timeout_ms)
if local_id != 0 and self.local_id != local_id:
raise InterleavedDataError("We don't support multiple streams...")
if remote_id != 0 and self.remote_id != remote_id:
raise InvalidResponseError(
'Incorrect remote id, expected %s got %s' % (
self.remote_id, remote_id))
# Ack write packets.
if cmd == b'WRTE':
self.Okay()
return cmd, data | python | def ReadUntil(self, *expected_cmds):
cmd, remote_id, local_id, data = AdbMessage.Read(
self.usb, expected_cmds, self.timeout_ms)
if local_id != 0 and self.local_id != local_id:
raise InterleavedDataError("We don't support multiple streams...")
if remote_id != 0 and self.remote_id != remote_id:
raise InvalidResponseError(
'Incorrect remote id, expected %s got %s' % (
self.remote_id, remote_id))
# Ack write packets.
if cmd == b'WRTE':
self.Okay()
return cmd, data | [
"def",
"ReadUntil",
"(",
"self",
",",
"*",
"expected_cmds",
")",
":",
"cmd",
",",
"remote_id",
",",
"local_id",
",",
"data",
"=",
"AdbMessage",
".",
"Read",
"(",
"self",
".",
"usb",
",",
"expected_cmds",
",",
"self",
".",
"timeout_ms",
")",
"if",
"loca... | Read a packet, Ack any write packets. | [
"Read",
"a",
"packet",
"Ack",
"any",
"write",
"packets",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L126-L139 |
235,769 | google/python-adb | adb/adb_protocol.py | _AdbConnection.ReadUntilClose | def ReadUntilClose(self):
"""Yield packets until a Close packet is received."""
while True:
cmd, data = self.ReadUntil(b'CLSE', b'WRTE')
if cmd == b'CLSE':
self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
break
if cmd != b'WRTE':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', data)
raise InvalidCommandError('Expected a WRITE or a CLOSE, got %s (%s)',
cmd, data)
yield data | python | def ReadUntilClose(self):
while True:
cmd, data = self.ReadUntil(b'CLSE', b'WRTE')
if cmd == b'CLSE':
self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
break
if cmd != b'WRTE':
if cmd == b'FAIL':
raise usb_exceptions.AdbCommandFailureException(
'Command failed.', data)
raise InvalidCommandError('Expected a WRITE or a CLOSE, got %s (%s)',
cmd, data)
yield data | [
"def",
"ReadUntilClose",
"(",
"self",
")",
":",
"while",
"True",
":",
"cmd",
",",
"data",
"=",
"self",
".",
"ReadUntil",
"(",
"b'CLSE'",
",",
"b'WRTE'",
")",
"if",
"cmd",
"==",
"b'CLSE'",
":",
"self",
".",
"_Send",
"(",
"b'CLSE'",
",",
"arg0",
"=",
... | Yield packets until a Close packet is received. | [
"Yield",
"packets",
"until",
"a",
"Close",
"packet",
"is",
"received",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L141-L154 |
235,770 | google/python-adb | adb/adb_protocol.py | AdbMessage.Pack | def Pack(self):
"""Returns this message in an over-the-wire format."""
return struct.pack(self.format, self.command, self.arg0, self.arg1,
len(self.data), self.checksum, self.magic) | python | def Pack(self):
return struct.pack(self.format, self.command, self.arg0, self.arg1,
len(self.data), self.checksum, self.magic) | [
"def",
"Pack",
"(",
"self",
")",
":",
"return",
"struct",
".",
"pack",
"(",
"self",
".",
"format",
",",
"self",
".",
"command",
",",
"self",
".",
"arg0",
",",
"self",
".",
"arg1",
",",
"len",
"(",
"self",
".",
"data",
")",
",",
"self",
".",
"ch... | Returns this message in an over-the-wire format. | [
"Returns",
"this",
"message",
"in",
"an",
"over",
"-",
"the",
"-",
"wire",
"format",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L217-L220 |
235,771 | google/python-adb | adb/adb_protocol.py | AdbMessage.Send | def Send(self, usb, timeout_ms=None):
"""Send this message over USB."""
usb.BulkWrite(self.Pack(), timeout_ms)
usb.BulkWrite(self.data, timeout_ms) | python | def Send(self, usb, timeout_ms=None):
usb.BulkWrite(self.Pack(), timeout_ms)
usb.BulkWrite(self.data, timeout_ms) | [
"def",
"Send",
"(",
"self",
",",
"usb",
",",
"timeout_ms",
"=",
"None",
")",
":",
"usb",
".",
"BulkWrite",
"(",
"self",
".",
"Pack",
"(",
")",
",",
"timeout_ms",
")",
"usb",
".",
"BulkWrite",
"(",
"self",
".",
"data",
",",
"timeout_ms",
")"
] | Send this message over USB. | [
"Send",
"this",
"message",
"over",
"USB",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L231-L234 |
235,772 | google/python-adb | adb/adb_protocol.py | AdbMessage.Read | def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
"""Receive a response from the device."""
total_timeout_ms = usb.Timeout(total_timeout_ms)
start = time.time()
while True:
msg = usb.BulkRead(24, timeout_ms)
cmd, arg0, arg1, data_length, data_checksum = cls.Unpack(msg)
command = cls.constants.get(cmd)
if not command:
raise InvalidCommandError(
'Unknown command: %x' % cmd, cmd, (arg0, arg1))
if command in expected_cmds:
break
if time.time() - start > total_timeout_ms:
raise InvalidCommandError(
'Never got one of the expected responses (%s)' % expected_cmds,
cmd, (timeout_ms, total_timeout_ms))
if data_length > 0:
data = bytearray()
while data_length > 0:
temp = usb.BulkRead(data_length, timeout_ms)
if len(temp) != data_length:
print(
"Data_length {} does not match actual number of bytes read: {}".format(data_length, len(temp)))
data += temp
data_length -= len(temp)
actual_checksum = cls.CalculateChecksum(data)
if actual_checksum != data_checksum:
raise InvalidChecksumError(
'Received checksum %s != %s', (actual_checksum, data_checksum))
else:
data = b''
return command, arg0, arg1, bytes(data) | python | def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
total_timeout_ms = usb.Timeout(total_timeout_ms)
start = time.time()
while True:
msg = usb.BulkRead(24, timeout_ms)
cmd, arg0, arg1, data_length, data_checksum = cls.Unpack(msg)
command = cls.constants.get(cmd)
if not command:
raise InvalidCommandError(
'Unknown command: %x' % cmd, cmd, (arg0, arg1))
if command in expected_cmds:
break
if time.time() - start > total_timeout_ms:
raise InvalidCommandError(
'Never got one of the expected responses (%s)' % expected_cmds,
cmd, (timeout_ms, total_timeout_ms))
if data_length > 0:
data = bytearray()
while data_length > 0:
temp = usb.BulkRead(data_length, timeout_ms)
if len(temp) != data_length:
print(
"Data_length {} does not match actual number of bytes read: {}".format(data_length, len(temp)))
data += temp
data_length -= len(temp)
actual_checksum = cls.CalculateChecksum(data)
if actual_checksum != data_checksum:
raise InvalidChecksumError(
'Received checksum %s != %s', (actual_checksum, data_checksum))
else:
data = b''
return command, arg0, arg1, bytes(data) | [
"def",
"Read",
"(",
"cls",
",",
"usb",
",",
"expected_cmds",
",",
"timeout_ms",
"=",
"None",
",",
"total_timeout_ms",
"=",
"None",
")",
":",
"total_timeout_ms",
"=",
"usb",
".",
"Timeout",
"(",
"total_timeout_ms",
")",
"start",
"=",
"time",
".",
"time",
... | Receive a response from the device. | [
"Receive",
"a",
"response",
"from",
"the",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L237-L273 |
235,773 | google/python-adb | adb/adb_protocol.py | AdbMessage.Connect | def Connect(cls, usb, banner=b'notadb', rsa_keys=None, auth_timeout_ms=100):
"""Establish a new connection to the device.
Args:
usb: A USBHandle with BulkRead and BulkWrite methods.
banner: A string to send as a host identifier.
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
Returns:
The device's reported banner. Always starts with the state (device,
recovery, or sideload), sometimes includes information after a : with
various product information.
Raises:
usb_exceptions.DeviceAuthError: When the device expects authentication,
but we weren't given any valid keys.
InvalidResponseError: When the device does authentication in an
unexpected way.
"""
# In py3, convert unicode to bytes. In py2, convert str to bytes.
# It's later joined into a byte string, so in py2, this ends up kind of being a no-op.
if isinstance(banner, str):
banner = bytearray(banner, 'utf-8')
msg = cls(
command=b'CNXN', arg0=VERSION, arg1=MAX_ADB_DATA,
data=b'host::%s\0' % banner)
msg.Send(usb)
cmd, arg0, arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'AUTH':
if not rsa_keys:
raise usb_exceptions.DeviceAuthError(
'Device authentication required, no keys available.')
# Loop through our keys, signing the last 'banner' or token.
for rsa_key in rsa_keys:
if arg0 != AUTH_TOKEN:
raise InvalidResponseError(
'Unknown AUTH response: %s %s %s' % (arg0, arg1, banner))
# Do not mangle the banner property here by converting it to a string
signed_token = rsa_key.Sign(banner)
msg = cls(
command=b'AUTH', arg0=AUTH_SIGNATURE, arg1=0, data=signed_token)
msg.Send(usb)
cmd, arg0, unused_arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'CNXN':
return banner
# None of the keys worked, so send a public key.
msg = cls(
command=b'AUTH', arg0=AUTH_RSAPUBLICKEY, arg1=0,
data=rsa_keys[0].GetPublicKey() + b'\0')
msg.Send(usb)
try:
cmd, arg0, unused_arg1, banner = cls.Read(
usb, [b'CNXN'], timeout_ms=auth_timeout_ms)
except usb_exceptions.ReadFailedError as e:
if e.usb_error.value == -7: # Timeout.
raise usb_exceptions.DeviceAuthError(
'Accept auth key on device, then retry.')
raise
# This didn't time-out, so we got a CNXN response.
return banner
return banner | python | def Connect(cls, usb, banner=b'notadb', rsa_keys=None, auth_timeout_ms=100):
# In py3, convert unicode to bytes. In py2, convert str to bytes.
# It's later joined into a byte string, so in py2, this ends up kind of being a no-op.
if isinstance(banner, str):
banner = bytearray(banner, 'utf-8')
msg = cls(
command=b'CNXN', arg0=VERSION, arg1=MAX_ADB_DATA,
data=b'host::%s\0' % banner)
msg.Send(usb)
cmd, arg0, arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'AUTH':
if not rsa_keys:
raise usb_exceptions.DeviceAuthError(
'Device authentication required, no keys available.')
# Loop through our keys, signing the last 'banner' or token.
for rsa_key in rsa_keys:
if arg0 != AUTH_TOKEN:
raise InvalidResponseError(
'Unknown AUTH response: %s %s %s' % (arg0, arg1, banner))
# Do not mangle the banner property here by converting it to a string
signed_token = rsa_key.Sign(banner)
msg = cls(
command=b'AUTH', arg0=AUTH_SIGNATURE, arg1=0, data=signed_token)
msg.Send(usb)
cmd, arg0, unused_arg1, banner = cls.Read(usb, [b'CNXN', b'AUTH'])
if cmd == b'CNXN':
return banner
# None of the keys worked, so send a public key.
msg = cls(
command=b'AUTH', arg0=AUTH_RSAPUBLICKEY, arg1=0,
data=rsa_keys[0].GetPublicKey() + b'\0')
msg.Send(usb)
try:
cmd, arg0, unused_arg1, banner = cls.Read(
usb, [b'CNXN'], timeout_ms=auth_timeout_ms)
except usb_exceptions.ReadFailedError as e:
if e.usb_error.value == -7: # Timeout.
raise usb_exceptions.DeviceAuthError(
'Accept auth key on device, then retry.')
raise
# This didn't time-out, so we got a CNXN response.
return banner
return banner | [
"def",
"Connect",
"(",
"cls",
",",
"usb",
",",
"banner",
"=",
"b'notadb'",
",",
"rsa_keys",
"=",
"None",
",",
"auth_timeout_ms",
"=",
"100",
")",
":",
"# In py3, convert unicode to bytes. In py2, convert str to bytes.",
"# It's later joined into a byte string, so in py2, th... | Establish a new connection to the device.
Args:
usb: A USBHandle with BulkRead and BulkWrite methods.
banner: A string to send as a host identifier.
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
Returns:
The device's reported banner. Always starts with the state (device,
recovery, or sideload), sometimes includes information after a : with
various product information.
Raises:
usb_exceptions.DeviceAuthError: When the device expects authentication,
but we weren't given any valid keys.
InvalidResponseError: When the device does authentication in an
unexpected way. | [
"Establish",
"a",
"new",
"connection",
"to",
"the",
"device",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L276-L348 |
235,774 | google/python-adb | adb/adb_protocol.py | AdbMessage.Open | def Open(cls, usb, destination, timeout_ms=None):
"""Opens a new connection to the device via an OPEN message.
Not the same as the posix 'open' or any other google3 Open methods.
Args:
usb: USB device handle with BulkRead and BulkWrite methods.
destination: The service:command string.
timeout_ms: Timeout in milliseconds for USB packets.
Raises:
InvalidResponseError: Wrong local_id sent to us.
InvalidCommandError: Didn't get a ready response.
Returns:
The local connection id.
"""
local_id = 1
msg = cls(
command=b'OPEN', arg0=local_id, arg1=0,
data=destination + b'\0')
msg.Send(usb, timeout_ms)
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
timeout_ms=timeout_ms)
if local_id != their_local_id:
raise InvalidResponseError(
'Expected the local_id to be {}, got {}'.format(local_id, their_local_id))
if cmd == b'CLSE':
# Some devices seem to be sending CLSE once more after a request, this *should* handle it
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
timeout_ms=timeout_ms)
# Device doesn't support this service.
if cmd == b'CLSE':
return None
if cmd != b'OKAY':
raise InvalidCommandError('Expected a ready response, got {}'.format(cmd),
cmd, (remote_id, their_local_id))
return _AdbConnection(usb, local_id, remote_id, timeout_ms) | python | def Open(cls, usb, destination, timeout_ms=None):
local_id = 1
msg = cls(
command=b'OPEN', arg0=local_id, arg1=0,
data=destination + b'\0')
msg.Send(usb, timeout_ms)
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
timeout_ms=timeout_ms)
if local_id != their_local_id:
raise InvalidResponseError(
'Expected the local_id to be {}, got {}'.format(local_id, their_local_id))
if cmd == b'CLSE':
# Some devices seem to be sending CLSE once more after a request, this *should* handle it
cmd, remote_id, their_local_id, _ = cls.Read(usb, [b'CLSE', b'OKAY'],
timeout_ms=timeout_ms)
# Device doesn't support this service.
if cmd == b'CLSE':
return None
if cmd != b'OKAY':
raise InvalidCommandError('Expected a ready response, got {}'.format(cmd),
cmd, (remote_id, their_local_id))
return _AdbConnection(usb, local_id, remote_id, timeout_ms) | [
"def",
"Open",
"(",
"cls",
",",
"usb",
",",
"destination",
",",
"timeout_ms",
"=",
"None",
")",
":",
"local_id",
"=",
"1",
"msg",
"=",
"cls",
"(",
"command",
"=",
"b'OPEN'",
",",
"arg0",
"=",
"local_id",
",",
"arg1",
"=",
"0",
",",
"data",
"=",
"... | Opens a new connection to the device via an OPEN message.
Not the same as the posix 'open' or any other google3 Open methods.
Args:
usb: USB device handle with BulkRead and BulkWrite methods.
destination: The service:command string.
timeout_ms: Timeout in milliseconds for USB packets.
Raises:
InvalidResponseError: Wrong local_id sent to us.
InvalidCommandError: Didn't get a ready response.
Returns:
The local connection id. | [
"Opens",
"a",
"new",
"connection",
"to",
"the",
"device",
"via",
"an",
"OPEN",
"message",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_protocol.py#L351-L388 |
235,775 | google/python-adb | adb/fastboot.py | FastbootCommands.ConnectDevice | def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, chunk_kb=1024, **kwargs):
"""Convenience function to get an adb device from usb path or serial.
Args:
port_path: The filename of usb port to use.
serial: The serial number of the device to use.
default_timeout_ms: The default timeout in milliseconds to use.
chunk_kb: Amount of data, in kilobytes, to break fastboot packets up into
kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle)
banner: Connection banner to pass to the remote device
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
If serial specifies a TCP address:port, then a TCP connection is
used instead of a USB connection.
"""
if 'handle' in kwargs:
self._handle = kwargs['handle']
else:
self._handle = common.UsbHandle.FindAndOpen(
DeviceIsAvailable, port_path=port_path, serial=serial,
timeout_ms=default_timeout_ms)
self._protocol = FastbootProtocol(self._handle, chunk_kb)
return self | python | def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, chunk_kb=1024, **kwargs):
if 'handle' in kwargs:
self._handle = kwargs['handle']
else:
self._handle = common.UsbHandle.FindAndOpen(
DeviceIsAvailable, port_path=port_path, serial=serial,
timeout_ms=default_timeout_ms)
self._protocol = FastbootProtocol(self._handle, chunk_kb)
return self | [
"def",
"ConnectDevice",
"(",
"self",
",",
"port_path",
"=",
"None",
",",
"serial",
"=",
"None",
",",
"default_timeout_ms",
"=",
"None",
",",
"chunk_kb",
"=",
"1024",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'handle'",
"in",
"kwargs",
":",
"self",
".",... | Convenience function to get an adb device from usb path or serial.
Args:
port_path: The filename of usb port to use.
serial: The serial number of the device to use.
default_timeout_ms: The default timeout in milliseconds to use.
chunk_kb: Amount of data, in kilobytes, to break fastboot packets up into
kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle)
banner: Connection banner to pass to the remote device
rsa_keys: List of AuthSigner subclass instances to be used for
authentication. The device can either accept one of these via the Sign
method, or we will send the result of GetPublicKey from the first one
if the device doesn't accept any of them.
auth_timeout_ms: Timeout to wait for when sending a new public key. This
is only relevant when we send a new public key. The device shows a
dialog and this timeout is how long to wait for that dialog. If used
in automation, this should be low to catch such a case as a failure
quickly; while in interactive settings it should be high to allow
users to accept the dialog. We default to automation here, so it's low
by default.
If serial specifies a TCP address:port, then a TCP connection is
used instead of a USB connection. | [
"Convenience",
"function",
"to",
"get",
"an",
"adb",
"device",
"from",
"usb",
"path",
"or",
"serial",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/fastboot.py#L225-L261 |
235,776 | google/python-adb | adb/common_cli.py | _DocToArgs | def _DocToArgs(doc):
"""Converts a docstring documenting arguments into a dict."""
m = None
offset = None
in_arg = False
out = {}
for l in doc.splitlines():
if l.strip() == 'Args:':
in_arg = True
elif in_arg:
if not l.strip():
break
if offset is None:
offset = len(l) - len(l.lstrip())
l = l[offset:]
if l[0] == ' ' and m:
out[m.group(1)] += ' ' + l.lstrip()
else:
m = re.match(r'^([a-z_]+): (.+)$', l.strip())
out[m.group(1)] = m.group(2)
return out | python | def _DocToArgs(doc):
m = None
offset = None
in_arg = False
out = {}
for l in doc.splitlines():
if l.strip() == 'Args:':
in_arg = True
elif in_arg:
if not l.strip():
break
if offset is None:
offset = len(l) - len(l.lstrip())
l = l[offset:]
if l[0] == ' ' and m:
out[m.group(1)] += ' ' + l.lstrip()
else:
m = re.match(r'^([a-z_]+): (.+)$', l.strip())
out[m.group(1)] = m.group(2)
return out | [
"def",
"_DocToArgs",
"(",
"doc",
")",
":",
"m",
"=",
"None",
"offset",
"=",
"None",
"in_arg",
"=",
"False",
"out",
"=",
"{",
"}",
"for",
"l",
"in",
"doc",
".",
"splitlines",
"(",
")",
":",
"if",
"l",
".",
"strip",
"(",
")",
"==",
"'Args:'",
":"... | Converts a docstring documenting arguments into a dict. | [
"Converts",
"a",
"docstring",
"documenting",
"arguments",
"into",
"a",
"dict",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common_cli.py#L66-L86 |
235,777 | google/python-adb | adb/common_cli.py | MakeSubparser | def MakeSubparser(subparsers, parents, method, arguments=None):
"""Returns an argparse subparser to create a 'subcommand' to adb."""
name = ('-'.join(re.split(r'([A-Z][a-z]+)', method.__name__)[1:-1:2])).lower()
help = method.__doc__.splitlines()[0]
subparser = subparsers.add_parser(
name=name, description=help, help=help.rstrip('.'), parents=parents)
subparser.set_defaults(method=method, positional=[])
argspec = inspect.getargspec(method)
# Figure out positionals and default argument, if any. Explicitly includes
# arguments that default to '' but excludes arguments that default to None.
offset = len(argspec.args) - len(argspec.defaults or []) - 1
positional = []
for i in range(1, len(argspec.args)):
if i > offset and argspec.defaults[i - offset - 1] is None:
break
positional.append(argspec.args[i])
defaults = [None] * offset + list(argspec.defaults or [])
# Add all arguments so they append to args.positional.
args_help = _DocToArgs(method.__doc__)
for name, default in zip(positional, defaults):
if not isinstance(default, (None.__class__, str)):
continue
subparser.add_argument(
name, help=(arguments or {}).get(name, args_help.get(name)),
default=default, nargs='?' if default is not None else None,
action=PositionalArg)
if argspec.varargs:
subparser.add_argument(
argspec.varargs, nargs=argparse.REMAINDER,
help=(arguments or {}).get(argspec.varargs, args_help.get(argspec.varargs)))
return subparser | python | def MakeSubparser(subparsers, parents, method, arguments=None):
name = ('-'.join(re.split(r'([A-Z][a-z]+)', method.__name__)[1:-1:2])).lower()
help = method.__doc__.splitlines()[0]
subparser = subparsers.add_parser(
name=name, description=help, help=help.rstrip('.'), parents=parents)
subparser.set_defaults(method=method, positional=[])
argspec = inspect.getargspec(method)
# Figure out positionals and default argument, if any. Explicitly includes
# arguments that default to '' but excludes arguments that default to None.
offset = len(argspec.args) - len(argspec.defaults or []) - 1
positional = []
for i in range(1, len(argspec.args)):
if i > offset and argspec.defaults[i - offset - 1] is None:
break
positional.append(argspec.args[i])
defaults = [None] * offset + list(argspec.defaults or [])
# Add all arguments so they append to args.positional.
args_help = _DocToArgs(method.__doc__)
for name, default in zip(positional, defaults):
if not isinstance(default, (None.__class__, str)):
continue
subparser.add_argument(
name, help=(arguments or {}).get(name, args_help.get(name)),
default=default, nargs='?' if default is not None else None,
action=PositionalArg)
if argspec.varargs:
subparser.add_argument(
argspec.varargs, nargs=argparse.REMAINDER,
help=(arguments or {}).get(argspec.varargs, args_help.get(argspec.varargs)))
return subparser | [
"def",
"MakeSubparser",
"(",
"subparsers",
",",
"parents",
",",
"method",
",",
"arguments",
"=",
"None",
")",
":",
"name",
"=",
"(",
"'-'",
".",
"join",
"(",
"re",
".",
"split",
"(",
"r'([A-Z][a-z]+)'",
",",
"method",
".",
"__name__",
")",
"[",
"1",
... | Returns an argparse subparser to create a 'subcommand' to adb. | [
"Returns",
"an",
"argparse",
"subparser",
"to",
"create",
"a",
"subcommand",
"to",
"adb",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common_cli.py#L89-L121 |
235,778 | google/python-adb | adb/common_cli.py | _RunMethod | def _RunMethod(dev, args, extra):
"""Runs a method registered via MakeSubparser."""
logging.info('%s(%s)', args.method.__name__, ', '.join(args.positional))
result = args.method(dev, *args.positional, **extra)
if result is not None:
if isinstance(result, io.StringIO):
sys.stdout.write(result.getvalue())
elif isinstance(result, (list, types.GeneratorType)):
r = ''
for r in result:
r = str(r)
sys.stdout.write(r)
if not r.endswith('\n'):
sys.stdout.write('\n')
else:
result = str(result)
sys.stdout.write(result)
if not result.endswith('\n'):
sys.stdout.write('\n')
return 0 | python | def _RunMethod(dev, args, extra):
logging.info('%s(%s)', args.method.__name__, ', '.join(args.positional))
result = args.method(dev, *args.positional, **extra)
if result is not None:
if isinstance(result, io.StringIO):
sys.stdout.write(result.getvalue())
elif isinstance(result, (list, types.GeneratorType)):
r = ''
for r in result:
r = str(r)
sys.stdout.write(r)
if not r.endswith('\n'):
sys.stdout.write('\n')
else:
result = str(result)
sys.stdout.write(result)
if not result.endswith('\n'):
sys.stdout.write('\n')
return 0 | [
"def",
"_RunMethod",
"(",
"dev",
",",
"args",
",",
"extra",
")",
":",
"logging",
".",
"info",
"(",
"'%s(%s)'",
",",
"args",
".",
"method",
".",
"__name__",
",",
"', '",
".",
"join",
"(",
"args",
".",
"positional",
")",
")",
"result",
"=",
"args",
"... | Runs a method registered via MakeSubparser. | [
"Runs",
"a",
"method",
"registered",
"via",
"MakeSubparser",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common_cli.py#L124-L143 |
235,779 | google/python-adb | adb/common_cli.py | StartCli | def StartCli(args, adb_commands, extra=None, **device_kwargs):
"""Starts a common CLI interface for this usb path and protocol."""
try:
dev = adb_commands()
dev.ConnectDevice(port_path=args.port_path, serial=args.serial, default_timeout_ms=args.timeout_ms,
**device_kwargs)
except usb_exceptions.DeviceNotFoundError as e:
print('No device found: {}'.format(e), file=sys.stderr)
return 1
except usb_exceptions.CommonUsbError as e:
print('Could not connect to device: {}'.format(e), file=sys.stderr)
return 1
try:
return _RunMethod(dev, args, extra or {})
except Exception as e: # pylint: disable=broad-except
sys.stdout.write(str(e))
return 1
finally:
dev.Close() | python | def StartCli(args, adb_commands, extra=None, **device_kwargs):
try:
dev = adb_commands()
dev.ConnectDevice(port_path=args.port_path, serial=args.serial, default_timeout_ms=args.timeout_ms,
**device_kwargs)
except usb_exceptions.DeviceNotFoundError as e:
print('No device found: {}'.format(e), file=sys.stderr)
return 1
except usb_exceptions.CommonUsbError as e:
print('Could not connect to device: {}'.format(e), file=sys.stderr)
return 1
try:
return _RunMethod(dev, args, extra or {})
except Exception as e: # pylint: disable=broad-except
sys.stdout.write(str(e))
return 1
finally:
dev.Close() | [
"def",
"StartCli",
"(",
"args",
",",
"adb_commands",
",",
"extra",
"=",
"None",
",",
"*",
"*",
"device_kwargs",
")",
":",
"try",
":",
"dev",
"=",
"adb_commands",
"(",
")",
"dev",
".",
"ConnectDevice",
"(",
"port_path",
"=",
"args",
".",
"port_path",
",... | Starts a common CLI interface for this usb path and protocol. | [
"Starts",
"a",
"common",
"CLI",
"interface",
"for",
"this",
"usb",
"path",
"and",
"protocol",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common_cli.py#L146-L164 |
235,780 | google/python-adb | adb/filesync_protocol.py | FilesyncProtocol.Pull | def Pull(cls, connection, filename, dest_file, progress_callback):
"""Pull a file from the device into the file-like dest_file."""
if progress_callback:
total_bytes = cls.Stat(connection, filename)[1]
progress = cls._HandleProgress(lambda current: progress_callback(filename, current, total_bytes))
next(progress)
cnxn = FileSyncConnection(connection, b'<2I')
try:
cnxn.Send(b'RECV', filename)
for cmd_id, _, data in cnxn.ReadUntil((b'DATA',), b'DONE'):
if cmd_id == b'DONE':
break
dest_file.write(data)
if progress_callback:
progress.send(len(data))
except usb_exceptions.CommonUsbError as e:
raise PullFailedError('Unable to pull file %s due to: %s' % (filename, e)) | python | def Pull(cls, connection, filename, dest_file, progress_callback):
if progress_callback:
total_bytes = cls.Stat(connection, filename)[1]
progress = cls._HandleProgress(lambda current: progress_callback(filename, current, total_bytes))
next(progress)
cnxn = FileSyncConnection(connection, b'<2I')
try:
cnxn.Send(b'RECV', filename)
for cmd_id, _, data in cnxn.ReadUntil((b'DATA',), b'DONE'):
if cmd_id == b'DONE':
break
dest_file.write(data)
if progress_callback:
progress.send(len(data))
except usb_exceptions.CommonUsbError as e:
raise PullFailedError('Unable to pull file %s due to: %s' % (filename, e)) | [
"def",
"Pull",
"(",
"cls",
",",
"connection",
",",
"filename",
",",
"dest_file",
",",
"progress_callback",
")",
":",
"if",
"progress_callback",
":",
"total_bytes",
"=",
"cls",
".",
"Stat",
"(",
"connection",
",",
"filename",
")",
"[",
"1",
"]",
"progress",... | Pull a file from the device into the file-like dest_file. | [
"Pull",
"a",
"file",
"from",
"the",
"device",
"into",
"the",
"file",
"-",
"like",
"dest_file",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/filesync_protocol.py#L84-L101 |
235,781 | google/python-adb | adb/filesync_protocol.py | FileSyncConnection.Read | def Read(self, expected_ids, read_data=True):
"""Read ADB messages and return FileSync packets."""
if self.send_idx:
self._Flush()
# Read one filesync packet off the recv buffer.
header_data = self._ReadBuffered(self.recv_header_len)
header = struct.unpack(self.recv_header_format, header_data)
# Header is (ID, ...).
command_id = self.wire_to_id[header[0]]
if command_id not in expected_ids:
if command_id == b'FAIL':
reason = ''
if self.recv_buffer:
reason = self.recv_buffer.decode('utf-8', errors='ignore')
raise usb_exceptions.AdbCommandFailureException('Command failed: {}'.format(reason))
raise adb_protocol.InvalidResponseError(
'Expected one of %s, got %s' % (expected_ids, command_id))
if not read_data:
return command_id, header[1:]
# Header is (ID, ..., size).
size = header[-1]
data = self._ReadBuffered(size)
return command_id, header[1:-1], data | python | def Read(self, expected_ids, read_data=True):
if self.send_idx:
self._Flush()
# Read one filesync packet off the recv buffer.
header_data = self._ReadBuffered(self.recv_header_len)
header = struct.unpack(self.recv_header_format, header_data)
# Header is (ID, ...).
command_id = self.wire_to_id[header[0]]
if command_id not in expected_ids:
if command_id == b'FAIL':
reason = ''
if self.recv_buffer:
reason = self.recv_buffer.decode('utf-8', errors='ignore')
raise usb_exceptions.AdbCommandFailureException('Command failed: {}'.format(reason))
raise adb_protocol.InvalidResponseError(
'Expected one of %s, got %s' % (expected_ids, command_id))
if not read_data:
return command_id, header[1:]
# Header is (ID, ..., size).
size = header[-1]
data = self._ReadBuffered(size)
return command_id, header[1:-1], data | [
"def",
"Read",
"(",
"self",
",",
"expected_ids",
",",
"read_data",
"=",
"True",
")",
":",
"if",
"self",
".",
"send_idx",
":",
"self",
".",
"_Flush",
"(",
")",
"# Read one filesync packet off the recv buffer.",
"header_data",
"=",
"self",
".",
"_ReadBuffered",
... | Read ADB messages and return FileSync packets. | [
"Read",
"ADB",
"messages",
"and",
"return",
"FileSync",
"packets",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/filesync_protocol.py#L212-L238 |
235,782 | google/python-adb | adb/filesync_protocol.py | FileSyncConnection.ReadUntil | def ReadUntil(self, expected_ids, *finish_ids):
"""Useful wrapper around Read."""
while True:
cmd_id, header, data = self.Read(expected_ids + finish_ids)
yield cmd_id, header, data
if cmd_id in finish_ids:
break | python | def ReadUntil(self, expected_ids, *finish_ids):
while True:
cmd_id, header, data = self.Read(expected_ids + finish_ids)
yield cmd_id, header, data
if cmd_id in finish_ids:
break | [
"def",
"ReadUntil",
"(",
"self",
",",
"expected_ids",
",",
"*",
"finish_ids",
")",
":",
"while",
"True",
":",
"cmd_id",
",",
"header",
",",
"data",
"=",
"self",
".",
"Read",
"(",
"expected_ids",
"+",
"finish_ids",
")",
"yield",
"cmd_id",
",",
"header",
... | Useful wrapper around Read. | [
"Useful",
"wrapper",
"around",
"Read",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/filesync_protocol.py#L240-L246 |
235,783 | google/python-adb | adb/adb_debug.py | Devices | def Devices(args):
"""Lists the available devices.
Mimics 'adb devices' output:
List of devices attached
015DB7591102001A device 1,2
"""
for d in adb_commands.AdbCommands.Devices():
if args.output_port_path:
print('%s\tdevice\t%s' % (
d.serial_number, ','.join(str(p) for p in d.port_path)))
else:
print('%s\tdevice' % d.serial_number)
return 0 | python | def Devices(args):
for d in adb_commands.AdbCommands.Devices():
if args.output_port_path:
print('%s\tdevice\t%s' % (
d.serial_number, ','.join(str(p) for p in d.port_path)))
else:
print('%s\tdevice' % d.serial_number)
return 0 | [
"def",
"Devices",
"(",
"args",
")",
":",
"for",
"d",
"in",
"adb_commands",
".",
"AdbCommands",
".",
"Devices",
"(",
")",
":",
"if",
"args",
".",
"output_port_path",
":",
"print",
"(",
"'%s\\tdevice\\t%s'",
"%",
"(",
"d",
".",
"serial_number",
",",
"','",... | Lists the available devices.
Mimics 'adb devices' output:
List of devices attached
015DB7591102001A device 1,2 | [
"Lists",
"the",
"available",
"devices",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_debug.py#L47-L60 |
235,784 | google/python-adb | adb/adb_debug.py | List | def List(device, device_path):
"""Prints a directory listing.
Args:
device_path: Directory to list.
"""
files = device.List(device_path)
files.sort(key=lambda x: x.filename)
maxname = max(len(f.filename) for f in files)
maxsize = max(len(str(f.size)) for f in files)
for f in files:
mode = (
('d' if stat.S_ISDIR(f.mode) else '-') +
('r' if f.mode & stat.S_IRUSR else '-') +
('w' if f.mode & stat.S_IWUSR else '-') +
('x' if f.mode & stat.S_IXUSR else '-') +
('r' if f.mode & stat.S_IRGRP else '-') +
('w' if f.mode & stat.S_IWGRP else '-') +
('x' if f.mode & stat.S_IXGRP else '-') +
('r' if f.mode & stat.S_IROTH else '-') +
('w' if f.mode & stat.S_IWOTH else '-') +
('x' if f.mode & stat.S_IXOTH else '-'))
t = time.gmtime(f.mtime)
yield '%s %*d %04d-%02d-%02d %02d:%02d:%02d %-*s\n' % (
mode, maxsize, f.size,
t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
maxname, f.filename) | python | def List(device, device_path):
files = device.List(device_path)
files.sort(key=lambda x: x.filename)
maxname = max(len(f.filename) for f in files)
maxsize = max(len(str(f.size)) for f in files)
for f in files:
mode = (
('d' if stat.S_ISDIR(f.mode) else '-') +
('r' if f.mode & stat.S_IRUSR else '-') +
('w' if f.mode & stat.S_IWUSR else '-') +
('x' if f.mode & stat.S_IXUSR else '-') +
('r' if f.mode & stat.S_IRGRP else '-') +
('w' if f.mode & stat.S_IWGRP else '-') +
('x' if f.mode & stat.S_IXGRP else '-') +
('r' if f.mode & stat.S_IROTH else '-') +
('w' if f.mode & stat.S_IWOTH else '-') +
('x' if f.mode & stat.S_IXOTH else '-'))
t = time.gmtime(f.mtime)
yield '%s %*d %04d-%02d-%02d %02d:%02d:%02d %-*s\n' % (
mode, maxsize, f.size,
t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
maxname, f.filename) | [
"def",
"List",
"(",
"device",
",",
"device_path",
")",
":",
"files",
"=",
"device",
".",
"List",
"(",
"device_path",
")",
"files",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"filename",
")",
"maxname",
"=",
"max",
"(",
"len",
"(",
... | Prints a directory listing.
Args:
device_path: Directory to list. | [
"Prints",
"a",
"directory",
"listing",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_debug.py#L63-L89 |
235,785 | google/python-adb | adb/adb_debug.py | Shell | def Shell(device, *command):
"""Runs a command on the device and prints the stdout.
Args:
command: Command to run on the target.
"""
if command:
return device.StreamingShell(' '.join(command))
else:
# Retrieve the initial terminal prompt to use as a delimiter for future reads
terminal_prompt = device.InteractiveShell()
print(terminal_prompt.decode('utf-8'))
# Accept user input in a loop and write that into the interactive shells stdin, then print output
while True:
cmd = input('> ')
if not cmd:
continue
elif cmd == 'exit':
break
else:
stdout = device.InteractiveShell(cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True)
if stdout:
if isinstance(stdout, bytes):
stdout = stdout.decode('utf-8')
print(stdout)
device.Close() | python | def Shell(device, *command):
if command:
return device.StreamingShell(' '.join(command))
else:
# Retrieve the initial terminal prompt to use as a delimiter for future reads
terminal_prompt = device.InteractiveShell()
print(terminal_prompt.decode('utf-8'))
# Accept user input in a loop and write that into the interactive shells stdin, then print output
while True:
cmd = input('> ')
if not cmd:
continue
elif cmd == 'exit':
break
else:
stdout = device.InteractiveShell(cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True)
if stdout:
if isinstance(stdout, bytes):
stdout = stdout.decode('utf-8')
print(stdout)
device.Close() | [
"def",
"Shell",
"(",
"device",
",",
"*",
"command",
")",
":",
"if",
"command",
":",
"return",
"device",
".",
"StreamingShell",
"(",
"' '",
".",
"join",
"(",
"command",
")",
")",
"else",
":",
"# Retrieve the initial terminal prompt to use as a delimiter for future ... | Runs a command on the device and prints the stdout.
Args:
command: Command to run on the target. | [
"Runs",
"a",
"command",
"on",
"the",
"device",
"and",
"prints",
"the",
"stdout",
"."
] | d9b94b2dda555c14674c19806debb8449c0e9652 | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_debug.py#L98-L125 |
235,786 | retext-project/retext | ReText/tab.py | ReTextTab.updateActiveMarkupClass | def updateActiveMarkupClass(self):
'''
Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted.
'''
previousMarkupClass = self.activeMarkupClass
self.activeMarkupClass = find_markup_class_by_name(globalSettings.defaultMarkup)
if self._fileName:
markupClass = get_markup_for_file_name(
self._fileName, return_class=True)
if markupClass:
self.activeMarkupClass = markupClass
if self.activeMarkupClass != previousMarkupClass:
self.highlighter.docType = self.activeMarkupClass.name if self.activeMarkupClass else None
self.highlighter.rehighlight()
self.activeMarkupChanged.emit()
self.triggerPreviewUpdate() | python | def updateActiveMarkupClass(self):
'''
Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted.
'''
previousMarkupClass = self.activeMarkupClass
self.activeMarkupClass = find_markup_class_by_name(globalSettings.defaultMarkup)
if self._fileName:
markupClass = get_markup_for_file_name(
self._fileName, return_class=True)
if markupClass:
self.activeMarkupClass = markupClass
if self.activeMarkupClass != previousMarkupClass:
self.highlighter.docType = self.activeMarkupClass.name if self.activeMarkupClass else None
self.highlighter.rehighlight()
self.activeMarkupChanged.emit()
self.triggerPreviewUpdate() | [
"def",
"updateActiveMarkupClass",
"(",
"self",
")",
":",
"previousMarkupClass",
"=",
"self",
".",
"activeMarkupClass",
"self",
".",
"activeMarkupClass",
"=",
"find_markup_class_by_name",
"(",
"globalSettings",
".",
"defaultMarkup",
")",
"if",
"self",
".",
"_fileName",... | Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted. | [
"Update",
"the",
"active",
"markup",
"class",
"based",
"on",
"the",
"default",
"class",
"and",
"the",
"current",
"filename",
".",
"If",
"the",
"active",
"markup",
"class",
"changes",
"the",
"highlighter",
"is",
"rerun",
"on",
"the",
"input",
"text",
"the",
... | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/tab.py#L145-L168 |
235,787 | retext-project/retext | ReText/tab.py | ReTextTab.detectFileEncoding | def detectFileEncoding(self, fileName):
'''
Detect content encoding of specific file.
It will return None if it can't determine the encoding.
'''
try:
import chardet
except ImportError:
return
with open(fileName, 'rb') as inputFile:
raw = inputFile.read(2048)
result = chardet.detect(raw)
if result['confidence'] > 0.9:
if result['encoding'].lower() == 'ascii':
# UTF-8 files can be falsely detected as ASCII files if they
# don't contain non-ASCII characters in first 2048 bytes.
# We map ASCII to UTF-8 to avoid such situations.
return 'utf-8'
return result['encoding'] | python | def detectFileEncoding(self, fileName):
'''
Detect content encoding of specific file.
It will return None if it can't determine the encoding.
'''
try:
import chardet
except ImportError:
return
with open(fileName, 'rb') as inputFile:
raw = inputFile.read(2048)
result = chardet.detect(raw)
if result['confidence'] > 0.9:
if result['encoding'].lower() == 'ascii':
# UTF-8 files can be falsely detected as ASCII files if they
# don't contain non-ASCII characters in first 2048 bytes.
# We map ASCII to UTF-8 to avoid such situations.
return 'utf-8'
return result['encoding'] | [
"def",
"detectFileEncoding",
"(",
"self",
",",
"fileName",
")",
":",
"try",
":",
"import",
"chardet",
"except",
"ImportError",
":",
"return",
"with",
"open",
"(",
"fileName",
",",
"'rb'",
")",
"as",
"inputFile",
":",
"raw",
"=",
"inputFile",
".",
"read",
... | Detect content encoding of specific file.
It will return None if it can't determine the encoding. | [
"Detect",
"content",
"encoding",
"of",
"specific",
"file",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/tab.py#L296-L317 |
235,788 | retext-project/retext | ReText/tab.py | ReTextTab.openSourceFile | def openSourceFile(self, fileToOpen):
"""Finds and opens the source file for link target fileToOpen.
When links like [test](test) are clicked, the file test.md is opened.
It has to be located next to the current opened file.
Relative paths like [test](../test) or [test](folder/test) are also possible.
"""
if self.fileName:
currentExt = splitext(self.fileName)[1]
basename, ext = splitext(fileToOpen)
if ext in ('.html', '') and exists(basename + currentExt):
self.p.openFileWrapper(basename + currentExt)
return basename + currentExt
if exists(fileToOpen) and get_markup_for_file_name(fileToOpen, return_class=True):
self.p.openFileWrapper(fileToOpen)
return fileToOpen | python | def openSourceFile(self, fileToOpen):
if self.fileName:
currentExt = splitext(self.fileName)[1]
basename, ext = splitext(fileToOpen)
if ext in ('.html', '') and exists(basename + currentExt):
self.p.openFileWrapper(basename + currentExt)
return basename + currentExt
if exists(fileToOpen) and get_markup_for_file_name(fileToOpen, return_class=True):
self.p.openFileWrapper(fileToOpen)
return fileToOpen | [
"def",
"openSourceFile",
"(",
"self",
",",
"fileToOpen",
")",
":",
"if",
"self",
".",
"fileName",
":",
"currentExt",
"=",
"splitext",
"(",
"self",
".",
"fileName",
")",
"[",
"1",
"]",
"basename",
",",
"ext",
"=",
"splitext",
"(",
"fileToOpen",
")",
"if... | Finds and opens the source file for link target fileToOpen.
When links like [test](test) are clicked, the file test.md is opened.
It has to be located next to the current opened file.
Relative paths like [test](../test) or [test](folder/test) are also possible. | [
"Finds",
"and",
"opens",
"the",
"source",
"file",
"for",
"link",
"target",
"fileToOpen",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/tab.py#L443-L458 |
235,789 | retext-project/retext | ReText/mdx_posmap.py | PosMapExtension.extendMarkdown | def extendMarkdown(self, md):
""" Insert the PosMapExtension blockprocessor before any other
extensions to make sure our own markers, inserted by the
preprocessor, are removed before any other extensions get confused
by them.
"""
md.preprocessors.register(PosMapMarkPreprocessor(md), 'posmap_mark', 50)
md.preprocessors.register(PosMapCleanPreprocessor(md), 'posmap_clean', 5)
md.parser.blockprocessors.register(PosMapBlockProcessor(md.parser), 'posmap', 150)
# Monkey patch CodeHilite constructor to remove the posmap markers from
# text before highlighting it
orig_codehilite_init = CodeHilite.__init__
def new_codehilite_init(self, src=None, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
orig_codehilite_init(self, src=src, *args, **kwargs)
CodeHilite.__init__ = new_codehilite_init
# Same for PyMdown Extensions if it is available
if Highlight is not None:
orig_highlight_highlight = Highlight.highlight
def new_highlight_highlight(self, src, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
return orig_highlight_highlight(self, src, *args, **kwargs)
Highlight.highlight = new_highlight_highlight | python | def extendMarkdown(self, md):
md.preprocessors.register(PosMapMarkPreprocessor(md), 'posmap_mark', 50)
md.preprocessors.register(PosMapCleanPreprocessor(md), 'posmap_clean', 5)
md.parser.blockprocessors.register(PosMapBlockProcessor(md.parser), 'posmap', 150)
# Monkey patch CodeHilite constructor to remove the posmap markers from
# text before highlighting it
orig_codehilite_init = CodeHilite.__init__
def new_codehilite_init(self, src=None, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
orig_codehilite_init(self, src=src, *args, **kwargs)
CodeHilite.__init__ = new_codehilite_init
# Same for PyMdown Extensions if it is available
if Highlight is not None:
orig_highlight_highlight = Highlight.highlight
def new_highlight_highlight(self, src, *args, **kwargs):
src = POSMAP_MARKER_RE.sub('', src)
return orig_highlight_highlight(self, src, *args, **kwargs)
Highlight.highlight = new_highlight_highlight | [
"def",
"extendMarkdown",
"(",
"self",
",",
"md",
")",
":",
"md",
".",
"preprocessors",
".",
"register",
"(",
"PosMapMarkPreprocessor",
"(",
"md",
")",
",",
"'posmap_mark'",
",",
"50",
")",
"md",
".",
"preprocessors",
".",
"register",
"(",
"PosMapCleanPreproc... | Insert the PosMapExtension blockprocessor before any other
extensions to make sure our own markers, inserted by the
preprocessor, are removed before any other extensions get confused
by them. | [
"Insert",
"the",
"PosMapExtension",
"blockprocessor",
"before",
"any",
"other",
"extensions",
"to",
"make",
"sure",
"our",
"own",
"markers",
"inserted",
"by",
"the",
"preprocessor",
"are",
"removed",
"before",
"any",
"other",
"extensions",
"get",
"confused",
"by",... | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/mdx_posmap.py#L39-L65 |
235,790 | retext-project/retext | ReText/window.py | ReTextWindow.tabFileNameChanged | def tabFileNameChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
filename of the current tab has changed.
'''
if tab == self.currentTab:
if tab.fileName:
self.setWindowTitle("")
if globalSettings.windowTitleFullPath:
self.setWindowTitle(tab.fileName + '[*]')
self.setWindowFilePath(tab.fileName)
self.tabWidget.setTabText(self.ind, tab.getBaseName())
self.tabWidget.setTabToolTip(self.ind, tab.fileName)
QDir.setCurrent(QFileInfo(tab.fileName).dir().path())
else:
self.setWindowFilePath('')
self.setWindowTitle(self.tr('New document') + '[*]')
canReload = bool(tab.fileName) and not self.autoSaveActive(tab)
self.actionSetEncoding.setEnabled(canReload)
self.actionReload.setEnabled(canReload) | python | def tabFileNameChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
filename of the current tab has changed.
'''
if tab == self.currentTab:
if tab.fileName:
self.setWindowTitle("")
if globalSettings.windowTitleFullPath:
self.setWindowTitle(tab.fileName + '[*]')
self.setWindowFilePath(tab.fileName)
self.tabWidget.setTabText(self.ind, tab.getBaseName())
self.tabWidget.setTabToolTip(self.ind, tab.fileName)
QDir.setCurrent(QFileInfo(tab.fileName).dir().path())
else:
self.setWindowFilePath('')
self.setWindowTitle(self.tr('New document') + '[*]')
canReload = bool(tab.fileName) and not self.autoSaveActive(tab)
self.actionSetEncoding.setEnabled(canReload)
self.actionReload.setEnabled(canReload) | [
"def",
"tabFileNameChanged",
"(",
"self",
",",
"tab",
")",
":",
"if",
"tab",
"==",
"self",
".",
"currentTab",
":",
"if",
"tab",
".",
"fileName",
":",
"self",
".",
"setWindowTitle",
"(",
"\"\"",
")",
"if",
"globalSettings",
".",
"windowTitleFullPath",
":",
... | Perform all UI state changes that need to be done when the
filename of the current tab has changed. | [
"Perform",
"all",
"UI",
"state",
"changes",
"that",
"need",
"to",
"be",
"done",
"when",
"the",
"filename",
"of",
"the",
"current",
"tab",
"has",
"changed",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L462-L482 |
235,791 | retext-project/retext | ReText/window.py | ReTextWindow.tabActiveMarkupChanged | def tabActiveMarkupChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
active markup class of the current tab has changed.
'''
if tab == self.currentTab:
markupClass = tab.getActiveMarkupClass()
dtMarkdown = (markupClass == markups.MarkdownMarkup)
dtMkdOrReST = dtMarkdown or (markupClass == markups.ReStructuredTextMarkup)
self.formattingBox.setEnabled(dtMarkdown)
self.symbolBox.setEnabled(dtMarkdown)
self.actionUnderline.setEnabled(dtMarkdown)
self.actionBold.setEnabled(dtMkdOrReST)
self.actionItalic.setEnabled(dtMkdOrReST) | python | def tabActiveMarkupChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
active markup class of the current tab has changed.
'''
if tab == self.currentTab:
markupClass = tab.getActiveMarkupClass()
dtMarkdown = (markupClass == markups.MarkdownMarkup)
dtMkdOrReST = dtMarkdown or (markupClass == markups.ReStructuredTextMarkup)
self.formattingBox.setEnabled(dtMarkdown)
self.symbolBox.setEnabled(dtMarkdown)
self.actionUnderline.setEnabled(dtMarkdown)
self.actionBold.setEnabled(dtMkdOrReST)
self.actionItalic.setEnabled(dtMkdOrReST) | [
"def",
"tabActiveMarkupChanged",
"(",
"self",
",",
"tab",
")",
":",
"if",
"tab",
"==",
"self",
".",
"currentTab",
":",
"markupClass",
"=",
"tab",
".",
"getActiveMarkupClass",
"(",
")",
"dtMarkdown",
"=",
"(",
"markupClass",
"==",
"markups",
".",
"MarkdownMar... | Perform all UI state changes that need to be done when the
active markup class of the current tab has changed. | [
"Perform",
"all",
"UI",
"state",
"changes",
"that",
"need",
"to",
"be",
"done",
"when",
"the",
"active",
"markup",
"class",
"of",
"the",
"current",
"tab",
"has",
"changed",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L484-L497 |
235,792 | retext-project/retext | ReText/window.py | ReTextWindow.tabModificationStateChanged | def tabModificationStateChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
modification state of the current tab has changed.
'''
if tab == self.currentTab:
changed = tab.editBox.document().isModified()
if self.autoSaveActive(tab):
changed = False
self.actionSave.setEnabled(changed)
self.setWindowModified(changed) | python | def tabModificationStateChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
modification state of the current tab has changed.
'''
if tab == self.currentTab:
changed = tab.editBox.document().isModified()
if self.autoSaveActive(tab):
changed = False
self.actionSave.setEnabled(changed)
self.setWindowModified(changed) | [
"def",
"tabModificationStateChanged",
"(",
"self",
",",
"tab",
")",
":",
"if",
"tab",
"==",
"self",
".",
"currentTab",
":",
"changed",
"=",
"tab",
".",
"editBox",
".",
"document",
"(",
")",
".",
"isModified",
"(",
")",
"if",
"self",
".",
"autoSaveActive"... | Perform all UI state changes that need to be done when the
modification state of the current tab has changed. | [
"Perform",
"all",
"UI",
"state",
"changes",
"that",
"need",
"to",
"be",
"done",
"when",
"the",
"modification",
"state",
"of",
"the",
"current",
"tab",
"has",
"changed",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L499-L509 |
235,793 | retext-project/retext | ReText/window.py | ReTextWindow.getPageSizeByName | def getPageSizeByName(self, pageSizeName):
""" Returns a validated PageSize instance corresponding to the given
name. Returns None if the name is not a valid PageSize.
"""
pageSize = None
lowerCaseNames = {pageSize.lower(): pageSize for pageSize in
self.availablePageSizes()}
if pageSizeName.lower() in lowerCaseNames:
pageSize = getattr(QPagedPaintDevice, lowerCaseNames[pageSizeName.lower()])
return pageSize | python | def getPageSizeByName(self, pageSizeName):
pageSize = None
lowerCaseNames = {pageSize.lower(): pageSize for pageSize in
self.availablePageSizes()}
if pageSizeName.lower() in lowerCaseNames:
pageSize = getattr(QPagedPaintDevice, lowerCaseNames[pageSizeName.lower()])
return pageSize | [
"def",
"getPageSizeByName",
"(",
"self",
",",
"pageSizeName",
")",
":",
"pageSize",
"=",
"None",
"lowerCaseNames",
"=",
"{",
"pageSize",
".",
"lower",
"(",
")",
":",
"pageSize",
"for",
"pageSize",
"in",
"self",
".",
"availablePageSizes",
"(",
")",
"}",
"if... | Returns a validated PageSize instance corresponding to the given
name. Returns None if the name is not a valid PageSize. | [
"Returns",
"a",
"validated",
"PageSize",
"instance",
"corresponding",
"to",
"the",
"given",
"name",
".",
"Returns",
"None",
"if",
"the",
"name",
"is",
"not",
"a",
"valid",
"PageSize",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L995-L1006 |
235,794 | retext-project/retext | ReText/window.py | ReTextWindow.availablePageSizes | def availablePageSizes(self):
""" List available page sizes. """
sizes = [x for x in dir(QPagedPaintDevice)
if type(getattr(QPagedPaintDevice, x)) == QPagedPaintDevice.PageSize]
return sizes | python | def availablePageSizes(self):
sizes = [x for x in dir(QPagedPaintDevice)
if type(getattr(QPagedPaintDevice, x)) == QPagedPaintDevice.PageSize]
return sizes | [
"def",
"availablePageSizes",
"(",
"self",
")",
":",
"sizes",
"=",
"[",
"x",
"for",
"x",
"in",
"dir",
"(",
"QPagedPaintDevice",
")",
"if",
"type",
"(",
"getattr",
"(",
"QPagedPaintDevice",
",",
"x",
")",
")",
"==",
"QPagedPaintDevice",
".",
"PageSize",
"]... | List available page sizes. | [
"List",
"available",
"page",
"sizes",
"."
] | ad70435341dd89c7a74742df9d1f9af70859a969 | https://github.com/retext-project/retext/blob/ad70435341dd89c7a74742df9d1f9af70859a969/ReText/window.py#L1008-L1013 |
235,795 | scikit-tda/kepler-mapper | kmapper/kmapper.py | KeplerMapper.data_from_cluster_id | def data_from_cluster_id(self, cluster_id, graph, data):
"""Returns the original data of each cluster member for a given cluster ID
Parameters
----------
cluster_id : String
ID of the cluster.
graph : dict
The resulting dictionary after applying map()
data : Numpy Array
Original dataset. Accepts both 1-D and 2-D array.
Returns
-------
entries:
rows of cluster member data as Numpy array.
"""
if cluster_id in graph["nodes"]:
cluster_members = graph["nodes"][cluster_id]
cluster_members_data = data[cluster_members]
return cluster_members_data
else:
return np.array([]) | python | def data_from_cluster_id(self, cluster_id, graph, data):
if cluster_id in graph["nodes"]:
cluster_members = graph["nodes"][cluster_id]
cluster_members_data = data[cluster_members]
return cluster_members_data
else:
return np.array([]) | [
"def",
"data_from_cluster_id",
"(",
"self",
",",
"cluster_id",
",",
"graph",
",",
"data",
")",
":",
"if",
"cluster_id",
"in",
"graph",
"[",
"\"nodes\"",
"]",
":",
"cluster_members",
"=",
"graph",
"[",
"\"nodes\"",
"]",
"[",
"cluster_id",
"]",
"cluster_member... | Returns the original data of each cluster member for a given cluster ID
Parameters
----------
cluster_id : String
ID of the cluster.
graph : dict
The resulting dictionary after applying map()
data : Numpy Array
Original dataset. Accepts both 1-D and 2-D array.
Returns
-------
entries:
rows of cluster member data as Numpy array. | [
"Returns",
"the",
"original",
"data",
"of",
"each",
"cluster",
"member",
"for",
"a",
"given",
"cluster",
"ID"
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/kmapper.py#L807-L830 |
235,796 | scikit-tda/kepler-mapper | kmapper/visuals.py | _colors_to_rgb | def _colors_to_rgb(colorscale):
""" Ensure that the color scale is formatted in rgb strings.
If the colorscale is a hex string, then convert to rgb.
"""
if colorscale[0][1][0] == "#":
plotly_colors = np.array(colorscale)[:, 1].tolist()
for k, hexcode in enumerate(plotly_colors):
hexcode = hexcode.lstrip("#")
hex_len = len(hexcode)
step = hex_len // 3
colorscale[k][1] = "rgb" + str(
tuple(int(hexcode[j : j + step], 16) for j in range(0, hex_len, step))
)
return colorscale | python | def _colors_to_rgb(colorscale):
if colorscale[0][1][0] == "#":
plotly_colors = np.array(colorscale)[:, 1].tolist()
for k, hexcode in enumerate(plotly_colors):
hexcode = hexcode.lstrip("#")
hex_len = len(hexcode)
step = hex_len // 3
colorscale[k][1] = "rgb" + str(
tuple(int(hexcode[j : j + step], 16) for j in range(0, hex_len, step))
)
return colorscale | [
"def",
"_colors_to_rgb",
"(",
"colorscale",
")",
":",
"if",
"colorscale",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"==",
"\"#\"",
":",
"plotly_colors",
"=",
"np",
".",
"array",
"(",
"colorscale",
")",
"[",
":",
",",
"1",
"]",
".",
"tolist",
"... | Ensure that the color scale is formatted in rgb strings.
If the colorscale is a hex string, then convert to rgb. | [
"Ensure",
"that",
"the",
"color",
"scale",
"is",
"formatted",
"in",
"rgb",
"strings",
".",
"If",
"the",
"colorscale",
"is",
"a",
"hex",
"string",
"then",
"convert",
"to",
"rgb",
"."
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/visuals.py#L60-L74 |
235,797 | scikit-tda/kepler-mapper | kmapper/visuals.py | build_histogram | def build_histogram(data, colorscale=None, nbins=10):
""" Build histogram of data based on values of color_function
"""
if colorscale is None:
colorscale = colorscale_default
# TODO: we should weave this method of handling colors into the normal build_histogram and combine both functions
colorscale = _colors_to_rgb(colorscale)
h_min, h_max = 0, 1
hist, bin_edges = np.histogram(data, range=(h_min, h_max), bins=nbins)
bin_mids = np.mean(np.array(list(zip(bin_edges, bin_edges[1:]))), axis=1)
histogram = []
max_bucket_value = max(hist)
sum_bucket_value = sum(hist)
for bar, mid in zip(hist, bin_mids):
height = np.floor(((bar / max_bucket_value) * 100) + 0.5)
perc = round((bar / sum_bucket_value) * 100.0, 1)
color = _map_val2color(mid, 0.0, 1.0, colorscale)
histogram.append({"height": height, "perc": perc, "color": color})
return histogram | python | def build_histogram(data, colorscale=None, nbins=10):
if colorscale is None:
colorscale = colorscale_default
# TODO: we should weave this method of handling colors into the normal build_histogram and combine both functions
colorscale = _colors_to_rgb(colorscale)
h_min, h_max = 0, 1
hist, bin_edges = np.histogram(data, range=(h_min, h_max), bins=nbins)
bin_mids = np.mean(np.array(list(zip(bin_edges, bin_edges[1:]))), axis=1)
histogram = []
max_bucket_value = max(hist)
sum_bucket_value = sum(hist)
for bar, mid in zip(hist, bin_mids):
height = np.floor(((bar / max_bucket_value) * 100) + 0.5)
perc = round((bar / sum_bucket_value) * 100.0, 1)
color = _map_val2color(mid, 0.0, 1.0, colorscale)
histogram.append({"height": height, "perc": perc, "color": color})
return histogram | [
"def",
"build_histogram",
"(",
"data",
",",
"colorscale",
"=",
"None",
",",
"nbins",
"=",
"10",
")",
":",
"if",
"colorscale",
"is",
"None",
":",
"colorscale",
"=",
"colorscale_default",
"# TODO: we should weave this method of handling colors into the normal build_histogra... | Build histogram of data based on values of color_function | [
"Build",
"histogram",
"of",
"data",
"based",
"on",
"values",
"of",
"color_function"
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/visuals.py#L212-L236 |
235,798 | scikit-tda/kepler-mapper | kmapper/drawing.py | draw_matplotlib | def draw_matplotlib(g, ax=None, fig=None):
"""Draw the graph using NetworkX drawing functionality.
Parameters
------------
g: graph object returned by ``map``
The Mapper graph as constructed by ``KeplerMapper.map``
ax: matplotlib Axes object
A matplotlib axes object to plot graph on. If none, then use ``plt.gca()``
fig: matplotlib Figure object
A matplotlib Figure object to plot graph on. If none, then use ``plt.figure()``
Returns
--------
nodes: nx node set object list
List of nodes constructed with Networkx ``draw_networkx_nodes``. This can be used to further customize node attributes.
"""
import networkx as nx
import matplotlib.pyplot as plt
fig = fig if fig else plt.figure()
ax = ax if ax else plt.gca()
if not isinstance(g, nx.Graph):
from .adapter import to_networkx
g = to_networkx(g)
# Determine a fine size for nodes
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
area = width * height * fig.dpi
n_nodes = len(g.nodes)
# size of node should be related to area and number of nodes -- heuristic
node_size = np.pi * area / n_nodes
node_r = np.sqrt(node_size / np.pi)
node_edge = node_r / 3
pos = nx.spring_layout(g)
nodes = nx.draw_networkx_nodes(g, node_size=node_size, pos=pos)
edges = nx.draw_networkx_edges(g, pos=pos)
nodes.set_edgecolor("w")
nodes.set_linewidth(node_edge)
plt.axis("square")
plt.axis("off")
return nodes | python | def draw_matplotlib(g, ax=None, fig=None):
import networkx as nx
import matplotlib.pyplot as plt
fig = fig if fig else plt.figure()
ax = ax if ax else plt.gca()
if not isinstance(g, nx.Graph):
from .adapter import to_networkx
g = to_networkx(g)
# Determine a fine size for nodes
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
area = width * height * fig.dpi
n_nodes = len(g.nodes)
# size of node should be related to area and number of nodes -- heuristic
node_size = np.pi * area / n_nodes
node_r = np.sqrt(node_size / np.pi)
node_edge = node_r / 3
pos = nx.spring_layout(g)
nodes = nx.draw_networkx_nodes(g, node_size=node_size, pos=pos)
edges = nx.draw_networkx_edges(g, pos=pos)
nodes.set_edgecolor("w")
nodes.set_linewidth(node_edge)
plt.axis("square")
plt.axis("off")
return nodes | [
"def",
"draw_matplotlib",
"(",
"g",
",",
"ax",
"=",
"None",
",",
"fig",
"=",
"None",
")",
":",
"import",
"networkx",
"as",
"nx",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"fig",
"=",
"fig",
"if",
"fig",
"else",
"plt",
".",
"figure",
"(",
... | Draw the graph using NetworkX drawing functionality.
Parameters
------------
g: graph object returned by ``map``
The Mapper graph as constructed by ``KeplerMapper.map``
ax: matplotlib Axes object
A matplotlib axes object to plot graph on. If none, then use ``plt.gca()``
fig: matplotlib Figure object
A matplotlib Figure object to plot graph on. If none, then use ``plt.figure()``
Returns
--------
nodes: nx node set object list
List of nodes constructed with Networkx ``draw_networkx_nodes``. This can be used to further customize node attributes. | [
"Draw",
"the",
"graph",
"using",
"NetworkX",
"drawing",
"functionality",
"."
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/drawing.py#L11-L65 |
235,799 | scikit-tda/kepler-mapper | kmapper/plotlyviz.py | get_kmgraph_meta | def get_kmgraph_meta(mapper_summary):
""" Extract info from mapper summary to be displayed below the graph plot
"""
d = mapper_summary["custom_meta"]
meta = (
"<b>N_cubes:</b> "
+ str(d["n_cubes"])
+ " <b>Perc_overlap:</b> "
+ str(d["perc_overlap"])
)
meta += (
"<br><b>Nodes:</b> "
+ str(mapper_summary["n_nodes"])
+ " <b>Edges:</b> "
+ str(mapper_summary["n_edges"])
+ " <b>Total samples:</b> "
+ str(mapper_summary["n_total"])
+ " <b>Unique_samples:</b> "
+ str(mapper_summary["n_unique"])
)
return meta | python | def get_kmgraph_meta(mapper_summary):
d = mapper_summary["custom_meta"]
meta = (
"<b>N_cubes:</b> "
+ str(d["n_cubes"])
+ " <b>Perc_overlap:</b> "
+ str(d["perc_overlap"])
)
meta += (
"<br><b>Nodes:</b> "
+ str(mapper_summary["n_nodes"])
+ " <b>Edges:</b> "
+ str(mapper_summary["n_edges"])
+ " <b>Total samples:</b> "
+ str(mapper_summary["n_total"])
+ " <b>Unique_samples:</b> "
+ str(mapper_summary["n_unique"])
)
return meta | [
"def",
"get_kmgraph_meta",
"(",
"mapper_summary",
")",
":",
"d",
"=",
"mapper_summary",
"[",
"\"custom_meta\"",
"]",
"meta",
"=",
"(",
"\"<b>N_cubes:</b> \"",
"+",
"str",
"(",
"d",
"[",
"\"n_cubes\"",
"]",
")",
"+",
"\" <b>Perc_overlap:</b> \"",
"+",
"str",
"(... | Extract info from mapper summary to be displayed below the graph plot | [
"Extract",
"info",
"from",
"mapper",
"summary",
"to",
"be",
"displayed",
"below",
"the",
"graph",
"plot"
] | d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/plotlyviz.py#L403-L424 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.