Most recent observation from the 'Previous observations' table
 This is unfinished, will need to capture the markup when the
 current reading is not avaliable and stub it w/fakeweb...
963064
def previous_reading(doc)
      reading = {}
      text = 'Previous observations'
      xpath = "//table/caption[@class='dataHeader'][text()[contains(.,'#{text}')]]"

      xpath += "/../tr/td"
      elements = doc.xpath xpath

      reading
    end
946118
function checkForTabAdded(refreshData) {
    var updatedTabsArray = refreshData.updatedTabsArray,
        updatedTabsLiContent = refreshData.updatedTabsLiContent || [],
        updatedTabsPostProcessors = refreshData.updatedTabsPostProcessors || [],
        propNames = refreshData.propNames,
        ignoreTabPanes = refreshData.ignoreTabPanes,
        options = refreshData.options,
        $currTabLis = refreshData.$currTabLis,
        $navTabs = refreshData.$navTabs,
        $currTabContentPanesContainer = ignoreTabPanes ? null : refreshData.$currTabContentPanesContainer,
        $currTabContentPanes = ignoreTabPanes ? null : refreshData.$currTabContentPanes,
        isInitTabsRequired = false;
  
    // make sure each tab in the updated tabs array has a corresponding DOM element
    updatedTabsArray.forEach(function (tab, idx) {
      var $li = $currTabLis.find('a[href="#' + tab[propNames.paneId] + '"]'),
          isTabIdxPastCurrTabs = (idx >= $currTabLis.length),
          $pane;
  
      if (!$li.length) { // new tab
        isInitTabsRequired = true;
  
        // add the tab, add its pane (if necessary), and refresh the scroller
        options.tabLiContent = updatedTabsLiContent[idx];
        options.tabPostProcessor = updatedTabsPostProcessors[idx];
        $li = tabElements.getNewElTabLi(tab, propNames, options);
        tabUtils.storeDataOnLiEl($li, updatedTabsArray, idx);
  
        if (isTabIdxPastCurrTabs) { // append to end of current tabs
          $li.appendTo($navTabs);
        } else {                        // insert in middle of current tabs
          $li.insertBefore($currTabLis.eq(idx));
        }
  
        if (!ignoreTabPanes && tab[propNames.content] !== undefined) {
          $pane = tabElements.getNewElTabPane(tab, propNames, options);
          if (isTabIdxPastCurrTabs) { // append to end of current tabs
            $pane.appendTo($currTabContentPanesContainer);
          } else {                        // insert in middle of current tabs
            $pane.insertBefore($currTabContentPanes.eq(idx));
          }
        }
  
      }
  
    });
  
    return isInitTabsRequired;
  }
1370671
public function lastCompleted()
    {
        // We use $this->token since there is no showToken anymore
        $html = $this->getHtmlSequence();
        $org  = $this->token->getOrganization();

        $html->h3($this->_('Token'));

        $this->addWelcome($html);

        $html->pInfo($this->_('Thank you for answering. At the moment we have no further surveys for you to take.'));

        if ($sig = $org->getSignature()) {
            $html->pInfo()->raw(\MUtil_Markup::render($this->_($sig), 'Bbcode', 'Html'));
        }

        return $html;
    }
1084327
def _load(self, data):
        
        self.raw_data = data
        self.creation_date = _convert_tstamp(data['creationDate'])
        self.economics = data['economics']
        self.id = data['id']
        self.last_modified_date = _convert_tstamp(data['lastModifiedDate'])
        self.length = data['length']
        self.link_text = data['linkText']
        self.link_url = data['linkURL']
        self.long_description = data['longDescription']
        self.name = data['name']
        self.plays_total = data['playsTotal']
        self.plays_trailing_week = data['playsTrailingWeek']
        self.published_date = _convert_tstamp(data['publishedDate'])
        self.start_date = _convert_tstamp(data.get('startDate', None))
        self.end_date = _convert_tstamp(data.get('endDate', None))
        self.reference_id = data['referenceId']
        self.short_description = data['shortDescription']
        self.tags = []
        for tag in data['tags']:
            self.tags.append(tag)
        self.thumbnail_url = data['thumbnailURL']
        self.video_still_url = data['videoStillURL']
