code stringlengths 1 18.2k |
|---|
def _mixup( self, ps ): """Private method to mix up a list of values in-place using a Fisher-Yates shuffle (see https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). :param ps: the array :returns: the array, shuffled in-place""" for i in range(len(ps) - 1, 0, -1): j = int(numpy.random.random() * i) temp = ps[i] ps[i] = ... |
def runExperiment( self, e ): """Run the experiment across the parameter space in parallel using all the engines in the cluster. This method returns immediately. The experiments are run asynchronously, with the points in the parameter space being explored randomly so that intermediate retrievals of results are more rep... |
try to make intermediate (incomplete) result # sets more representative of the overall result set ps = self._mixup(space) try: # connect to the cluster self.open() # submit an experiment at each point in the parameter space to the cluster view = self._client.load_balanced_view() jobs = [] for p in ps: jobs.extend((view... |
def updateResults( self ): """Update our results within any pending results that have completed since we last retrieved results from the cluster. :returns: the number of pending results completed at this call""" # we do all the tests for pending results against the notebook directly, # as the corresponding methods on s... |
well # values come back from Client.result_status() in # varying degrees of list-nesting, which LabNotebook.addResult() # handles itself nb.addResult(r, j) # commit changes to the notebook nb.commit() # purge the completed job from the cluster self._client.purge_hub_results(j) # record that we retrieved the results for... |
def _availableResultsFraction( self ): """Private method to return the fraction of results available, as a real number between 0 and 1. This does not update the results fetched from the cluster. :returns: the fraction of available results""" tr = self.notebook().numberOfResults() + self.notebook().numberOfPendingResult... |
def wait( self, timeout = -1 ): """Wait for all pending results to be finished. If timeout is set, return after this many seconds regardless. :param timeout: timeout period in seconds (defaults to forever) :returns: True if all the results completed""" # we can't use ipyparallel.Client.wait() for this, because that # m... |
unfortunate, but understandable given the typical use cases for # Client objects. # # Instead. we have to code around a little busily. The ClusterLab.WaitingTime # global sets the latency for waiting, and we repeatedly wait for this amount # of time before updating the results. The latency value essentially controls # ... |
-1: # wait for the default waiting period dt = self.WaitingTime else: # wait for the default waiting period or until the end of the timeout. # whichever comes first if (timeout - timeWaited) < self.WaitingTime: dt = timeout - timeWaited else: dt = self.WaitingTime # sleep for a while time.sleep(dt) timeWaited = timeWai... |
def _abortJobs( self, js ): """Private method to abort a set of jobs. :param js: the job ids to be aborted""" self.open() self._client.abort(jobs = js) self.close() |
def cancelPendingResultsFor( self, params ): """Cancel any results pending for experiments at the given point in the parameter space. :param params: the experimental parameters""" # grab the result job ids jobs = self.pendingResultsFor(params) if len(jobs) > 0: # abort in the cluster self._abortJobs(jobs) # cancel in t... |
def cancelAllPendingResults( self ): """Cancel all pending results.""" # grab all the pending job ids jobs = self.pendingResults() if len(jobs) > 0: # abort in the cluster self._abortJobs(jobs) # cancel in the notebook self.notebook().cancelAllPendingResults() |
def sort(self, column_name=None, reverse=False): """ Sort rows in this table, preserving a record of how that sorting is done in TableFu.options['sorted_by'] """ if not column_name and self.options.has_key('sorted_by'): column_name = self.options['sorted_by'].keys()[0] if column_name not in self.default_columns: raise ... |
def filter(self, func=None, **query): """ Tables can be filtered in one of two ways: - Simple keyword arguments return rows where values match *exactly* - Pass in a function and return rows where that function evaluates to True In either case, a new TableFu instance is returned """ if callable(func): result = filter(fu... |
def facet_by(self, column): """ Faceting creates new TableFu instances with rows matching each possible value. """ faceted_spreadsheets = {} for row in self.rows: if row[column]: col = row[column].value if faceted_spreadsheets.has_key(col): faceted_spreadsheets[col].append(row.cells) else: faceted_spreadsheets[col] = [... |
def map(self, func, *columns): """ Map a function to rows, or to given columns """ if not columns: return map(func, self.rows) else: values = (self.values(column) for column in columns) result = [map(func, v) for v in values] if len(columns) == 1: return result[0] else: return result |
def csv(self, **kwargs): """ Export this table as a CSV """ out = StringIO() writer = csv.DictWriter(out, self.columns, **kwargs) writer.writerow(dict(zip(self.columns, self.columns))) writer.writerows(dict(row.items()) for row in self.rows) return out |
def from_file(fn, **options): """ Creates a new TableFu instance from a file or path """ if hasattr(fn, 'read'): return TableFu(fn, **options) with open(fn) as f: return TableFu(f, **options) |
def from_url(url, **options): """ Downloads the contents of a given URL and loads it into a new TableFu instance """ resp = urllib2.urlopen(url) return TableFu(resp, **options) |
def get(self, column_name, default=None): """ Return the Datum for column_name, or default. """ if column_name in self.table.default_columns: index = self.table.default_columns.index(column_name) return Datum(self.cells[index], self.row_num, column_name, self.table) return default |
def main(argString=None): """The main function. The purpose of this module is to plot Eigenvectors provided by the Eigensoft software. Here are the steps of this module: 1. Reads the Eigenvector (:py:func:`read_eigenvalues`). 2. Plots the Scree Plot (:py:func:`create_scree_plot`). """ # Getting and checking the options... |
def create_scree_plot(data, o_filename, options): """Creates the scree plot. :param data: the eigenvalues. :param o_filename: the name of the output files. :param options: the options. :type data: numpy.ndarray :type o_filename: str :type options: argparse.Namespace """ # Importing plt mpl.use("Agg") import matplotlib.... |
10), textcoords="offset points", ha="left", va="bottom", bbox=dict(boxstyle="round,pad=0.5", fc="#FFFFFF")) # Next plot the cumulative values axes[1].set_title(("Cumulative explained variance " "(max={:.3f})".format(np.sum(data))), weight="bold") axes[1].set_xlabel("Component") axes[1].set_ylabel("Cumulative explained ... |
def read_eigenvalues(i_filename): """Reads the eigenvalues from EIGENSOFT results. :param i_filename: the name of the input file. :type i_filename: str :returns: a :py:class:`numpy.ndarray` array containing the eigenvalues. """ # The data is the first line of the result file (should begin with # "#eigvals" data = None ... |
def check_args(args): """Checks the arguments and options. :param args: an object containing the options and arguments of the program. :type args: :py:class:`argparse.Namespace` :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class... |
def parse_args(argString=None): """Parses the command line options and arguments. :returns: A :py:class:`argparse.Namespace` object created by the :py:mod:`argparse` module. It contains the values of the different options. ====================== ====== ================================ Options Type Description =========... |
def dump_json(token_dict, dump_path): """write json data to file """ if sys.version > '3': with open(dump_path, 'w', encoding='utf-8') as output_file: json.dump(token_dict, output_file, indent=4) else: with open(dump_path, 'w') as output_file: json.dump(token_dict, output_file, indent=4) |
def parse(): """parse arguments supplied by cmd-line """ parser = argparse.ArgumentParser( description='BabelFy Entity Tagger', formatter_class=argparse.RawTextHelpFormatter ) group = parser.add_mutually_exclusive_group() group.add_argument( '-t', '--text', help='text to be annotated by BabelFy API', metavar='', ) grou... |
def main(self, x): """ Transposed FIR structure """ self.acc[0] = x * self.TAPS[-1] for i in range(1, len(self.acc)): self.acc[i] = self.acc[i - 1] + x * self.TAPS[len(self.TAPS) - 1 - i] self.out = self.acc[-1] return self.out |
def pg_version(using=None): """ Return tuple with PostgreSQL version of a specific connection :type using: str :param using: Connection name :rtype: tuple :return: PostgreSQL version """ connection = get_connection(using) cursor = connection.cursor() cursor.execute('SHOW server_version') row = cursor.fetchone() return ... |
def batch_qs(qs, batch_size=1000): """ Returns a (start, end, total, queryset) tuple for each batch in the given queryset. Usage: # Make sure to order your queryset article_qs = Article.objects.order_by('id') for start, end, total, qs in batch_qs(article_qs): print "Now processing %s - %s of %s" % (start + 1, end, tota... |
def list(self, **kwds): """ Endpoint: /tags/list.json Returns a list of Tag objects. """ tags = self._client.get("/tags/list.json", **kwds)["result"] tags = self._result_to_list(tags) return [Tag(self._client, tag) for tag in tags] |
def create(self, tag, **kwds): """ Endpoint: /tag/create.json Creates a new tag. Returns True if successful. Raises a TroveboxError if not. """ return self._client.post("/tag/create.json", tag=tag, **kwds)["result"] |
def delete(self, tag, **kwds): """ Endpoint: /tag/<id>/delete.json Deletes a tag. Returns True if successful. Raises a TroveboxError if not. """ return self._client.post("/tag/%s/delete.json" % self._quote_url(self._extract_id(tag)), **kwds)["result"] |
def update(self, tag, **kwds): """ Endpoint: /tag/<id>/update.json Updates a tag with the specified parameters. Returns the updated tag object. """ result = self._client.post("/tag/%s/update.json" % self._quote_url(self._extract_id(tag)), **kwds)["result"] return Tag(self._client, result) |
def record(self, action, props=None, path=KISSmetrics.RECORD_PATH, resp=False): """Record event for identity with any properties. :param action: event performed :param props: any additional data to include :type props: dict :param resp: indicate whether to return response :type resp: boolean :returns: an HTTP response ... |
def set(self, data, path=KISSmetrics.SET_PATH, resp=False): """Set a properties provided in `data` for identity. :param data: key-value pairs to associate with identity :type data: dict :param path: endpoint path; defaults to ``KISSmetrics.SET_PATH`` :param resp: indicate whether to return response :type resp: boolean ... |
def alias(self, name, alias_to, path=KISSmetrics.ALIAS_PATH, resp=False): """Map `name` to `alias_to`; actions done by one resolve to other. :param name: consider as same individual as ``alias_to`` :param alias_to: consider an alias of ``name`` :param path: endpoint path; defaults to ``KISSmetrics.ALIAS_PATH`` :param r... |
def PMF(samples, y): """ Compute the probability mass function. The set of samples defines a probability density P(y), which is computed using a kernel density estimator. From :math:`P(y)` we define: :math:`\mathrm{pmf}(p) = \int_{P(y)<p} P(y) dy` This is the cumulative distribution function expressed as a function of ... |
####. | .####| ####. | ..#####| #####.. | ....#######| #######.... | .###########| ###########. +---------------------+-------------------------------> y t ^ M(p) ^ M(y) | | 1| +++ 1| + | + | + + | ++++++++ | + + | ++ | ++ ++ | ++ | ++ ++ |+++ |+++ +++ +---------------------> p +---------------------> y 0 Parameters --... |
= max(samples) + 10*numpy.sqrt(kernel.covariance[0, 0]) y_ = numpy.linspace(mn, mx, len(y)*10) # Compute the probabilities at each of the extended samples ps_ = kernel(y_) # Compute the masses ms = [] for yi in y: # compute the probability at this y value p = kernel(yi) if p <= max(ps_)*1e-5: m = 0. else: # Find out wh... |
sum(kernel.integrate_box_1d(a, b) for a, b in zip(starts, stops)) ms.append(m) return numpy.array(ms) except numpy.linalg.LinAlgError: return numpy.zeros_like(y) |
def compute_pmf(fsamps, y, **kwargs): """ Compute the pmf defined by fsamps at each x for each y. Parameters ---------- fsamps: 2D array-like array of function samples, as returned by :func:`fgivenx.compute_samples` y: 1D array-like y values to evaluate the PMF at parallel, tqdm_kwargs: optional see docstring for :func... |
def weld_range(start, stop, step): """Create a vector for the range parameters above. Parameters ---------- start : int stop : int or WeldObject Could be the lazily computed length of a WeldObject vec. step : int Returns ------- WeldObject Representation of this computation. """ if isinstance(stop, WeldObject): obj_id,... |
def weld_compare(array, scalar, operation, weld_type): """Applies comparison operation between each element in the array with scalar. Parameters ---------- array : numpy.ndarray or WeldObject Input data. scalar : {int, float, str, bool, bytes_} Value to compare with; must be same type as the values in the array. If not... |
no casting! requires Weld fix weld_template = """map( {array}, |a: {type}| a {operation} {cast} )""" weld_obj.weld_code = weld_template.format(array=obj_id, operation=operation, type=weld_type, cast=cast) return weld_obj |
def weld_filter(array, weld_type, bool_array): """Returns a new array only with the elements with a corresponding True in bool_array. Parameters ---------- array : numpy.ndarray or WeldObject Input data. weld_type : WeldType Type of the elements in the input array. bool_array : numpy.ndarray or WeldObject Array of bool... |
def weld_slice(array, weld_type, slice_, default_start=0, default_stop=0, default_step=1): """Returns a new array according to the given slice. Parameters ---------- array : numpy.ndarray or WeldObject 1-dimensional array. weld_type : WeldType Type of the elements in the input array. slice_ : slice Subset to return. As... |
type=weld_type, slice_start='{}L'.format(slice_.start), slice_stop='{}L'.format(slice_.stop - slice_.start), slice_step='{}L'.format(slice_.step)) return weld_obj |
def weld_tail(array, length, n): """Return the last n elements. Parameters ---------- array : numpy.ndarray or WeldObject Array to select from. length : int or WeldObject Length of the array. Int if already known can simplify the computation. n : int How many values. Returns ------- WeldObject Representation of the com... |
def weld_array_op(array1, array2, result_type, operation): """Applies operation to each pair of elements in the arrays. Their lengths and types are assumed to be the same. Parameters ---------- array1 : numpy.ndarray or WeldObject Input array. array2 : numpy.ndarray or WeldObject Second input array. result_type : WeldT... |
merge(b, {action}) ) )""" weld_obj.weld_code = weld_template.format(array1=obj_id1, array2=obj_id2, type=result_type, action=action) return weld_obj |
def weld_invert(array): """Inverts a bool array. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Assumed to be bool data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = """result( for({array}, appender[bool], |b: appe... |
def weld_iloc_int(array, index): """Retrieves the value at index. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Assumed to be bool data. index : int The array index from which to retrieve value. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_obj... |
def weld_iloc_indices(array, weld_type, indices): """Retrieve the values at indices. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Assumed to be bool data. weld_type : WeldType The WeldType of the array data. indices : numpy.ndarray or WeldObject The indices to lookup. Returns ------- WeldObject... |
def weld_iloc_indices_with_missing(array, weld_type, indices): """Retrieve the values at indices. Indices greater than array length get replaced with a corresponding-type missing value literal. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Assumed to be bool data. weld_type : WeldType The WeldTy... |
def weld_element_wise_op(array, weld_type, scalar, operation): """Applies operation to each element in the array with scalar. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of each element in the input array. scalar : {int, float, str, bool, bytes_} Value to compare wit... |
weld_template.format(array=obj_id, type=weld_type, action=action) return weld_obj |
def weld_sort(arrays, weld_types, readable_text, ascending=True): """Sort the arrays. Parameters ---------- arrays : list of (numpy.ndarray or WeldObject) Arrays to put in a struct. weld_types : list of WeldType The Weld types of the arrays in the same order. readable_text : str Explanatory string to add in the Weld pl... |
def weld_unique(array, weld_type): """Return the unique elements of the array. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(arr... |
def weld_drop_duplicates(arrays, weld_types, subset_indices, keep): """Return the unique elements of the array. Parameters ---------- arrays : list of (numpy.ndarray or WeldObject) Input arrays. weld_types : list of WeldType Type of elements in the input arrays. subset_indices : list of int Indices of which arrays to c... |
value_merges = struct_of('e.${e}', value_indices) # flattening the struct of struct results = [] key_i = 0 value_i = 0 for i in all_indices: if i in subset_indices: results.append('e.${}.${}'.format(0, key_i)) key_i += 1 else: results.append('e.${}.${}'.format(1, value_i)) value_i += 1 res = '{{{}}}'.format(', '.join(r... |
def weld_replace(array, weld_type, this, to): """Replaces 'this' values to 'to' value. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of the data in the array. this : {int, float, str, bool, bytes} Scalar to replace. to : {int, float, str, bool, bytes} Scalar to replace... |
def weld_udf(weld_template, mapping): """Create WeldObject to encode weld_template code given mapping. Parameters ---------- weld_template : str Weld code to encode. mapping : dict Which substitutions to make in the weld_template. Returns ------- WeldObject Representation of this computation. """ weld_obj = create_empt... |
def option_parser(): """Option Parser to give various options.""" usage = ''' $ ./crawler -d5 <url> Here in this case it goes till depth of 5 and url is target URL to start crawling. ''' version = "2.0.0" parser = optparse.OptionParser(usage=usage, version=version) parser.add_option("-l", "--links", action="store_true"... |
async def getlinks(url): """Get Links from the Linkfetcher class.""" page = Linkfetcher(url) await page.linkfetch() for i, url in enumerate(page): return (i, url) |
async def main(): """ Main class.""" opts, args = option_parser() url = args[0] if opts.links: getlinks(url) raise SystemExit(0) depth = opts.depth sTime = time.time() webcrawler = Webcrawler(url, depth) webcrawler.crawl() eTime = time.time() tTime = eTime - sTime print("CRAWLER STARTED:") print("%s, will crawl upto de... |
def _get_mapping(): """ Finds and loads gulp's rev-manifest.json file. In default, this is looking for rev-manifest.json file places in your STATIC_ROOT. Can be overriden to a specific location by setting DJANGO_GULP_REV_PATH. """ global _STATIC_MAPPING if _STATIC_MAPPING is None: manifest_path = getattr(settings, 'DJA... |
def production_url(path, original): """ For a production environment (DEBUG=False), replaces original path created by Django's {% static %} template tag with relevant path from our mapping. """ mapping = _get_mapping() if mapping: if path in mapping: return original.replace(path, mapping[path]) return original else: re... |
def static_rev(path): """ Gets a joined path with the STATIC_URL setting, and applies revisioning depending on DEBUG setting. Usage:: {% load rev %} {% static_rev "css/base.css" %} Example:: {% static_rev "css/base.css" %} On DEBUG=True will return: /static/css/base.css?d9wdjs On DEBUG=False will return: /static/css/ba... |
def _build_object_table(self): '''Builds the object table for each RDDL type.''' types = self.domain.types objects = dict(self.non_fluents.objects) self.object_table = dict() for name, value in self.domain.types: if value == 'object': objs = objects[name] idx = { obj: i for i, obj in enumerate(objs) } self.object_table... |
def _build_fluent_table(self): '''Builds the fluent table for each RDDL pvariable.''' self.fluent_table = collections.OrderedDict() for name, size in zip(self.domain.non_fluent_ordering, self.non_fluent_size): non_fluent = self.domain.non_fluents[name] self.fluent_table[name] = (non_fluent, size) for name, size in zip(... |
def non_fluent_variables(self) -> FluentParamsList: '''Returns the instantiated non-fluents in canonical order. Returns: Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name and a list of instantiated fluents represented as strings. ''' fluents = self.domain.non_fluents ordering = self.domain.non_fluent_ord... |
def state_fluent_variables(self) -> FluentParamsList: '''Returns the instantiated state fluents in canonical order. Returns: Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name and a list of instantiated fluents represented as strings. ''' fluents = self.domain.state_fluents ordering = self.domain.state_fl... |
def interm_fluent_variables(self) -> FluentParamsList: '''Returns the instantiated intermediate fluents in canonical order. Returns: Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name and a list of instantiated fluents represented as strings. ''' fluents = self.domain.intermediate_fluents ordering = self.... |
def action_fluent_variables(self) -> FluentParamsList: '''Returns the instantiated action fluents in canonical order. Returns: Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name and a list of instantiated fluents represented as strings. ''' fluents = self.domain.action_fluents ordering = self.domain.actio... |
def non_fluent_size(self) -> Sequence[Sequence[int]]: '''The size of each non-fluent in canonical order. Returns: Sequence[Sequence[int]]: A tuple of tuple of integers representing the shape and size of each non-fluent. ''' fluents = self.domain.non_fluents ordering = self.domain.non_fluent_ordering return self._fluent... |
def state_size(self) -> Sequence[Sequence[int]]: '''The size of each state fluent in canonical order. Returns: Sequence[Sequence[int]]: A tuple of tuple of integers representing the shape and size of each fluent. ''' fluents = self.domain.state_fluents ordering = self.domain.state_fluent_ordering return self._fluent_si... |
def action_size(self) -> Sequence[Sequence[int]]: '''The size of each action fluent in canonical order. Returns: Sequence[Sequence[int]]: A tuple of tuple of integers representing the shape and size of each fluent. ''' fluents = self.domain.action_fluents ordering = self.domain.action_fluent_ordering return self._fluen... |
def interm_size(self)-> Sequence[Sequence[int]]: '''The size of each intermediate fluent in canonical order. Returns: Sequence[Sequence[int]]: A tuple of tuple of integers representing the shape and size of each fluent. ''' fluents = self.domain.intermediate_fluents ordering = self.domain.interm_fluent_ordering return ... |
def state_range_type(self) -> Sequence[str]: '''The range type of each state fluent in canonical order. Returns: Sequence[str]: A tuple of range types representing the range of each fluent. ''' fluents = self.domain.state_fluents ordering = self.domain.state_fluent_ordering return self._fluent_range_type(fluents, order... |
def action_range_type(self) -> Sequence[str]: '''The range type of each action fluent in canonical order. Returns: Sequence[str]: A tuple of range types representing the range of each fluent. ''' fluents = self.domain.action_fluents ordering = self.domain.action_fluent_ordering return self._fluent_range_type(fluents, o... |
def interm_range_type(self) -> Sequence[str]: '''The range type of each intermediate fluent in canonical order. Returns: Sequence[str]: A tuple of range types representing the range of each fluent. ''' fluents = self.domain.intermediate_fluents ordering = self.domain.interm_fluent_ordering return self._fluent_range_typ... |
def _fluent_range_type(cls, fluents, ordering) -> Sequence[str]: '''Returns the range types of `fluents` following the given `ordering`. Returns: Sequence[str]: A tuple of range types representing the range of each fluent. ''' range_types = [] for name in ordering: fluent = fluents[name] range_type = fluent.range range... |
def _fluent_params(self, fluents, ordering) -> FluentParamsList: '''Returns the instantiated `fluents` for the given `ordering`. For each fluent in `fluents`, it instantiates each parameter type w.r.t. the contents of the object table. Returns: Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name and a list... |
def _fluent_size(self, fluents, ordering) -> Sequence[Sequence[int]]: '''Returns the sizes of `fluents` following the given `ordering`. Returns: Sequence[Sequence[int]]: A tuple of tuple of integers representing the shape and size of each fluent. ''' shapes = [] for name in ordering: fluent = fluents[name] shape = self... |
def _param_types_to_shape(self, param_types: Optional[str]) -> Sequence[int]: '''Returns the fluent shape given its `param_types`.''' param_types = [] if param_types is None else param_types shape = tuple(self.object_table[ptype]['size'] for ptype in param_types) return shape |
def t_DATE(t): r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})' day = int(t.lexer.lexmatch.group('day')) month = int(t.lexer.lexmatch.group('month')) year = int(t.lexer.lexmatch.group('year')) t.value = date(year, month, day) return t |
def t_FIELD(t): r'[A-Za-z_][\w_]*' if t.value in u_ops: t.type = 'U_OP' elif t.value in b_ops: t.type = 'B_OP' return t |
def main(self, c): """ :type c: Complex :rtype: Sfix """ conj = self.conjugate.main(c) mult = self.complex_mult.main(c, conj) angle = self.angle.main(mult) self.y = self.GAIN_SFIX * angle return self.y |
def find_ctx(elt): """Find a Pointcut ctx which is a class/instance related to input function/method. :param elt: elt from where find a ctx. :return: elt ctx. None if no ctx available or if elt is a None method. """ result = None if ismethod(elt): result = elt.__self__ if result is None and PY2: result = elt.im_class e... |
def base_ctx(ctx): """Get base ctx. :param ctx: initial ctx. :return: base ctx.""" result = None if isclass(ctx): result = getattr(ctx, '__base__', None) if result is None: mro = getmro(ctx) if len(mro) > 1: result = mro[1] else: result = ctx.__class__ return result |
def super_method(name, ctx): """Get super ctx method and ctx where name matches with input name. :param name: method name to find in super ctx. :param ctx: initial method ctx. :return: method in super ctx and super ctx. :rtype: tuple""" result = None, None # get class ctx if isclass(ctx): _ctx = ctx first_mro = 1 else:... |
def _apply_interception( target, interception_fn, ctx=None, _globals=None ): """Apply interception on input target and return the final target. :param Callable target: target on applying the interception_fn. :param function interception_fn: interception function to apply on target :param ctx: target ctx (instance or cl... |
= find_ctx(elt=target) # if target is a builtin if isbuiltin(target) or getmodule(target) is builtins: # update builtin function reference in module with wrapper module = getmodule(target) found = False # check for found function if module is not None: # update all references by value for name, _ in getmembers( module,... |
else: # get target name if isclass(target): # if target is a class, get constructor name target_name = _get_function(target).__name__ else: # else get target name target_name = target.__name__ # get the right intercepted intercepted = getattr(ctx, target_name) # in case of method if ismethod(intercepted): # in creating... |
setattr(interception_fn, _INTERCEPTED, intercepted) # set intercepted ctx if ctx is not None: setattr(interception_fn, _INTERCEPTED_CTX, ctx) interception_fn.__globals__[_INTERCEPTED] = intercepted interception_fn.__globals__[_INTERCEPTION] = interception if _globals is not None: interception_fn.__globals__.update(_glo... |
def _unapply_interception(target, ctx=None): """Unapply interception on input target in cleaning it. :param routine target: target from where removing an interception function. is_joinpoint(target) must be True. :param ctx: target ctx. """ # try to get the right ctx if ctx is None: ctx = find_ctx(elt=target) # get prev... |
getmembers(module): if member is target: setattr(module, name, intercepted) found = True # if no reference found, raise an Exception if not found: raise JoinpointError( "Impossible to unapply interception on not modifiable element \ {0}. Must be contained in module {1}".format(target, module) ) elif ctx is None: # get ... |
# recover intercepted recover = True else: # get joinpoint_function joinpoint_function = _get_function(target) # get base function if is_intercepted(base_interception): base_intercepted, _ = get_intercepted(base_interception) else: base_intercepted = _get_function(base_interception) # is interception inherited ? if bas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.