text
stringlengths
78
104k
score
float64
0
0.18
def _query_zendesk(self, endpoint, object_type, *endpoint_args, **endpoint_kwargs): """ Query Zendesk for items. If an id or list of ids are passed, attempt to locate these items in the relevant cache. If they cannot be found, or no ids are passed, execute a call to Zendesk to retrieve...
0.005389
def matrix(self): """The 4x4 matrix representation of this rotation""" result = np.identity(4, float) result[0:3, 0:3] = self.r return result
0.011561
def strip_headers(text): """Remove lines that are part of the Project Gutenberg header or footer. Note: this function is a port of the C++ utility by Johannes Krugel. The original version of the code can be found at: http://www14.in.tum.de/spp1307/src/strip_headers.cpp Args: text (unicode):...
0.000579
def login(self, request, extra_context=None): """ Displays the login form for the given HttpRequest. """ from django.contrib.auth.views import login context = { 'title': _('Log in'), 'app_path': request.get_full_path(), REDIRECT_FIELD_NAME: req...
0.003053
def parse_mcast_grps(family, grp_attr): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L64. Positional arguments: family -- genl_family class instance. grp_attr -- nlattr class instance. Returns: 0 on success or a negative error code. """ remaining = c_int() i...
0.002222
def write_record(self, event_str): """Writes a serialized event to file.""" header = struct.pack('Q', len(event_str)) header += struct.pack('I', masked_crc32c(header)) footer = struct.pack('I', masked_crc32c(event_str)) self._writer.write(header + event_str + footer)
0.006515
def _initialize_trackbars(self): """ Initialize trackbars by discovering ``block_matcher``'s parameters. """ for parameter in self.block_matcher.parameter_maxima.keys(): maximum = self.block_matcher.parameter_maxima[parameter] if not maximum: maxim...
0.003361
def magic_read(infile, data=None, return_keys=False, verbose=False): """ Reads a Magic template file, returns data in a list of dictionaries. Parameters ___________ Required: infile : the MagIC formatted tab delimited data file first line contains 'tab' in the firs...
0.00093
def _import_serializer_class(self, location): """ Resolves a dot-notation string to serializer class. <app>.<SerializerName> will automatically be interpreted as: <app>.serializers.<SerializerName> """ pieces = location.split(".") class_name = pieces.pop() ...
0.003922
def get_stats_participation(self): """ :calls: `GET /repos/:owner/:repo/stats/participation <http://developer.github.com/v3/repos/statistics/#get-the-weekly-commit-count-for-the-repo-owner-and-everyone-else>`_ :rtype: None or :class:`github.StatsParticipation.StatsParticipation` """ ...
0.006431
def create_mutation_inputs(service): """ Args: service : The service being created by the mutation Returns: (list) : a list of all of the fields availible for the service, with the required ones respected. """ # grab the default list of field summaries...
0.001876
def _handle_break(self, node, scope, ctxt, stream): """Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling break") raise errors.InterpBreak()
0.007353
def subdivide_to_size(vertices, faces, max_edge, max_iter=10): """ Subdivide a mesh until every edge is shorter than a specified length. Will return a triangle soup, not a nicely structured mesh. Parameters ------------ vert...
0.000438
def kibana_config(self): """ config kibana :return: """ uncomment("/etc/kibana/kibana.yml", "#server.host:", use_sudo=True) sed('/etc/kibana/kibana.yml', 'server.host:.*', 'server.host: "{0}"'.format(env.host_string), use_sudo=True) sudo('systemctl st...
0.004219
def frost_days(tasmin, freq='YS'): r"""Frost days index Number of days where daily minimum temperatures are below 0℃. Parameters ---------- tasmin : xarray.DataArray Minimum daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.D...
0.002528
def getScreen(self,screen_data=None): """This function fills screen_data with the RAW Pixel data screen_data MUST be a numpy array of uint8/int8. This could be initialized like so: screen_data = np.array(w*h,dtype=np.uint8) Notice, it must be width*height in size also If it is No...
0.009067
def _create_placeholder_objects(self): """ PDF objects #1 through #3 are typically saved for the Zeroth, Catalog, and Pages Objects. This program will save the numbers, but outputs the individual Page and Content objects first. The actual Catalog and Pages objects are cal...
0.004292
def _find_passwords(self, service, username, deleting=False): """Get password of the username for the service """ passwords = [] service = self._safe_string(service) username = self._safe_string(username) for attrs_tuple in (('username', 'service'), ('user', 'domain')): ...
0.001835
def predict_distributed(self, data_rdd, batch_size = -1): """ Model inference base on the given data. You need to invoke collect() to trigger those action \ as the returning result is an RDD. :param data_rdd: the data to be predict. :param batch_size: total batch size of...
0.008503
def n_exec_stmt(self, node): """ exec_stmt ::= EXEC expr exec_stmt ::= EXEC expr IN test exec_stmt ::= EXEC expr IN test COMMA test """ self.write(self.indent, 'exec ') self.preorder(node[1]) if len(node) > 2: self.write(self.indent, ' in ') ...
0.003906
def keelhaul(rest): "Inflict great pain and embarassment on some(one|thing)" keelee = rest karma.Karma.store.change(keelee, -1) return ( "/me straps %s to a dirty rope, tosses 'em overboard and pulls " "with great speed. Yarrr!" % keelee)
0.028455
def to_pivot_table(self, fieldnames=(), verbose=True, values=None, rows=None, cols=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, coerce_float=True): """ A convenience method for creating a spread sheet style pivot ...
0.002099
def get_netG(): """Get net G""" # build the generator netG = nn.Sequential() with netG.name_scope(): # input is Z, going into a convolution netG.add(nn.Conv2DTranspose(ngf * 8, 4, 1, 0, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Activation('relu')) # st...
0.000953
def axis_transform(pca_axes): """ Creates an affine transformation matrix to rotate data in PCA axes into Cartesian plane """ from_ = N.identity(3) to_ = pca_axes # Find inverse transform for forward transform # y = M x -> M = y (x)^(-1) # We don't need to do least-squares since ...
0.004684
def get_user(self, auth, username): """ Returns a representing the user with username ``username``. :param auth.Authentication auth: authentication object, can be ``None`` :param str username: username of user to get :return: the retrieved user :rtype: GogsUser :...
0.004942
def repost(self, token): """ Repost the job if it has timed out (:py:data:`cloudsight.STATUS_TIMEOUT`). :param token: Job token as returned from :py:meth:`cloudsight.API.image_request` or :py:meth:`cloudsight.API.remote_image_request` ...
0.003101
def _set_interface_hello_padding(self, v, load=False): """ Setter method for interface_hello_padding, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_hello/interface_hello_padding (container) If this variable is read-only (config: false) in the source YANG file,...
0.005793
def add_state(self, state, storage_load=False): """Adds a state to the container state. :param state: the state that is going to be added :param storage_load: True if the state was directly loaded from filesystem :return: the state_id of the new state :raises exceptions.Attribut...
0.00565
def tradesWS(symbols=None, on_data=None): '''https://iextrading.com/developer/docs/#trades''' symbols = _strToList(symbols) sendinit = ({'symbols': symbols, 'channels': ['trades']},) return _stream(_wsURL('deep'), sendinit, on_data)
0.004032
def _bottom_position(self, resource): """ Place watermark to bottom position :param resource: Image.Image :return: Image.Image """ image = self._get_scaled_image(resource) left = int(round(resource.size[0] // 2 - image.size[0] // 2)) upper = int(round(res...
0.005181
def distinguish(self, id_, how=True): """Login required. Sends POST to distinguish a submission or comment. Returns :class:`things.Link` or :class:`things.Comment`, or raises :class:`exceptions.UnexpectedResponse` otherwise. URL: ``http://www.reddit.com/api/distinguish/`` :pa...
0.010078
async def _get_messenger_profile(self, page, fields: List[Text]): """ Fetch the value of specified fields in order to avoid setting the same field twice at the same value (since Facebook engineers are not able to make menus that keep on working if set again). """ params ...
0.002894
def provider_parser(subparser): """Configure provider parser for CloudNS""" identity_group = subparser.add_mutually_exclusive_group() identity_group.add_argument( "--auth-id", help="specify user id for authentication") identity_group.add_argument( "--auth-subid", help="specify subuser id...
0.001435
def create_template(material, path, show=False): """ Create a template csv file for a data set. :param material: the name of the material :param path: the path of the directory where the file must be written :param show: a boolean indicating whether the created file should be \ ...
0.001137
def dense_message_pass(node_states, edge_matrices): """Computes a_t from h_{t-1}, see bottom of page 3 in the paper. Args: node_states: [B, L, D] tensor (h_{t-1}) edge_matrices (tf.float32): [B, L*D, L*D] Returns: messages (tf.float32): [B, L, D] For each pair of nodes in the graph a message i...
0.010893
def call(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, on_error='ignore', returncode=False): """Run the given command (with shell=False) and return the output as a string. Strips the output of enclosing whitespace. If the return code is non-zero, throw GitInvocationError. """ ...
0.001292
def send_exit_status(self, status): """ Send the exit status of an executed command to the client. (This really only makes sense in server mode.) Many clients expect to get some sort of status code back from an executed command after it completes. @param status...
0.005355
def get_member_by_uuid(self, member_uuid): """ Returns the member with specified member uuid. :param member_uuid: (int), uuid of the desired member. :return: (:class:`~hazelcast.core.Member`), the corresponding member. """ for member in self.get_member_list(): ...
0.005236
def _normalize_cmd_args(cmd): """Normalize subprocess arguments to handle list commands, string and pipes. Piped commands set pipefail and require use of bash to help with debugging intermediate errors. """ if isinstance(cmd, six.string_types): # check for standard or anonymous named pipes ...
0.003578
def create_model(self, model): """Ran when a new model is created.""" super().create_model(model) for mixin in self.post_processing_mixins: mixin.create_model(model)
0.009852
def _check_data_flow_id(self, data_flow): """Checks the validity of a data flow id Checks whether the id of the given data flow is already by anther data flow used within the state. :param rafcon.core.data_flow.DataFlow data_flow: The data flow to be checked :return bool validity, str ...
0.008439
def _satisfied(self, cl, model): """ Given a clause (as an iterable of integers) and an assignment (as a list of integers), this method checks whether or not the assignment satisfies the clause. This is done by a simple clause traversal. The method is invoked from...
0.004021
def visible_to_user(self, element, *ignorable): """ Determines whether an element is visible to the user. A list of ignorable elements can be passed to this function. These would typically be things like invisible layers sitting atop other elements. This function ignores these el...
0.000773
def design(self, max_stimuli=-1, max_inhibitors=-1, max_experiments=10, relax=False, configure=None): """ Finds all optimal experimental designs using up to :attr:`max_experiments` experiments, such that each experiment has up to :attr:`max_stimuli` stimuli and :attr:`max_inhibitors` inhibitors....
0.003518
def device_id(self): """ Randomly generated deviceId. :return: """ if self._device_id is None: self._device_id = "".join( random.choice("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(50)) return self._device_id
0.009375
def _get_stream_metadata(self, use_cached): """Retrieve metadata about this stream from Device Cloud""" if self._cached_data is None or not use_cached: try: self._cached_data = self._conn.get_json("/ws/DataStream/%s" % self._stream_id)["items"][0] except DeviceClo...
0.006723
def support(self, version): """ return `True` if current python version match version passed. raise a deprecation warning if only PY2 or PY3 is supported as you probably have a conditional that should be removed. """ if not self._known_version(version): ...
0.012522
def eqCoords(lon, lat): """ Converts from ecliptical to equatorial coordinates. This algorithm is described in book 'Primary Directions', pp. 147-150. """ # Convert to radians _lambda = math.radians(lon) _beta = math.radians(lat) _epson = math.radians(23.44) # The earth's inclina...
0.011785
def raise_stmt__30(self, raise_loc, exc_opt): """(3.0-) raise_stmt: 'raise' [test ['from' test]]""" exc = from_loc = cause = None loc = raise_loc if exc_opt: exc, cause_opt = exc_opt loc = loc.join(exc.loc) if cause_opt: from_loc, cause...
0.003846
def change_view(self, change_in_depth): """Change the view depth by expand or collapsing all same-level nodes""" self.current_view_depth += change_in_depth if self.current_view_depth < 0: self.current_view_depth = 0 self.collapseAll() if self.current_view_depth ...
0.006803
def _single_mp_run(x, Phi, bound, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): """ run of the RSSMP algorithm """ rng = check_random_state(random_state) pad = int(pad) x = np.concatenate((np.zeros(pad), x, np.zeros(pad))) n = x.size m = Phi.doth(x...
0.000439
def _set_or_check_remote_id(self, remote_id): """Set or check the remote id.""" if not self.remote_id: assert self.closed_state == self.ClosedState.PENDING, 'Bad ClosedState!' self.remote_id = remote_id self.closed_state = self.ClosedState.OPEN elif self.remote_id != remote_id: raise...
0.012225
def process_updated_files(self, paths: List[str]) -> List[str]: """ Return the paths in the analysis directory (symbolic links) corresponding to the given paths. Result also includes any files which are within a tracked directory. This method will remove/add symb...
0.002782
def visitStarCardinality(self, ctx: ShExDocParser.StarCardinalityContext): """ '*' """ self.expression.min = 0 self.expression.max = -1
0.012579
def prefix_attr_add(arg, opts, shell_opts): """ Add attributes to a prefix """ spec = { 'prefix': arg } v = get_vrf(opts.get('vrf_rt'), abort=True) spec['vrf_rt'] = v.rt res = Prefix.list(spec) if len(res) == 0: print("Prefix %s not found in %s." % (arg, vrf_format(v)), file=sys.st...
0.005814
def envCheckFlag(self, name, default = False): """Check graph flag for enabling / disabling attributes through the use of <name> environment variable. @param name: Name of flag. (Also determines the environment variable name.) @param default: Boolean (...
0.00892
def repo_id(self, repo: str) -> str: """ Returns an unique identifier from a repo URL for the folder the repo is gonna be pulled in. """ if repo.startswith("http"): repo_id = re.sub(r"https?://(.www)?", "", repo) repo_id = re.sub(r"\.git/?$", "", repo_id) else: ...
0.004184
def makepilimage(self, scale = "log", negative = False): """ Makes a PIL image out of the array, respecting the z1 and z2 cutoffs. By default we use a log scaling identical to iraf's, and produce an image of mode "L", i.e. grayscale. But some drawings or colourscales will change the mode...
0.014836
def create(self, properties): """ Create a :term:`Metrics Context` resource in the HMC this client is connected to. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section '...
0.001613
def to_string(self, endpoints): # type: (List[EndpointDescription]) -> str """ Converts the given endpoint description beans into a string :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document """ # Make the ElementTre...
0.00365
def format_config_read_queue(self, use_color: bool = False, max_col_width: int = 50) -> str: """ Prepares a string with pretty printed config read queue. :param use_color: use terminal colors :param max_col_width: limit c...
0.005565
def _parallel_extracter(data_dir, number_of_test, number_of_dev, total, counter): """Generate a function to extract a tar file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param data_dir: the target directory to ...
0.004848
def uri_read(*args, **kwargs): """ Reads the contents of a URI into a string or bytestring. See :func:`uri_open` for complete description of keyword parameters. :returns: Contents of URI :rtype: str, bytes """ with uri_open(*args, **kwargs) as f: content = f.read() return conte...
0.003106
def parse_node(self, node): """ Parses the specified child task node, and returns the task spec. This can be called by a TaskParser instance, that is owned by this ProcessParser. """ if node.get('id') in self.parsed_nodes: return self.parsed_nodes[node.get('i...
0.002782
def vote(self, candidates): """Rank artifact candidates. The voting is needed for the agents living in societies using social decision making. The function should return a sorted list of (candidate, evaluation)-tuples. Depending on the social choice function used, the evaluation...
0.002144
def refreshCompositeOf(self, single_keywords, composite_keywords, store=None, namespace=None): """Re-check sub-parts of this keyword. This should be called after the whole RDF was processed, because it is using a cache of single keywords and if that one is inc...
0.002444
def unsubscribe(self, event, handler): """ Unsubscribes the Handler from the given Event. Both synchronous and asynchronous handlers are removed. @param event: (str|see.Event) event to which the handler is subscribed. @param handler: (callable) function or method to unsubscribe....
0.003063
def _F_hyperedge_head_cardinality(H, F): """Returns the result of a function F applied to the set of cardinalities of hyperedge heads in the hypergraph. :param H: the hypergraph whose head cardinalities will be operated on. :param F: function to execute on the set of cardinalities i...
0.001393
def check_time_event(oqparam, occupancy_periods): """ Check the `time_event` parameter in the datastore, by comparing with the periods found in the exposure. """ time_event = oqparam.time_event if time_event and time_event not in occupancy_periods: raise ValueError( 'time_eve...
0.00216
def _add_loss_summaries(total_loss): """Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages ...
0.011066
def lf_overlaps(L, normalize_by_coverage=False): """Return the **fraction of items each LF labels that are also labeled by at least one other LF.** Note that the maximum possible overlap fraction for an LF is the LF's coverage, unless `normalize_by_coverage=True`, in which case it is 1. Args: ...
0.002656
def read_uint(data, start, length): """Extract a uint from a position in a sequence.""" return int.from_bytes(data[start:start+length], byteorder='big')
0.00625
def remote_sys_desc_uneq_store(self, remote_system_desc): """This function saves the system desc, if different from stored. """ if remote_system_desc != self.remote_system_desc: self.remote_system_desc = remote_system_desc return True return False
0.00678
def write_installed_files(self, paths, prefix, dry_run=False): """ Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths. """ prefix = os.path.joi...
0.001299
def sample_forecast_max_hail(self, dist_model_name, condition_model_name, num_samples, condition_threshold=0.5, query=None): """ Samples every forecast hail object and returns an empirical distribution of possible maximum hail sizes. Hail sizes are sampled from ...
0.00736
def pre_delete_title(instance, **kwargs): ''' Update article.languages ''' if instance.article.languages: languages = instance.article.languages.split(',') else: languages = [] if instance.language in languages: languages.remove(instance.language) instance.article.lan...
0.002227
def camera_action_raw(self, world_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() world_pos.assign_to(action.action_raw.camera_move.center_world_space) return action
0.004425
def cmd_connect(node, cmd_name, node_info): """Connect to node.""" # FUTURE: call function to check for custom connection-info conn_info = "Defaults" conf_mess = ("\r{0}{1} TO{2} {3} using {5}{4}{2} - Confirm [y/N]: ". format(C_STAT[cmd_name.upper()], cmd_name.upper(), C_NORM, ...
0.000816
def submit_sample(self, sample, cookbook=None, params={}, _extra_params={}): """ Submit a sample and returns the submission id. Parameters: sample: The sample to submit. Needs to be a file-like object or a tuple in the shape (filename, file-like object). ...
0.003782
def add_macro(self,name,value): """ Add a variable (macro) for this node. This can be different for each node in the DAG, even if they use the same CondorJob. Within the CondorJob, the value of the macro can be referenced as '$(name)' -- for instance, to define a unique output or error file fo...
0.009728
def should_cache(self, request, response): """ Given the request and response should it be cached """ if not getattr(request, '_cache_update_cache', False): return False if not response.status_code in getattr(settings, 'BETTERCACHE_CACHEABLE_STATUS', CACHEABLE_STATUS): r...
0.008636
def NRTL(xs, taus, alphas): r'''Calculates the activity coefficients of each species in a mixture using the Non-Random Two-Liquid (NRTL) method, given their mole fractions, dimensionless interaction parameters, and nonrandomness constants. Those are normally correlated with temperature in some form, and...
0.001008
def system_describe_projects(input_params={}, always_retry=True, **kwargs): """ Invokes the /system/describeProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/System-Methods#API-method:-/system/describeProjects """ return DXHTTPRequest('/system/describeProje...
0.007979
def get_date_format_string(period): """ For a given period (e.g. 'month', 'day', or some numeric interval such as 3600 (in secs)), return the format string that can be used with strftime to format that time to specify the times across that interval, but no more detailed. For example, >>> get_date_format_string(...
0.030046
def fmt(self, value): """ Sets self.fmt, with some extra help for plain format strings. """ if isinstance(value, str): value = value.split(self.join_str) if not (value and isinstance(value, (list, tuple))): raise TypeError( ' '.join(( '...
0.003419
def language_selector(context): """ displays a language selector dropdown in the admin, based on Django "LANGUAGES" context. requires: * USE_I18N = True / settings.py * LANGUAGES specified / settings.py (otherwise all Django locales will be displayed) * "set_language" url...
0.006916
def copyright_model_factory(*, validator=validators.is_copyright_model, **kwargs): """Generate a Copyright model. Expects ``data``, ``validator``, ``model_cls``, and ``ld_context`` as keyword arguments. Raises: :exc:`ModelError`: If a non-'Copyright' ``ld_type`` key...
0.002193
def rotate_direction(hexgrid_type, direction, ccw=True): """ Takes a direction string associated with a type of hexgrid element, and rotates it one tick in the given direction. :param direction: string, eg 'NW', 'N', 'SE' :param ccw: if True, rotates counter clockwise. Otherwise, rotates clockwise. ...
0.004242
def _piped_realign_gatk(data, region, cl, out_base_file, tmp_dir, prep_params): """Perform realignment with GATK, using input commandline. GATK requires writing to disk and indexing before realignment. """ broad_runner = broad.runner_from_config(data["config"]) pa_bam = "%s-prealign%s" % os.path.spl...
0.004979
def gpg_profile_delete_key( blockchain_id, key_id, proxy=None, wallet_keys=None ): """ Remove a GPG from a blockchain ID's global account. Do NOT remove it from the local keyring. Return {'status': True, ...} on success. May include 'delete_errors' if any specific keys couldn't be removed. Return {...
0.011855
def datagetter(cls): """ example datagetter function, make any local modifications here """ with open('myfile', 'rt') as f: rows = [r for r in csv.reader(f)] dothing = lambda _: [i for i, v in enumerate(_)] rows = [dothing(_) for _ in rows] raise NotImplementedError('...
0.007916
def empty_bar_plot(ax): ''' Delete all axis ticks and labels ''' plt.sca(ax) plt.setp(plt.gca(),xticks=[],xticklabels=[]) return ax
0.027027
def finalize(self): """ finalize simulation for consumer """ # todo sort self.result by path_num if self.result: self.result = sorted(self.result, key=lambda x: x[0]) p, r = map(list, zip(*self.result)) self.result = r
0.006803
def pfm_to_pwm(self, pfm, pseudo=0.001): """Convert PFM with counts to a PFM with fractions. Parameters ---------- pfm : list 2-dimensional list with counts. pseudo : float Pseudocount used in conversion. Returns ------- p...
0.008299
def to_cursor_ref(self): """Returns dict of values to uniquely reference this item""" fields = self._meta.get_primary_keys() assert fields values = {field.name:self.__data__[field.name] for field in fields} return values
0.011538
def cluster_health_for_shards(self, index=None, params={}, **kwargs): """ Return a list of cluster health of specified indices(default all) and append shards information of each index the first element is a dictionary represent a global information of the cluster the second eleme...
0.007364
def xmlstring(self, pretty_print=False): """Serialises this FoLiA element and all its contents to XML. Returns: str: a string with XML representation for this element and all its children""" s = ElementTree.tostring(self.xml(), xml_declaration=False, pretty_print=pretty_print, encod...
0.019006
def get_reporters(self): """ Converts the report_generators list to a dictionary, and caches the result. :return: A dictionary with such references. """ if not hasattr(self, '_report_generators_by_key'): self._report_generators_by_key = {r.key: r for r in self.report...
0.010582
def clean(self): """ check the content of each field :return: """ cleaned_data = super(UserServiceForm, self).clean() sa = ServicesActivated.objects.get(name=self.initial['name']) # set the name of the service, related to ServicesActivated model cleaned_da...
0.003018
def add_callback(obj, callback, args=()): """Add a callback to an object.""" callbacks = obj._callbacks node = Node(callback, args) # Store a single callback directly in _callbacks if callbacks is None: obj._callbacks = node return node # Otherwise use a dllist. if not isinst...
0.002012