1189500
def timestamps!
      [:created_at, :updated_at].each do |name|
        _add_key(name)
        attr_reader name
        class_eval(<<-RUBY, __FILE__, __LINE__)
          def #{name}=(value)                       # def created_at=(value)
            if value.kind_of?(String)               #   if value.kind_of?(String)
              value = Time.cast_from_string(value)  #     value = Time.cast_from_string(value)
            end                                     #   end
            @#{name} = value.nil? ? nil : value.utc #   @created_at = value.nil? ? nil : value.utc
          end                                       # end
        RUBY
      end

      class_eval(<<-RUBY, __FILE__, __LINE__)
        def _save(safe)
          if new_record?
            self.created_at = self.updated_at = Time.now
          else
            original_updated_at = updated_at
            self.updated_at = Time.now
          end
          super
        rescue Mongo::MongoDBError => e
          if new_record?
            self.created_at = self.updated_at = nil
          else
            self.updated_at = original_updated_at
          end
          raise e
        end

        def _update(selector, data, safe)
          original_updated_at = updated_at
          self.updated_at = Time.now
          data[:updated_at] = updated_at
          super
        rescue Mongo::MongoDBError => e
          self.updated_at = original_updated_at
          raise e
        end
      RUBY
    end
432930
def update_status(table_name="swdata", date_column="date"):
    
    status_text = 'Latest entry: {}'.format(
        _get_most_recent_record(table_name, date_column))
    L.info(status_text)

    scraperwiki.status('ok', status_text)
1314597
function findMinMcWitnessedLevel(handleMinMcWl){
					createListOfBestChildrenIncludedByLaterUnits([first_unstable_mc_unit], function(arrBestChildren){
						conn.query( // if 2 witnesses authored the same unit, unit_authors will be joined 2 times and counted twice
							"SELECT witnessed_level, address \n\
							FROM units \n\
							CROSS JOIN unit_authors USING(unit) \n\
							WHERE unit IN("+arrBestChildren.map(db.escape).join(', ')+") AND address IN(?) \n\
							ORDER BY witnessed_level DESC",
							[arrWitnesses],
							function(rows){
								var arrCollectedWitnesses = [];
								var min_mc_wl = -1;
								for (var i=0; i<rows.length; i++){
									var row = rows[i];
									if (arrCollectedWitnesses.indexOf(row.address) === -1){
										arrCollectedWitnesses.push(row.address);
										if (arrCollectedWitnesses.length >= constants.MAJORITY_OF_WITNESSES){
											min_mc_wl = row.witnessed_level;
											break;
										}
									}
								}
							//	var min_mc_wl = rows[constants.MAJORITY_OF_WITNESSES-1].witnessed_level;
								if (first_unstable_mc_index > constants.branchedMinMcWlUpgradeMci){
									if (min_mc_wl === -1)
										throw Error("couldn't collect 7 witnesses, earlier unit "+earlier_unit+", best children "+arrBestChildren.join(', ')+", later "+arrLaterUnits.join(', ')+", witnesses "+arrWitnesses.join(', ')+", collected witnesses "+arrCollectedWitnesses.join(', '));
									return handleMinMcWl(min_mc_wl);
								}
								// it might be more optimistic because it collects 7 witness units, not 7 units posted by _different_ witnesses
								findMinMcWitnessedLevelOld(function(old_min_mc_wl){
									var diff = min_mc_wl - old_min_mc_wl;
									console.log("---------- new min_mc_wl="+min_mc_wl+", old min_mc_wl="+old_min_mc_wl+", diff="+diff+", later "+arrLaterUnits.join(', '));
								//	if (diff < 0)
								//		throw Error("new min_mc_wl="+min_mc_wl+", old min_mc_wl="+old_min_mc_wl+", diff="+diff+" for earlier "+earlier_unit+", later "+arrLaterUnits.join(', '));
									handleMinMcWl(Math.max(old_min_mc_wl, min_mc_wl));
								});
							}
						);
					});
				}
445290
def with_timestamps(self, created_at=None, updated_at=None):
        
        if not created_at:
            created_at = self.created_at()

        if not updated_at:
            updated_at = self.updated_at()

        return self.with_pivot(created_at, updated_at)
691468
def prev_page(self):
        
        if self.history.position > self.lines and self.history.top:
            mid = min(len(self.history.top),
                      int(math.ceil(self.lines * self.history.ratio)))

            self.history.bottom.extendleft(
                self.buffer[y]
                for y in range(self.lines - 1, self.lines - mid - 1, -1))
            self.history = self.history \
                ._replace(position=self.history.position - mid)

            for y in range(self.lines - 1, mid - 1, -1):
                self.buffer[y] = self.buffer[y - mid]
            for y in range(mid - 1, -1, -1):
                self.buffer[y] = self.history.top.pop()

            self.dirty = set(range(self.lines))
