code stringlengths 1 18.2k |
|---|
def _unseen_event_ids(medium): """ Return all events that have not been seen on this medium. """ query = ''' SELECT event.id FROM entity_event_event AS event LEFT OUTER JOIN (SELECT * FROM entity_event_eventseen AS seen WHERE seen.medium_id=%s) AS eventseen ON event.id = eventseen.event_id WHERE eventseen.medium_id IS ... |
def mark_seen(self, medium): """ Creates EventSeen objects for the provided medium for every event in the queryset. Creating these EventSeen objects ensures they will not be returned when passing ``seen=False`` to any of the medium event retrieval functions, ``events``, ``entity_events``, or ``events_targets``. """ Eve... |
def create_event(self, actors=None, ignore_duplicates=False, **kwargs): """ Create events with actors. This method can be used in place of ``Event.objects.create`` to create events, and the appropriate actors. It takes all the same keywords as ``Event.objects.create`` for the event creation, but additionally takes a li... |
that creates events to ensure they do not create duplicate events. This id could be, for example some hash of the ``context``, or, if the creator is unconcerned with creating duplicate events a call to python's ``uuid1()`` in the ``uuid`` module. :type time_expires: datetime (optional) :param time_expires: If given, th... |
before attempting to create the event. Setting this to ``True`` allows the creator of events to gracefully ensure no duplicates are attempted to be created. There is a uniqueness constraint on uuid so it will raise an exception if duplicates are allowed and submitted. :rtype: Event :returns: The created event. Alternat... |
def create_events(self, kwargs_list): """ Create events in bulk to save on queries. Each element in the kwargs list should be a dict with the same set of arguments you would normally pass to create_event :param kwargs_list: list of kwargs dicts :return: list of Event """ # Build map of uuid to event info uuid_map = { k... |
but we are allowing duplicates if not event_dict['exists'] or not event_dict['ignore_duplicates']: events_to_create.append(Event(**event_dict['event_kwargs'])) # Bulk create the events created_events = Event.objects.bulk_create(events_to_create) # Build list of EventActor objects to bulk create event_actors_to_create =... |
def right(self, num=None): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [-num:] """ if num == None: return self.last.node if num <= 0: return [] if not self.list: self._build_list() return self.list[-num:] |
def not_right(self, num): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:] """ if not self.list: self._build_list() if num == None: return self.list[:-1:] if num <= 0: return [] return self.list[:-num:] |
def get_object_url(self): """ Returns the url where this object can be edited. """ if self.kwargs.get(self.slug_url_kwarg, False) == \ unicode(getattr(self.object, self.slug_field, "")) \ and not self.force_add: url = self.request.build_absolute_uri() else: url = self.bundle.get_view_url('edit', self.request.user, {'ob... |
def get_cancel_url(self): """ Returns the cancel url for this view. if `self.cancel_view` is None the current url will be used. Otherwise the get_view_url will be called with the current bundle using `self.cancel_view` as the view name. """ if self.cancel_view: url = self.bundle.get_view_url(self.cancel_view, self.requ... |
def get_success_url(self): """ Returns the url to redirect to after a successful update. if `self.redirect_to_view` is None the current url will be used. Otherwise the get_view_url will be called on the current bundle using `self.redirect_to_view` as the view name. If the name is "main" or "main_list" no object will be... |
def get_object(self): """ Get the object we are working with. Makes sure get_queryset is called even when in add mode. """ if not self.force_add and self.kwargs.get(self.slug_url_kwarg, None): return super(FormView, self).get_object() else: self.queryset = self.get_queryset() return None |
def get_fieldsets(self): """ Hook for specifying fieldsets. If 'self.fieldsets' is empty this will default to include all the fields in the form with a title of None. """ if self.fieldsets: return self.fieldsets form_class = self.get_form_class() form = self.get_form(form_class) fields = form.base_fields.keys() readonl... |
def get_form_class(self): """ Returns the form class to use in this view. Makes sure that the form_field_callback is set to use the `formfield_for_dbfield` method and that any custom form classes are prepared by the `customize_form_widgets` method. """ if self.fieldsets: fields = flatten_fieldsets(self.get_fieldsets())... |
model = self.model fc = self.customize_form_widgets(self.form_class, fields=fields) params['form'] = fc else: if self.model is not None: # If a model has been explicitly provided, use it model = self.model elif hasattr(self, 'object') and self.object is not None: # If this view is operating on a single object, use # th... |
def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = {'initial': self.get_initial(), 'instance': self.object} if self.request.method in ('POST', 'PUT') and self.can_submit: kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES }) return kwargs |
def save_form(self, form): """ Save a valid form. If there is a parent attribute, this will make sure that the parent object is added to the saved object. Either as a relationship before saving or in the case of many to many relations after saving. Any forced instance values are set as well. Returns the saved object. "... |
FieldDoesNotExist: pass obj = form.save() # Do we need to add this to a m2m if should_add: getattr(obj, self.parent_field).add(self.parent_object) return obj |
def save_formsets(self, form, formsets, auto_tags=None): """ Hook for saving formsets. Loops through all the given formsets and calls their save method. """ for formset in formsets.values(): tag_handler.set_auto_tags_for_formset(formset, auto_tags) formset.save() |
def form_valid(self, form, formsets): """ Response for valid form. In one transaction this will save the current form and formsets, log the action and message the user. Returns the results of calling the `success_response` method. """ # check if it's a new object before it save the form new_object = False if not self.o... |
def success_response(self, message=None): """ Returns a 'render redirect' to the result of the `get_success_url` method. """ return self.render(self.request, redirect_url=self.get_success_url(), obj=self.object, message=message, collect_render_data=False) |
def render(self, request, **kwargs): """ Renders this view. Adds cancel_url to the context. If the request get parameters contains 'popup' then the `render_type` is set to 'popup'. """ if request.GET.get('popup'): self.render_type = 'popup' kwargs['popup'] = 1 kwargs['cancel_url'] = self.get_cancel_url() if not self.ob... |
def get(self, request, *args, **kwargs): """ Method for handling GET requests. Calls the `render` method with the following items in context. * **adminForm** - The main form wrapped in an helper class \ that helps with fieldset iteration and html attributes. * **obj** - The object being edited. * **formsets** - Any att... |
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Validates submitted form and formsets. Saves if valid, re displays page with errors if invalid. """ self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formsets = self.get_formsets(form, savi... |
def get_object(self): """ Get the object for previewing. Raises a http404 error if the object is not found. """ obj = super(PreviewWrapper, self).get_object() if not obj: raise http.Http404 return obj |
def get_preview_kwargs(self, **kwargs): """ Gets the url keyword arguments to pass to the `preview_view` callable. If the `pass_through_kwarg` attribute is set the value of `pass_through_attr` will be looked up on the object. So if you are previewing an item Obj<id=2> and :: self.pass_through_kwarg = 'object_id' self.p... |
def get(self, request, *args, **kwargs): """ Method for handling GET requests. Sets the renderer to be a RenderResponse instance that uses `default_template` as the template. The `preview_view` callable is called and passed to `render` method as the data keyword argument. """ self.renders = { 'response': renders.Render... |
def get(self, request, *args, **kwargs): """ Method for handling GET requests. Passes the following arguments to the context: * **versions** - The versions available for this object.\ These will be instances of the inner version class, and \ will not have access to the fields on the base model. * **done_url** - The res... |
def revert(self, version, url): """ Set the given version to be the active draft. This is done by calling the object's `make_draft` method. Logs the revert as a 'save' and messages the user. """ message = "Draft replaced with %s version. This revert has not been published." % version.date_published version.make_draft()... |
def delete(self, version): """ Deletes the given version, not the object itself. No log entry is generated but the user is notified with a message. """ # Shouldn't be able to delete live or draft version if version.state != version.DRAFT and \ version.state != version.PUBLISHED: version.delete() message = "%s version d... |
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Expects the 'vid' of the version to act on to be passed as in the POST variable 'version'. If a POST variable 'revert' is present this will call the revert method and then return a 'render redirect' to the result of the `get_done_url` meth... |
self.delete(version) # Delete should redirect back to itself url = self.request.build_absolute_uri() # If the give version isn't valid we'll just silently redirect except (ValueError, versions.model.DoesNotExist): pass return self.render(request, redirect_url=url, message=msg, obj=self.object, collect_render_data=False... |
def validate_parent_id(self, key, parent_id): """Parent has to be different from itself.""" id_ = getattr(self, 'id', None) if id_ is not None and parent_id is not None: assert id_ != parent_id, 'Can not be attached to itself.' return parent_id |
def _to_encoded_string(o): """ Build an encoded string suitable for use as a URL component. This includes double-escaping the string to avoid issues with escaped backslash characters being automatically converted by WSGI or, in some cases such as default Apache servers, blocked entirely. :param o: an object of any kind... |
def list_observatories(self): """ Get the IDs of all observatories with have stored observations on this server. :return: a sequence of strings containing observatories IDs """ response = requests.get(self.base_url + '/obstories').text return safe_load(response) |
def get_observatory_status(self, observatory_id, status_time=None): """ Get details of the specified camera's status :param string observatory_id: a observatory ID, as returned by list_observatories() :param float status_time: optional, if specified attempts to get the status for the given camera at a particular point ... |
def search_observations(self, search=None): """ Search for observations, returning an Observation object for each result. FileRecords within result Observations have two additional methods patched into them, get_url() and download_to(file_name), which will retrieve the URL for the file content and download that content... |
a query limit. Note that the default query limit is 100). """ if search is None: search = model.ObservationSearch() search_string = _to_encoded_string(search) url = self.base_url + '/obs/{0}'.format(search_string) # print url response = requests.get(url) response_object = safe_load(response.text) obs_dicts = response_o... |
def search_files(self, search=None): """ Search for files, returning a FileRecord for each result. FileRecords have two additional methods patched into them, get_url() and download_to(file_name), which will retrieve the URL for the file content and download that content to a named file on disk, respectively. :param Fil... |
Note that the default query limit is 100). """ if search is None: search = model.FileRecordSearch() search_string = _to_encoded_string(search) url = self.base_url + '/files/{0}'.format(search_string) # print url response = requests.get(url) response_object = safe_load(response.text) file_dicts = response_object['files'... |
def _augment_file(self, f): """ Augment a FileRecord with methods to get the data URL and to download, returning the updated file for use in generator functions :internal: """ def get_url(target): if target.file_size is None: return None if target.file_name is not None: return self.base_url + '/files/content/{0}/{1}'.f... |
def _augment_observation_files(self, e): """ Augment all the file records in an event :internal: """ e.file_records = [self._augment_file(f) for f in e.file_records] return e |
def build_defaults(self): """Build a dictionary of default values from the `Scheme`. Returns: dict: The default configurations as set by the `Scheme`. Raises: errors.InvalidSchemeError: The `Scheme` does not contain valid options. """ defaults = {} for arg in self.args: if not isinstance(arg, _BaseOpt): raise errors.In... |
def flatten(self): """Flatten the scheme into a dictionary where the keys are compound 'dot' notation keys, and the values are the corresponding options. Returns: dict: The flattened `Scheme`. """ if self._flat is None: flat = {} for arg in self.args: if isinstance(arg, Option): flat[arg.name] = arg elif isinstance(arg... |
def validate(self, config): """Validate the given config against the `Scheme`. Args: config (dict): The configuration to validate. Raises: errors.SchemeValidationError: The configuration fails validation against the `Schema`. """ if not isinstance(config, dict): raise errors.SchemeValidationError( 'Scheme can only vali... |
def cast(self, value): """Cast a value to the type required by the option, if one is set. This is used to cast the string values gathered from environment variable into their required type. Args: value: The value to cast. Returns: The value casted to the expected type for the option. """ # if there is no type set for t... |
'true' # the option type is currently not supported else: raise errors.BisonError('Unsupported type for casting: {}'.format(self.type)) |
def geometricmean(inlist): """ Calculates the geometric mean of the values in the passed list. That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list. Usage: lgeometricmean(inlist) """ mult = 1.0 one_over_n = 1.0 / len(inlist) for item in inlist: mult = mult * pow(item, one_over_n) return mult |
def harmonicmean(inlist): """ Calculates the harmonic mean of the values in the passed list. That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list. Usage: lharmonicmean(inlist) """ sum = 0 for item in inlist: sum = sum + 1.0 / item return len(inlist) / sum |
def mean(inlist): """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum / float(len(inlist)) |
def medianscore(inlist): """ Returns the 'middle' score of the passed list. If there is an even number of scores, the mean of the 2 middle scores is returned. Usage: lmedianscore(inlist) """ newlist = copy.deepcopy(inlist) newlist.sort() if len(newlist) % 2 == 0: # if even number of scores, average middle 2 index = len... |
def mode(inlist): """ Returns a list of the modal (most common) score(s) in the passed list. If there is more than one such score, all are returned. The bin-count for the mode(s) is also returned. Usage: lmode(inlist) Returns: bin-count for mode(s), a list of modal value(s) """ scores = pstat.unique(inlist) scores.sort... |
def moment(inlist, moment=1): """ Calculates the nth moment about the mean for a sample (defaults to the 1st moment). Used to calculate coefficients of skewness and kurtosis. Usage: lmoment(inlist,moment=1) Returns: appropriate moment (r) from pyLibrary. 1/n * SUM((inlist(i)-mean)**r) """ if moment == 1: return 0.0 els... |
def describe(inlist): """ Returns some descriptive statistics of the passed list (assumed to be 1D). Usage: ldescribe(inlist) Returns: n, mean, standard deviation, skew, kurtosis """ n = len(inlist) mm = (min(inlist), max(inlist)) m = mean(inlist) sd = stdev(inlist) sk = skew(inlist) kurt = kurtosis(inlist) return n, m... |
def itemfreq(inlist): """ Returns a list of pairs. Each pair consists of one of the scores in inlist and it's frequency count. Assumes a 1D list is passed. Usage: litemfreq(inlist) Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies) """ scores = pstat.unique(inlist) scores.sort() freq = [] for item in... |
def scoreatpercentile(inlist, percent): """ Returns the score at a given percentile relative to the distribution given by inlist. Usage: lscoreatpercentile(inlist,percent) """ if percent > 1: print("\nDividing percent>1 by 100 in lscoreatpercentile().\n") percent = percent / 100.0 targetcf = percent * len(inlist) h, lr... |
def percentileofscore(inlist, score, histbins=10, defaultlimits=None): """ Returns the percentile value of a score relative to the distribution given by inlist. Formula depends on the values used to histogram the data(!). Usage: lpercentileofscore(inlist,score,histbins=10,defaultlimits=None) """ h, lrl, binsize, extras... |
def histogram(inlist, numbins=10, defaultreallimits=None, printextras=0): """ Returns (i) a list of histogram bin counts, (ii) the smallest value of the histogram binning, and (iii) the bin width (the last 2 are not necessarily integers). Default number of bins is 10. If no sequence object is given for defaultreallimit... |
/ float(numbins) else: # no limits given for histogram, both must be calc'd estbinwidth = (max(inlist) - min(inlist)) / float(numbins) + 1e-6 # 1=>cover all binsize = ((max(inlist) - min(inlist) + estbinwidth)) / float(numbins) lowerreallimit = min(inlist) - binsize / 2 # lower real limit,1st bin bins = [0] * (numbins)... |
def cumfreq(inlist, numbins=10, defaultreallimits=None): """ Returns a cumulative frequency histogram, using the histogram function. Usage: lcumfreq(inlist,numbins=10,defaultreallimits=None) Returns: list of cumfreq bin values, lowerreallimit, binsize, extrapoints """ h, l, b, e = histogram(inlist, numbins, defaultreal... |
def relfreq(inlist, numbins=10, defaultreallimits=None): """ Returns a relative frequency histogram, using the histogram function. Usage: lrelfreq(inlist,numbins=10,defaultreallimits=None) Returns: list of cumfreq bin values, lowerreallimit, binsize, extrapoints """ h, l, b, e = histogram(inlist, numbins, defaultrealli... |
def obrientransform(*args): """ Computes a transform on input data (any number of columns). Used to test for homogeneity of variance prior to running one-way stats. From Maxwell and Delaney, p.112. Usage: lobrientransform(*args) Returns: transformed data for use in an ANOVA """ TINY = 1e-10 k = len(args) n = [0.0] * k ... |
for j in range(k): if v[j] - mean(nargs[j]) > TINY: check = 0 if check != 1: raise ValueError('Problem in obrientransform.') else: return nargs |
def samplevar(inlist): """ Returns the variance of the values in the passed list using N for the denominator (i.e., DESCRIBES the sample variance only). Usage: lsamplevar(inlist) """ n = len(inlist) mn = mean(inlist) deviations = [] for item in inlist: deviations.append(item - mn) return ss(deviations) / float(n) |
def cov(x, y, keepdims=0): """ Returns the estimated covariance of the values in the passed array (i.e., N-1). Dimension can equal None (ravel array first), an integer (the dimension over which to operate), or a sequence (operate over multiple dimensions). Set keepdims=1 to return an array with the same number of dimen... |
def var(inlist): """ Returns the variance of the values in the passed list using N-1 for the denominator (i.e., for estimating population variance). Usage: lvar(inlist) """ n = len(inlist) mn = mean(inlist) deviations = [0] * len(inlist) for i in range(len(inlist)): deviations[i] = inlist[i] - mn return ss(deviations) ... |
def sem(inlist): """ Returns the estimated standard error of the mean (sx-bar) of the values in the passed list. sem = stdev / sqrt(n) Usage: lsem(inlist) """ sd = stdev(inlist) n = len(inlist) return sd / math.sqrt(n) |
def zs(inlist): """ Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist) """ zscores = [] for item in inlist: zscores.append(z(inlist, item)) return zscores |
def trimboth(l, proportiontocut): """ Slices off the passed proportion of items from BOTH ends of the passed list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost' 10% of scores. Assumes list is sorted by magnitude. Slices off LESS if proportion results in a non-integer slice index (i.e., conservat... |
def trim1(l, proportiontocut, tail='right'): """ Slices off the passed proportion of items from ONE end of the passed list (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost' 10% of scores). Slices off LESS if proportion results in a non-integer slice index (i.e., conservatively slices off proportiontoc... |
def paired(x, y): """ Interactively determines the type of data and then runs the appropriated statistic for paired group data. Usage: lpaired(x,y) Returns: appropriate statistic name, value, and probability """ samples = '' while samples not in ['i', 'r', 'I', 'R', 'c', 'C']: print('\nIndependent or related samples, o... |
len(x) > 20 or len(y) > 20: z, p = ranksums(x, y) print('\nRank Sums test (NONparametric, n>20): ', round(z, 4), round(p, 4)) else: u, p = mannwhitneyu(x, y) print('\nMann-Whitney U-test (NONparametric, ns<20): ', round(u, 4), round(p, 4)) else: # RELATED SAMPLES if vartype[0] == 'e': t, p = ttest_rel(x, y, 0) print('\... |
[round(m, 4), round(b, 4), round(r, 4), round(p, 4), round(see, 4)]] pstat.printcc(lol) elif corrtype in ['r', 'R']: r, p = spearmanr(x, y) print('\nCorrelation for ranked variables ...') print("Spearman's r: ", round(r, 4), round(p, 4)) else: # DICHOTOMOUS r, p = pointbiserialr(x, y) print('\nAssuming x contains a dic... |
def lincc(x, y): """ Calculates Lin's concordance correlation coefficient. Usage: alincc(x,y) where x, y are equal-length arrays Returns: Lin's CC """ covar = cov(x, y) * (len(x) - 1) / float(len(x)) # correct denom to n xvar = var(x) * (len(x) - 1) / float(len(x)) # correct denom to n yvar = var(y) * (len(y) - 1) / fl... |
def pointbiserialr(cats, vals): """ Calculates a point-biserial correlation coefficient and the associated probability value. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.194. Usage: pointbiserialr(x,y) where x,y are equal-length lists Returns: Point-biserial r, two-tailed p-value """ TINY = 1e-30 i... |
adjust df = n - 2 t = rpb * math.sqrt(df / ((1.0 - rpb + TINY) * (1.0 + rpb + TINY))) prob = betai(0.5 * df, 0.5, df / (df + t * t)) # t already a float return rpb, prob |
def chisquare(f_obs, f_exp=None): """ Calculates a one-way chi square for list of observed frequencies and returns the result. If no expected frequencies are given, the total N is assumed to be equally distributed across all groups. Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq. Returns: chisq... |
def wilcoxont(x, y): """ Calculates the Wilcoxon T-test for related samples and returns the result. A non-parametric T-test. Usage: lwilcoxont(x,y) Returns: a t-statistic, two-tail probability estimate """ if len(x) != len(y): raise ValueError('Unequal N in wilcoxont. Aborting.') d = [] for i in range(len(x)): diff = x... |
(1.0 - zprob(abs(z))) return wt, prob |
def friedmanchisquare(*args): """ Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA. This function calculates the Friedman Chi-square test for repeated measures and returns the result, along with the associated probability value. It assumes 3 or more repeated measures. Only 3 levels requires a mini... |
+ 1) return chisq, chisqprob(chisq, k - 1) |
def erfcc(x): """ Returns the complementary error function erfc(x) with fractional error everywhere less than 1.2e-7. Adapted from Numerical Recipies. Usage: lerfcc(x) """ z = abs(x) t = 1.0 / (1.0 + 0.5 * z) ans = t * math.exp( -z * z - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.1862880... |
def fprob(dfnum, dfden, F): """ Returns the (1-tailed) significance level (p-value) of an F statistic given the degrees of freedom for the numerator (dfR-dfF) and the degrees of freedom for the denominator (dfF). Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn """ p = betai(0.5 * dfden, 0.5 * dfnum,... |
def betacf(a, b, x): """ This function evaluates the continued fraction form of the incomplete Beta function, betai. (Adapted from: Numerical Recipies in C.) Usage: lbetacf(a,b,x) """ ITMAX = 200 EPS = 3.0e-7 bm = az = am = 1.0 qab = a + b qap = a + 1.0 qam = a - 1.0 bz = 1.0 - qab * x / qap for i in range(ITMAX + 1): ... |
+ tem)) app = ap + d * az bpp = bp + d * bz aold = az am = ap / bpp bm = bp / bpp az = app / bpp bz = 1.0 if (abs(az - aold) < (EPS * abs(az))): return az print('a or b too big, or ITMAX too small in Betacf.') |
def F_oneway(*lists): """ Performs a 1-way ANOVA, returning an F-value and probability given any number of groups. From Heiman, pp.394-7. Usage: F_oneway(*lists) where *lists is any number of lists, one per treatment group Returns: F value, one-tailed p-value """ a = len(lists) # ANOVA on 'a' groups, each in it's own l... |
- ssbn dfbn = a - 1 dfwn = bign - a msb = ssbn / float(dfbn) msw = sswn / float(dfwn) f = msb / msw prob = fprob(dfbn, dfwn, f) return f, prob |
def F_value(ER, EF, dfnum, dfden): """ Returns an F-statistic given the following: ER = error associated with the null hypothesis (the Restricted model) EF = error associated with the alternate hypothesis (the Full model) dfR-dfF = degrees of freedom of the numerator dfF = degrees of freedom associated with the denomin... |
def incr(l, cap): # to increment a list up to a max-list of 'cap' """ Simulate a counting system from an n-dimensional list. Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n Returns: next set of values for list l, OR -1 (if overflow) """ l[0] = l[0] + 1 # e.g., [0,0,0] --> [2,4,3] (=cap) for ... |
def cumsum(inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1, len(newlist)): newlist[i] = newlist[i] + newlist[i - 1] return newlist |
def ss(inlist): """ Squares each value in the passed list, adds up these squares and returns the result. Usage: lss(inlist) """ ss = 0 for item in inlist: ss = ss + item * item return ss |
def summult(list1, list2): """ Multiplies elements in list1 and list2, element by element, and returns the sum of all resulting multiplications. Must provide equal length lists. Usage: lsummult(list1,list2) """ if len(list1) != len(list2): raise ValueError("Lists not equal length in summult.") s = 0 for item1, item2 in... |
def sumdiffsquared(x, y): """ Takes pairwise differences of the values in lists x and y, squares these differences, and returns the sum of these squares. Usage: lsumdiffsquared(x,y) Returns: sum[(x[i]-y[i])**2] """ sds = 0 for i in range(len(x)): sds = sds + (x[i] - y[i]) ** 2 return sds |
def shellsort(inlist): """ Shellsort algorithm. Sorts a 1D-list. Usage: lshellsort(inlist) Returns: sorted-inlist, sorting-index-vector (for original list) """ n = len(inlist) svec = copy.deepcopy(inlist) ivec = range(n) gap = n / 2 # integer division needed while gap > 0: for i in range(gap, n): for j in range(i - gap... |
def rankdata(inlist): """ Ranks the data in inlist, dealing with ties appropritely. Assumes a 1D inlist. Adapted from Gary Perlman's |Stat ranksort. Usage: rankdata(inlist) Returns: a list of length equal to inlist, containing rank scores """ n = len(inlist) svec, ivec = shellsort(inlist) sumranks = 0 dupcount = 0 newl... |
def findwithin(data): """ Returns an integer representing a binary vector, where 1=within- subject factor, 0=between. Input equals the entire data 2D list (i.e., column 0=random factor, column -1=measured values (those two are skipped). Note: input data is in |Stat format ... a list of lists ("2D list") with one row pe... |
on this factor? withinvec = withinvec + (1 << col) return withinvec |
def register_model(self, model, bundle): """ Registers a bundle as the main bundle for a model. Used when we need to lookup urls by a model. """ if model in self._model_registry: raise AlreadyRegistered('The model %s is already registered' \ % model) if bundle.url_params: raise Exception("A primary model bundle cannot ... |
def unregister_model(self, model): """ Unregisters the given model. """ if model not in self._model_registry: raise NotRegistered('The model %s is not registered' % model) del self._model_registry[model] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.