Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def notify_observers(self, which=None, min_priority=None): if self._update_on: if which is None: which = self if min_priority is None: [callble(self, which=which) for _, _, callble in self.observers] ...
[ "\n Notifies all observers. Which is the element, which kicked off this\n notification loop. The first argument will be self, the second `which`.\n\n .. note::\n \n notifies only observers with priority p > min_priority!\n \n :param min_priority: only notify...
Please provide a description of the function:def constrain_fixed(self, value=None, warning=True, trigger_parent=True): if value is not None: self[:] = value #index = self.unconstrain() index = self._add_to_index_operations(self.constraints, np.empty(0), __fixed__, warning) ...
[ "\n Constrain this parameter to be fixed to the current value it carries.\n\n This does not override the previous constraints, so unfixing will\n restore the constraint set before fixing.\n\n :param warning: print a warning for overwriting constraints.\n " ]
Please provide a description of the function:def unconstrain_fixed(self): unconstrained = self.unconstrain(__fixed__) self._highest_parent_._set_unfixed(self, unconstrained) #if self._default_constraint_ is not None: # return self.constrain(self._default_constraint_) ...
[ "\n This parameter will no longer be fixed.\n\n If there was a constraint on this parameter when fixing it,\n it will be constraint with that previous constraint.\n " ]
Please provide a description of the function:def constrain(self, transform, warning=True, trigger_parent=True): if isinstance(transform, Transformation): self.param_array[...] = transform.initialize(self.param_array) elif transform == __fixed__: return self.fix(warning=w...
[ "\n :param transform: the :py:class:`paramz.transformations.Transformation`\n to constrain the this parameter to.\n :param warning: print a warning if re-constraining parameters.\n\n Constrain the parameter to the given\n :py:class:`paramz.transformations.Transfo...
Please provide a description of the function:def constrain_positive(self, warning=True, trigger_parent=True): self.constrain(Logexp(), warning=warning, trigger_parent=trigger_parent)
[ "\n :param warning: print a warning if re-constraining parameters.\n\n Constrain this parameter to the default positive constraint.\n " ]
Please provide a description of the function:def constrain_negative(self, warning=True, trigger_parent=True): self.constrain(NegativeLogexp(), warning=warning, trigger_parent=trigger_parent)
[ "\n :param warning: print a warning if re-constraining parameters.\n\n Constrain this parameter to the default negative constraint.\n " ]
Please provide a description of the function:def constrain_bounded(self, lower, upper, warning=True, trigger_parent=True): self.constrain(Logistic(lower, upper), warning=warning, trigger_parent=trigger_parent)
[ "\n :param lower, upper: the limits to bound this parameter to\n :param warning: print a warning if re-constraining parameters.\n\n Constrain this parameter to lie within the given range.\n " ]
Please provide a description of the function:def load(file_or_path): from pickle import UnpicklingError _python3 = True try: import cPickle as pickle _python3 = False except ImportError: #python3 import pickle try: if _python3: strcl = str ...
[ "\n Load a previously pickled model, using `m.pickle('path/to/file.pickle)'`\n\n :param file_name: path/to/file.pickle\n " ]
Please provide a description of the function:def checkgrad(self, verbose=0, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): # Make sure we always call the gradcheck on the highest parent # This ensures the assumption of the highest parent to hold the fixes # In the checkgrad function we...
[ "\n Check the gradient of this parameter with respect to the highest parent's\n objective function.\n This is a three point estimate of the gradient, wiggling at the parameters\n with a stepsize step.\n The check passes if either the ratio or the difference between numerical and\n...
Please provide a description of the function:def opt(self, x_init, f_fp=None, f=None, fp=None): tnc_rcstrings = ['Local minimum', 'Converged', 'XConverged', 'Maximum number of f evaluations reached', 'Line search failed', 'Function is constant'] assert f_fp != None, "TNC requires ...
[ "\n Run the TNC optimizer\n\n " ]
Please provide a description of the function:def opt(self, x_init, f_fp=None, f=None, fp=None): rcstrings = ['Converged', 'Maximum number of f evaluations reached', 'Error'] assert f_fp != None, "BFGS requires f_fp" opt_dict = {} if self.xtol is not None: print("WA...
[ "\n Run the optimizer\n\n " ]
Please provide a description of the function:def opt(self, x_init, f_fp=None, f=None, fp=None): rcstrings = ['','Maximum number of iterations exceeded', 'Gradient and/or function calls not changing'] opt_dict = {} if self.xtol is not None: print("WARNING: bfgs doesn't have ...
[ "\n Run the optimizer\n\n " ]
Please provide a description of the function:def opt(self, x_init, f_fp=None, f=None, fp=None): statuses = ['Converged', 'Maximum number of function evaluations made', 'Maximum number of iterations reached'] opt_dict = {} if self.xtol is not None: opt_dict['xtol'] = self.x...
[ "\n The simplex optimizer does not require gradients.\n " ]
Please provide a description of the function:def combine_inputs(self, args, kw, ignore_args): "Combines the args and kw in a unique way, such that ordering of kwargs does not lead to recompute" inputs= args + tuple(c[1] for c in sorted(kw.items(), key=lambda x: x[0])) # REMOVE the ignored argume...
[]
Please provide a description of the function:def prepare_cache_id(self, combined_args_kw): "get the cacheid (conc. string of argument self.ids in order)" cache_id = "".join(self.id(a) for a in combined_args_kw) return cache_id
[]
Please provide a description of the function:def ensure_cache_length(self): "Ensures the cache is within its limits and has one place free" if len(self.order) == self.limit: # we have reached the limit, so lets release one element cache_id = self.order.popleft() combi...
[]
Please provide a description of the function:def add_to_cache(self, cache_id, inputs, output): self.inputs_changed[cache_id] = False self.cached_outputs[cache_id] = output self.order.append(cache_id) self.cached_inputs[cache_id] = inputs for a in inputs: if a...
[ "This adds cache_id to the cache, with inputs and output" ]
Please provide a description of the function:def on_cache_changed(self, direct, which=None): for what in [direct, which]: ind_id = self.id(what) _, cache_ids = self.cached_input_ids.get(ind_id, [None, []]) for cache_id in cache_ids: self.inputs_change...
[ "\n A callback funtion, which sets local flags when the elements of some cached inputs change\n\n this function gets 'hooked up' to the inputs when we cache them, and upon their elements being changed we update here.\n " ]
Please provide a description of the function:def reset(self): [a().remove_observer(self, self.on_cache_changed) if (a() is not None) else None for [a, _] in self.cached_input_ids.values()] self.order = collections.deque() self.cached_inputs = {} # point from cache_ids to a list of [in...
[ "\n Totally reset the cache\n " ]
Please provide a description of the function:def disable_caching(self): "Disable the cache of this object. This also removes previously cached results" self.caching_enabled = False for c in self.values(): c.disable_cacher()
[]
Please provide a description of the function:def enable_caching(self): "Enable the cache of this object." self.caching_enabled = True for c in self.values(): c.enable_cacher()
[]
Please provide a description of the function:def SCG(f, gradf, x, optargs=(), maxiters=500, max_f_eval=np.inf, xtol=None, ftol=None, gtol=None): if xtol is None: xtol = 1e-6 if ftol is None: ftol = 1e-6 if gtol is None: gtol = 1e-5 sigma0 = 1.0e-7 fold = f(x, *optargs) ...
[ "\n Optimisation through Scaled Conjugate Gradients (SCG)\n\n f: the objective function\n gradf : the gradient function (should return a 1D np.ndarray)\n x : the initial condition\n\n Returns\n x the optimal value for x\n flog : a list of all the objective values\n function_eval number of fn...
Please provide a description of the function:def remove(self, priority, observer, callble): self.flush() for i in range(len(self) - 1, -1, -1): p,o,c = self[i] if priority==p and observer==o and callble==c: del self._poc[i]
[ "\n Remove one observer, which had priority and callble.\n " ]
Please provide a description of the function:def add(self, priority, observer, callble): #if observer is not None: ins = 0 for pr, _, _ in self: if priority > pr: break ins += 1 self._poc.insert(ins, (priority, weakref.ref(observer), callb...
[ "\n Add an observer with priority and callble\n " ]
Please provide a description of the function:def properties_for(self, index): return vectorize(lambda i: [prop for prop in self.properties() if i in self[prop]], otypes=[list])(index)
[ "\n Returns a list of properties, such that each entry in the list corresponds\n to the element of the index given.\n\n Example:\n let properties: 'one':[1,2,3,4], 'two':[3,5,6]\n\n >>> properties_for([2,3,5])\n [['one'], ['one', 'two'], ['two']]\n " ]
Please provide a description of the function:def properties_dict_for(self, index): props = self.properties_for(index) prop_index = extract_properties_to_index(index, props) return prop_index
[ "\n Return a dictionary, containing properties as keys and indices as index\n Thus, the indices for each constraint, which is contained will be collected as\n one dictionary\n\n Example:\n let properties: 'one':[1,2,3,4], 'two':[3,5,6]\n\n >>> properties_dict_for([2,3,5])\n...
Please provide a description of the function:def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs): if self.is_fixed or self.size == 0: print('nothing to optimize') return if not self.up...
[ "\n Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors.\n\n kwargs are passed to the optimizer. They can be:\n\n :param max_iters: maximum number of function evaluations\n :type max_iters: int\n :messages: True: Display messages d...
Please provide a description of the function:def optimize_restarts(self, num_restarts=10, robust=False, verbose=True, parallel=False, num_processes=None, **kwargs): initial_length = len(self.optimization_runs) initial_parameters = self.optimizer_array.copy() if parallel: #pragma: no co...
[ "\n Perform random restarts of the model, and set the model to the best\n seen solution.\n\n If the robust flag is set, exceptions raised during optimizations will\n be handled silently. If _all_ runs fail, the model is reset to the\n existing parameter values.\n\n \\*\\*k...
Please provide a description of the function:def _grads(self, x): try: # self._set_params_transformed(x) self.optimizer_array = x self.obj_grads = self._transform_gradients(self.objective_function_gradients()) self._fail_count = 0 except (LinAlgEr...
[ "\n Gets the gradients from the likelihood and the priors.\n\n Failures are handled robustly. The algorithm will try several times to\n return the gradients, and will raise the original exception if\n the objective cannot be computed.\n\n :param x: the parameters of the model.\n ...
Please provide a description of the function:def _objective(self, x): try: self.optimizer_array = x obj = self.objective_function() self._fail_count = 0 except (LinAlgError, ZeroDivisionError, ValueError):#pragma: no cover if self._fail_count >= s...
[ "\n The objective function passed to the optimizer. It combines\n the likelihood and the priors.\n\n Failures are handled robustly. The algorithm will try several times to\n return the objective, and will raise the original exception if\n the objective cannot be computed.\n\n ...
Please provide a description of the function:def _checkgrad(self, target_param=None, verbose=False, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): if not self._model_initialized_: import warnings warnings.warn("This model has not been initialized, try model.inititialize_model()...
[ "\n Check the gradient of the ,odel by comparing to a numerical\n estimate. If the verbose flag is passed, individual\n components are tested (and printed)\n\n :param verbose: If True, print a \"full\" checking of each parameter\n :type verbose: bool\n :param step: The siz...
Please provide a description of the function:def _repr_html_(self): model_details = [['<b>Model</b>', self.name + '<br>'], ['<b>Objective</b>', '{}<br>'.format(float(self.objective_function()))], ["<b>Number of Parameters</b>", '{}<br>'.format(self.size...
[ "Representation of the model in html for notebook display.", "<style type=\"text/css\">\n.pd{\n font-family: \"Courier New\", Courier, monospace !important;\n width: 100%;\n padding: 3px;\n}\n</style>\\n" ]
Please provide a description of the function:def add_index_operation(self, name, operations): if name not in self._index_operations: self._add_io(name, operations) else: raise AttributeError("An index operation with the name {} was already taken".format(name))
[ "\n Add index operation with name to the operations given.\n\n raises: attribute error if operations exist.\n " ]
Please provide a description of the function:def _disconnect_parent(self, *args, **kw): for name, iop in list(self._index_operations.items()): iopc = iop.copy() iop.clear() self.remove_index_operation(name) self.add_index_operation(name, iopc) #se...
[ "\n From Parentable:\n disconnect the parent and set the new constraints to constr\n " ]
Please provide a description of the function:def _offset_for(self, param): if param.has_parent(): p = param._parent_._get_original(param) if p in self.parameters: return reduce(lambda a,b: a + b.size, self.parameters[:p._parent_index_], 0) return self...
[ "\n Return the offset of the param inside this parameterized object.\n This does not need to account for shaped parameters, as it\n basically just sums up the parameter sizes which come before param.\n " ]
Please provide a description of the function:def _raveled_index_for(self, param): from ..param import ParamConcatenation if isinstance(param, ParamConcatenation): return np.hstack((self._raveled_index_for(p) for p in param.params)) return param._raveled_index() + self._offse...
[ "\n get the raveled index for a param\n that is an int array, containing the indexes for the flattened\n param inside this parameterized logic.\n\n !Warning! be sure to call this method on the highest parent of a hierarchy,\n as it uses the fixes to do its work\n " ]
Please provide a description of the function:def _raveled_index_for_transformed(self, param): ravi = self._raveled_index_for(param) if self._has_fixes(): fixes = self._fixes_ ### Transformed indices, handling the offsets of previous fixes transformed = (np.r_...
[ "\n get the raveled index for a param for the transformed parameter array\n (optimizer array).\n\n that is an int array, containing the indexes for the flattened\n param inside this parameterized logic.\n\n !Warning! be sure to call this method on the highest parent of a hierarchy...
Please provide a description of the function:def _parent_changed(self, parent): from .index_operations import ParameterIndexOperationsView #if getattr(self, "_in_init_"): #import ipdb;ipdb.set_trace() #self.constraints.update(param.constraints, start) #self.p...
[ "\n From Parentable:\n Called when the parent changed\n\n update the constraints and priors view, so that\n constraining is automized for the parent.\n " ]
Please provide a description of the function:def _add_to_index_operations(self, which, reconstrained, what, warning): if warning and reconstrained.size > 0: # TODO: figure out which parameters have changed and only print those logging.getLogger(self.name).warning("reconstraining...
[ "\n Helper preventing copy code.\n This adds the given what (transformation, prior etc) to parameter index operations which.\n reconstrained are reconstrained indices.\n warn when reconstraining parameters if warning is True.\n TODO: find out which parameters have changed specific...
Please provide a description of the function:def _remove_from_index_operations(self, which, transforms): if len(transforms) == 0: transforms = which.properties() removed = np.empty((0,), dtype=int) for t in list(transforms): unconstrained = which.remove(t, self._...
[ "\n Helper preventing copy code.\n Remove given what (transform prior etc) from which param index ops.\n " ]
Please provide a description of the function:def copy(self): from .lists_and_dicts import ObserverList memo = {} memo[id(self)] = self memo[id(self.observers)] = ObserverList() return self.__deepcopy__(memo)
[ "\n Make a copy. This means, we delete all observers and return a copy of this\n array. It will still be an ObsAr!\n " ]
Please provide a description of the function:def update_model(self, updates=None): if updates is None: return self._update_on assert isinstance(updates, bool), "updates are either on (True) or off (False)" p = getattr(self, '_highest_parent_', None) def turn_updates(...
[ "\n Get or set, whether automatic updates are performed. When updates are\n off, the model might be in a non-working state. To make the model work\n turn updates on again.\n\n :param bool|None updates:\n\n bool: whether to do updates\n None: get the current update s...
Please provide a description of the function:def trigger_update(self, trigger_parent=True): if not self.update_model() or (hasattr(self, "_in_init_") and self._in_init_): #print "Warning: updates are off, updating the model will do nothing" return self._trigger_params_ch...
[ "\n Update the model from the current state.\n Make sure that updates are on, otherwise this\n method will do nothing\n\n :param bool trigger_parent: Whether to trigger the parent, after self has updated\n " ]
Please provide a description of the function:def optimizer_array(self): if self.__dict__.get('_optimizer_copy_', None) is None or self.size != self._optimizer_copy_.size: self._optimizer_copy_ = np.empty(self.size) if not self._optimizer_copy_transformed: self._optimize...
[ "\n Array for the optimizer to work on.\n This array always lives in the space for the optimizer.\n Thus, it is untransformed, going from Transformations.\n\n Setting this array, will make sure the transformed parameters for this model\n will be set accordingly. It has to be set w...
Please provide a description of the function:def optimizer_array(self, p): f = None if self.has_parent() and self.constraints[__fixed__].size != 0: f = np.ones(self.size).astype(bool) f[self.constraints[__fixed__]] = FIXED elif self._has_fixes(): f = ...
[ "\n Make sure the optimizer copy does not get touched, thus, we only want to\n set the values *inside* not the array itself.\n\n Also we want to update param_array in here.\n " ]
Please provide a description of the function:def _trigger_params_changed(self, trigger_parent=True): [p._trigger_params_changed(trigger_parent=False) for p in self.parameters if not p.is_fixed] self.notify_observers(None, None if trigger_parent else -np.inf)
[ "\n First tell all children to update,\n then update yourself.\n\n If trigger_parent is True, we will tell the parent, otherwise not.\n " ]
Please provide a description of the function:def _transform_gradients(self, g): #py3 fix #[np.put(g, i, c.gradfactor(self.param_array[i], g[i])) for c, i in self.constraints.iteritems() if c != __fixed__] [np.put(g, i, c.gradfactor(self.param_array[i], g[i])) for c, i in self.constraint...
[ "\n Transform the gradients by multiplying the gradient factor for each\n constraint to it.\n " ]
Please provide a description of the function:def parameter_names(self, add_self=False, adjust_for_printing=False, recursive=True, intermediate=False): if adjust_for_printing: adjust = adjust_name_for_printing else: adjust = lambda x: x names = [] if intermediate or (not recursiv...
[ "\n Get the names of all parameters of this model or parameter. It starts\n from the parameterized object you are calling this method on.\n\n Note: This does not unravel multidimensional parameters,\n use parameter_names_flat to unravel parameters!\n\n :param bool add_self: ...
Please provide a description of the function:def parameter_names_flat(self, include_fixed=False): name_list = [] for p in self.flattened_parameters: name = p.hierarchy_name() if p.size > 1: name_list.extend(["{}[{!s}]".format(name, i) for i in p._indices(...
[ "\n Return the flattened parameter names for all subsequent parameters\n of this parameter. We do not include the name for self here!\n\n If you want the names for fixed parameters as well in this list,\n set include_fixed to True.\n if not hasattr(obj, 'cache'):\n ...
Please provide a description of the function:def randomize(self, rand_gen=None, *args, **kwargs): if rand_gen is None: rand_gen = np.random.normal # first take care of all parameters (from N(0,1)) x = rand_gen(size=self._size_transformed(), *args, **kwargs) updates =...
[ "\n Randomize the model.\n Make this draw from the rand_gen if one exists, else draw random normal(0,1)\n\n :param rand_gen: np random number generator which takes args and kwargs\n :param flaot loc: loc parameter for random number generator\n :param float scale: scale parameter f...
Please provide a description of the function:def _propagate_param_grad(self, parray, garray): #if self.param_array.size != self.size: # self._param_array_ = np.empty(self.size, dtype=np.float64) #if self.gradient.size != self.size: # self._gradient_array_ = np.empty(self.s...
[ "\n For propagating the param_array and gradient_array.\n This ensures the in memory view of each subsequent array.\n\n 1.) connect param_array of children to self.param_array\n 2.) tell all children to propagate further\n " ]
Please provide a description of the function:def initialize_parameter(self): #logger.debug("connecting parameters") self._highest_parent_._notify_parent_change() self._highest_parent_._connect_parameters() #logger.debug("calling parameters changed") self._highest_parent_._connec...
[ "\n Call this function to initialize the model, if you built it without initialization.\n\n This HAS to be called manually before optmizing or it will be causing\n unexpected behaviour, if not errors!\n " ]
Please provide a description of the function:def param_array(self): if (self.__dict__.get('_param_array_', None) is None) or (self._param_array_.size != self.size): self._param_array_ = np.empty(self.size, dtype=np.float64) return self._param_array_
[ "\n Array representing the parameters of this class.\n There is only one copy of all parameters in memory, two during optimization.\n\n !WARNING!: setting the parameter array MUST always be done in memory:\n m.param_array[:] = m_copy.param_array\n " ]
Please provide a description of the function:def unfixed_param_array(self): if self.constraints[__fixed__].size !=0: fixes = np.ones(self.size).astype(bool) fixes[self.constraints[__fixed__]] = FIXED return self._param_array_[fixes] else: return s...
[ "\n Array representing the parameters of this class.\n There is only one copy of all parameters in memory, two during optimization.\n\n !WARNING!: setting the parameter array MUST always be done in memory:\n m.param_array[:] = m_copy.param_array\n " ]
Please provide a description of the function:def traverse(self, visit, *args, **kwargs): if not self.__visited: visit(self, *args, **kwargs) self.__visited = True self._traverse(visit, *args, **kwargs) self.__visited = False
[ "\n Traverse the hierarchy performing `visit(self, *args, **kwargs)`\n at every node passed by downwards. This function includes self!\n\n See *visitor pattern* in literature. This is implemented in pre-order fashion.\n\n Example::\n\n #Collect all children:\n\n chi...
Please provide a description of the function:def traverse_parents(self, visit, *args, **kwargs): if self.has_parent(): self.__visited = True self._parent_.traverse_parents(visit, *args, **kwargs) self._parent_.traverse(visit, *args, **kwargs) self.__visit...
[ "\n Traverse the hierarchy upwards, visiting all parents and their children except self.\n See \"visitor pattern\" in literature. This is implemented in pre-order fashion.\n\n Example:\n\n parents = []\n self.traverse_parents(parents.append)\n print parents\n " ]
Please provide a description of the function:def save(self, filename, ftype='HDF5'): # pragma: no coverage from ..param import Param def gather_params(self, plist): if isinstance(self,Param): plist.append(self) plist = [] self.traverse(gather_params,...
[ "\n Save all the model parameters into a file (HDF5 by default).\n\n This is not supported yet. We are working on having a consistent,\n human readable way of saving and loading GPy models. This only\n saves the parameter array to a hdf5 file. In order\n to load the model again, u...
Please provide a description of the function:def phi(self, Xpred, degrees=None): assert Xpred.shape[1] == self.X.shape[1], "Need to predict with same shape as training data." if degrees is None: degrees = range(self.basis.degree+1) tmp_phi = np.empty((len(degrees), Xpred.sha...
[ "\n Compute the design matrix for this model\n using the degrees given by the index array\n in degrees\n\n :param array-like Xpred: inputs to compute the design matrix for\n :param array-like degrees: array of degrees to use [default=range(self.degree+1)]\n :returns array-l...
Please provide a description of the function:def pickle(self, f, protocol=-1): try: #Py2 import cPickle as pickle if isinstance(f, basestring): with open(f, 'wb') as f: pickle.dump(self, f, protocol) else: pickle.du...
[ "\n :param f: either filename or open file object to write to.\n if it is an open buffer, you have to make sure to close\n it properly.\n :param protocol: pickling protocol to use, python-pickle for details.\n " ]
Please provide a description of the function:def copy(self, memo=None, which=None): #raise NotImplementedError, "Copy is not yet implemented, TODO: Observable hierarchy" if memo is None: memo = {} import copy # the next part makes sure that we do not include parents ...
[ "\n Returns a (deep) copy of the current parameter handle.\n\n All connections to parents of the copy will be cut.\n\n :param dict memo: memo for deepcopy\n :param Parameterized which: parameterized object which started the copy process [default: self]\n " ]
Please provide a description of the function:def consolidate_dependencies(needs_ipython, child_program, requirement_files, manual_dependencies): # We get the logger here because it's not defined at module level logger = logging.getLogger('fades') if needs_ipython: ...
[ "Parse files, get deps and merge them. Deps read later overwrite those read earlier." ]
Please provide a description of the function:def decide_child_program(args_executable, args_child_program): # We get the logger here because it's not defined at module level logger = logging.getLogger('fades') if args_executable: # if --exec given, check that it's just the executable name, ...
[ "Decide which the child program really is (if any)." ]
Please provide a description of the function:def detect_inside_virtualenv(prefix, real_prefix, base_prefix): if real_prefix is not None: return True if base_prefix is None: return False # if prefix is different than base_prefix, it's a venv return prefix != base_prefix
[ "Tell if fades is running inside a virtualenv.\n\n The params 'real_prefix' and 'base_prefix' may be None.\n\n This is copied from pip code (slightly modified), see\n\n https://github.com/pypa/pip/blob/281eb61b09d87765d7c2b92f6982b3fe76ccb0af/\n pip/locations.py#L39\n " ]
Please provide a description of the function:def _get_normalized_args(parser): env = os.environ if '_' in env and env['_'] != sys.argv[0] and len(sys.argv) >= 1 and " " in sys.argv[1]: return parser.parse_args(shlex.split(sys.argv[1]) + sys.argv[2:]) else: return parser.parse_args()
[ "Return the parsed command line arguments.\n\n Support the case when executed from a shebang, where all the\n parameters come in sys.argv[1] in a single string separated\n by spaces (in this case, the third parameter is what is being\n executed)\n " ]
Please provide a description of the function:def go(): parser = argparse.ArgumentParser(prog='PROG', epilog=help_epilog, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-V', '--version', action='store_true', help="show ...
[ "Make the magic happen.", "Handle signals received by parent process, send them to child.\n\n The only exception is CTRL-C, that is generated *from* the interactive\n interpreter (it's a keyboard combination!), so we swallow it for the\n interpreter to not see it twice.\n " ]
Please provide a description of the function:def set_up(verbose, quiet): logger = logging.getLogger('fades') logger.setLevel(logging.DEBUG) # select logging level according to user desire; also use a simpler # formatting for non-verbose logging if verbose: log_level = logging.DEBUG ...
[ "Set up the logging." ]
Please provide a description of the function:def emit(self, record): if not self._already_saluted: self._already_saluted = True self._logger.info(SALUTATION) super().emit(record)
[ "Call father's emit, but salute first (just once)." ]
Please provide a description of the function:def parse_fade_requirement(text): text = text.strip() if "::" in text: repo_raw, requirement = text.split("::", 1) try: repo = {'pypi': REPO_PYPI, 'vcs': REPO_VCS}[repo_raw] except KeyError: logger.warning("Not un...
[ "Return a requirement and repo from the given text, already parsed and converted." ]
Please provide a description of the function:def _parse_content(fh): content = iter(fh) deps = {} for line in content: # quickly discard most of the lines if 'fades' not in line: continue # discard other string with 'fades' that isn't a comment if '#' not i...
[ "Parse the content of a script to find marked dependencies." ]
Please provide a description of the function:def _parse_docstring(fh): find_fades = re.compile(r'\b(fades)\b:').search for line in fh: if line.startswith("'"): quote = "'" break if line.startswith('"'): quote = '"' break else: ret...
[ "Parse the docstrings of a script to find marked dependencies." ]
Please provide a description of the function:def _parse_requirement(iterable): deps = {} for line in iterable: line = line.strip() if not line or line[0] == '#': continue parsed_req = parse_fade_requirement(line) if parsed_req is None: continue ...
[ "Actually parse the requirements, from file or manually specified." ]
Please provide a description of the function:def _read_lines(filepath): with open(filepath, 'rt', encoding='utf8') as fh: for line in fh: line = line.strip() if line.startswith("-r"): logger.debug("Reading deps from nested requirement file: %s", line) ...
[ "Read a req file to a list to support nested requirement files." ]
Please provide a description of the function:def create_venv(requested_deps, interpreter, is_current, options, pip_options): # create virtualenv env = _FadesEnvBuilder() env_path, env_bin_path, pip_installed = env.create_env(interpreter, is_current, options) venv_data = {} venv_data['env_path']...
[ "Create a new virtualvenv with the requirements of this script." ]
Please provide a description of the function:def destroy_venv(env_path, venvscache=None): # remove the venv itself in disk logger.debug("Destroying virtualenv at: %s", env_path) shutil.rmtree(env_path, ignore_errors=True) # remove venv from cache if venvscache is not None: venvscache.r...
[ "Destroy a venv." ]
Please provide a description of the function:def create_with_virtualenv(self, interpreter, virtualenv_options): args = ['virtualenv', '--python', interpreter, self.env_path] args.extend(virtualenv_options) if not self.pip_installed: args.insert(3, '--no-pip') try: ...
[ "Create a virtualenv using the virtualenv lib." ]
Please provide a description of the function:def create_env(self, interpreter, is_current, options): if is_current: # apply pyvenv options pyvenv_options = options['pyvenv_options'] if "--system-site-packages" in pyvenv_options: self.system_site_packa...
[ "Create the virtualenv and return its info." ]
Please provide a description of the function:def store_usage_stat(self, venv_data, cache): with open(self.stat_file_path, 'at') as f: self._write_venv_usage(f, venv_data)
[ "Log an usage record for venv_data." ]
Please provide a description of the function:def clean_unused_venvs(self, max_days_to_keep): with filelock(self.stat_file_lock): now = datetime.utcnow() venvs_dict = self._get_compacted_dict_usage_from_file() for venv_uuid, usage_date in venvs_dict.copy().items(): ...
[ "Compact usage stats and remove venvs.\n\n This method loads the complete file usage in memory, for every venv compact all records in\n one (the lastest), updates this info for every env deleted and, finally, write the entire\n file to disk.\n\n If something failed during this steps, usa...
Please provide a description of the function:def logged_exec(cmd): logger = logging.getLogger('fades.exec') logger.debug("Executing external command: %r", cmd) p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) stdout = [] for line in p...
[ "Execute a command, redirecting the output to the log." ]
Please provide a description of the function:def _get_specific_dir(dir_type): if SNAP_BASEDIR_NAME in os.environ: logger.debug("Getting base dir information from SNAP_BASEDIR_NAME env var.") direct = os.path.join(os.environ[SNAP_BASEDIR_NAME], dir_type) else: try: basedi...
[ "Get a specific directory, using some XDG base, with sensible default." ]
Please provide a description of the function:def _get_interpreter_info(interpreter=None): if interpreter is None: # If interpreter is None by default returns the current interpreter data. major, minor = sys.version_info[:2] executable = sys.executable else: args = [interpret...
[ "Return the interpreter's full path using pythonX.Y format." ]
Please provide a description of the function:def get_interpreter_version(requested_interpreter): logger.debug('Getting interpreter version for: %s', requested_interpreter) current_interpreter = _get_interpreter_info() logger.debug('Current interpreter is %s', current_interpreter) if requested_inter...
[ "Return a 'sanitized' interpreter and indicates if it is the current one." ]
Please provide a description of the function:def check_pypi_updates(dependencies): dependencies_up_to_date = [] for dependency in dependencies.get('pypi', []): # get latest version from PyPI api try: latest_version = get_latest_version_number(dependency.project_name) exc...
[ "Return a list of dependencies to upgrade." ]
Please provide a description of the function:def _pypi_head_package(dependency): if dependency.specs: _, version = dependency.specs[0] url = BASE_PYPI_URL_WITH_VERSION.format(name=dependency.project_name, version=version) else: url = BASE_PYPI_URL.format(name=dependency.project_name...
[ "Hit pypi with a http HEAD to check if pkg_name exists." ]
Please provide a description of the function:def check_pypi_exists(dependencies): for dependency in dependencies.get('pypi', []): logger.debug("Checking if %r exists in PyPI", dependency) try: exists = _pypi_head_package(dependency) except Exception as error: log...
[ "Check if the indicated dependencies actually exists in pypi." ]
Please provide a description of the function:def download_remote_script(url): temp_fh = tempfile.NamedTemporaryFile('wt', encoding='utf8', suffix=".py", delete=False) downloader = _ScriptDownloader(url) logger.info( "Downloading remote script from %r using (%r downloader) to %r", url, d...
[ "Download the content of a remote script to a local temp file." ]
Please provide a description of the function:def dump_to_log(self, logger): logger.error("Execution ended in %s for cmd %s", self._retcode, self._cmd) for line in self._collected_stdout: logger.error(STDOUT_LOG_PREFIX + line)
[ "Send the cmd info and collected stdout to logger." ]
Please provide a description of the function:def _decide(self): netloc = parse.urlparse(self.url).netloc name = self.NETLOCS.get(netloc, 'raw') return name
[ "Find out which method should be applied to download that URL." ]
Please provide a description of the function:def get(self): method_name = "_download_" + self.name method = getattr(self, method_name) return method()
[ "Get the script content from the URL using the decided downloader." ]
Please provide a description of the function:def _download_raw(self, url=None): if url is None: url = self.url req = request.Request(url, headers=self.HEADERS_PLAIN) return request.urlopen(req).read().decode("utf8")
[ "Download content from URL directly." ]
Please provide a description of the function:def _download_linkode(self): # build the API url linkode_id = self.url.split("/")[-1] if linkode_id.startswith("#"): linkode_id = linkode_id[1:] url = "https://linkode.org/api/1/linkodes/" + linkode_id req = reque...
[ "Download content from Linkode pastebin." ]
Please provide a description of the function:def _download_pastebin(self): paste_id = self.url.split("/")[-1] url = "https://pastebin.com/raw/" + paste_id return self._download_raw(url)
[ "Download content from Pastebin itself." ]
Please provide a description of the function:def _download_gist(self): parts = parse.urlparse(self.url) url = "https://gist.github.com" + parts.path + "/raw" return self._download_raw(url)
[ "Download content from github's pastebin." ]
Please provide a description of the function:def get_version(): with open('fades/_version.py') as fh: m = re.search("\(([^']*)\)", fh.read()) if m is None: raise ValueError("Unrecognized version in 'fades/_version.py'") return m.groups()[0].replace(', ', '.')
[ "Retrieves package version from the file." ]
Please provide a description of the function:def initialize_options(self): install.initialize_options(self) # leave the proper script according to the platform script = SCRIPT_WIN if sys.platform == "win32" else SCRIPT_REST self.distribution.scripts = [script]
[ "Run parent initialization and then fix the scripts var." ]
Please provide a description of the function:def run(self): install.run(self) # man directory if self._custom_man_dir is not None: if not os.path.exists(self._custom_man_dir): os.makedirs(self._custom_man_dir) shutil.copy("man/fades.1", self._cus...
[ "Run parent install, and then save the man file." ]
Please provide a description of the function:def finalize_options(self): install.finalize_options(self) if self.prefix is None: # no place for man page (like in a 'snap') man_dir = None else: man_dir = os.path.join(self.prefix, "share", "man", "man1")...
[ "Alter the installation path." ]
Please provide a description of the function:def options_from_file(args): logger.debug("updating options from config files") updated_from_file = [] for config_file in CONFIG_FILES: logger.debug("updating from: %s", config_file) parser = ConfigParser() parser.read(config_file) ...
[ "Get a argparse.Namespace and return it updated with options from config files.\n\n Config files will be parsed with priority equal to his order in CONFIG_FILES.\n " ]
Please provide a description of the function:def _venv_match(self, installed, requirements): if not requirements: # special case for no requirements, where we can't actually # check anything: the venv is useful if nothing installed too return None if installed else [...
[ "Return True if what is installed satisfies the requirements.\n\n This method has multiple exit-points, but only for False (because\n if *anything* is not satisified, the venv is no good). Only after\n all was checked, and it didn't exit, the venv is ok so return True.\n " ]
Please provide a description of the function:def _match_by_uuid(self, current_venvs, uuid): for venv_str in current_venvs: venv = json.loads(venv_str) env_path = venv.get('metadata', {}).get('env_path') _, env_uuid = os.path.split(env_path) if env_uuid ==...
[ "Select a venv matching exactly by uuid." ]