369665
def build_updated_request(self):
        
        r_kwargs = {
            "table_name": self.message.table_name,
            "filter": self.message.filter,
        }

        if self.message.rows_limit != 0:
            r_kwargs["rows_limit"] = max(
                1, self.message.rows_limit - self.rows_read_so_far
            )

        # if neither RowSet.row_keys nor RowSet.row_ranges currently exist,
        # add row_range that starts with last_scanned_key as start_key_open
        # to request only rows that have not been returned yet
        if not self.message.HasField("rows"):
            row_range = data_v2_pb2.RowRange(start_key_open=self.last_scanned_key)
            r_kwargs["rows"] = data_v2_pb2.RowSet(row_ranges=[row_range])
        else:
            row_keys = self._filter_rows_keys()
            row_ranges = self._filter_row_ranges()
            r_kwargs["rows"] = data_v2_pb2.RowSet(
                row_keys=row_keys, row_ranges=row_ranges
            )
        return data_messages_v2_pb2.ReadRowsRequest(**r_kwargs)
414544
def _get_newest_ts_in_table(self, table_name):
        
        logger.debug(
            'Querying for newest timestamp in table %s', table_name
        )
        q = "SELECT TIMESTAMP_TO_SEC(MAX(timestamp)) AS max_ts %s;" % (
            self._from_for_table(table_name)
        )
        res = self._run_query(q)
        ts = int(res[0]['max_ts'])
        logger.debug('Newest timestamp in table %s: %s', table_name, ts)
        return ts
1171404
def query_recent(num=8, **kwargs):
        '''
        
        '''
        order_by_create = kwargs.get('order_by_create', False)
        kind = kwargs.get('kind', None)
        if order_by_create:
            if kind:
                recent_recs = TabPost.select().where(
                    (TabPost.kind == kind) & (TabPost.valid == 1)
                ).order_by(
                    TabPost.time_create.desc()
                ).limit(num)
            else:
                recent_recs = TabPost.select().where(
                    TabPost.valid == 1
                ).order_by(
                    TabPost.time_create.desc()
                ).limit(num)
        else:
            if kind:
                recent_recs = TabPost.select().where(
                    (TabPost.kind == kind) & (TabPost.valid == 1)
                ).order_by(
                    TabPost.time_update.desc()
                ).limit(num)
            else:
                recent_recs = TabPost.select().where(
                    TabPost.valid == 1
                ).order_by(
                    TabPost.time_update.desc()
                ).limit(num)
        return recent_recs
597415
def inspect(self):
        
        last_attempt = self.get_last_failed_access_attempt(
            ip_address=self.ip,
            captcha_enabled=True,
            captcha_passed=False,
            is_expired=False
        )

        if last_attempt is None and not self.request.user.is_authenticated():
            # create a new entry
            user_access = self._FailedAccessAttemptModel(
                ip_address=self.ip,
                username=self.username,
                captcha_enabled=True,
                captcha_passed=False,
                is_expired=False
            )
        elif last_attempt:
            user_access = last_attempt

        if self.request.method == 'POST':

            if not self.request.user.is_authenticated():

                user_access.user_agent = self.request.META.get('HTTP_USER_AGENT', '<unknown user agent>')[:255]
                user_access.username = self.username
                user_access.failed_attempts += 1
                user_access.params_get = self.request.GET
                user_access.params_post = self.request.POST

                if user_access.failed_attempts >= self.max_failed_attempts:
                    user_access.is_locked = True
                user_access.save()

            elif self.request.user.is_authenticated() and last_attempt:
                last_attempt.is_expired = True
                last_attempt.save()
1334325
def recent(self, with_catalog=True, with_date=True):
        '''
        
        '''
        kwd = {
            'pager': '',
            'title': 'Recent posts.',
            'with_catalog': with_catalog,
            'with_date': with_date,
        }
        self.render('list/post_list.html',
                    kwd=kwd,
                    view=MPost.query_recent(num=20),
                    postrecs=MPost.query_recent(num=2),
                    format_date=tools.format_date,
                    userinfo=self.userinfo,
                    cfg=CMS_CFG, )
944706
def recentlyAdded(self, libtype='episode', maxresults=50):
        
        return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults)
705427
def observed_vis(self, context):
        
        lrow, urow = MS.row_extents(context)

        data = self._manager.ordered_main_table.getcol(
            self._vis_column, startrow=lrow, nrow=urow-lrow)

        return data.reshape(context.shape).astype(context.dtype)
228963
function getDigestsToLastUsed(mainDoc, lastUsedDoc) {
  var result = {};

  // dedup by digest, use the most recent date
  Object.keys(mainDoc._attachments).forEach(function (attName) {
    var att = mainDoc._attachments[attName];
    var existing  = result[att.digest] || 0;
    result[att.digest] = Math.max(existing, lastUsedDoc.lastUsed[att.digest]);
  });

  return result;
}