Create consumption details and price estimates for past months.

        Usually we need to update historical values on resource import.
434903
def _create_historical_estimates(resource, configuration):
    
    today = timezone.now()
    month_start = core_utils.month_start(today)
    while month_start > resource.created:
        month_start -= relativedelta(months=1)
        models.PriceEstimate.create_historical(resource, configuration, max(month_start, resource.created))
520566
def update_meta_info(self):
        """"""
        result = super(BaseStructuredCalibration, self).update_meta_info()

        result['instrument'] = self.instrument
        result['uuid'] = self.uuid
        result['tags'] = self.tags
        result['type'] = self.name()

        minfo = self.meta_info
        try:
            result['mode'] = minfo['mode_name']
            origin = minfo['origin']
            date_obs = origin['date_obs']
        except KeyError:
            origin = {}
            date_obs = "1970-01-01T00:00:00.00"

        result['observation_date'] = conv.convert_date(date_obs)
        result['origin'] = origin

        return result
466002
def update(self, stats):
        """"""

        if self.generate_every != 0 and self._timer.finished():
            self.args.generate_graph = True
            self._timer.reset()

        if not self.args.generate_graph:
            return

        plugins = stats.getPluginsList()
        for plugin_name in plugins:
            plugin = stats._plugins[plugin_name]
            if plugin_name in self.plugins_to_export():
                self.export(plugin_name, plugin.get_export_history())

        logger.info("Graphs created in the folder {}".format(self.path))
        self.args.generate_graph = False
1112035
def _update_capacity(self, data):
        
        if 'ConsumedCapacity' in data:
            # This is all for backwards compatibility
            consumed = data['ConsumedCapacity']
            if not isinstance(consumed, list):
                consumed = [consumed]
            for cap in consumed:
                self.capacity += cap.get('CapacityUnits', 0)
                self.table_capacity += cap.get('Table',
                                               {}).get('CapacityUnits', 0)
                local_indexes = cap.get('LocalSecondaryIndexes', {})
                for k, v in six.iteritems(local_indexes):
                    self.indexes.setdefault(k, 0)
                    self.indexes[k] += v['CapacityUnits']
                global_indexes = cap.get('GlobalSecondaryIndexes', {})
                for k, v in six.iteritems(global_indexes):
                    self.global_indexes.setdefault(k, 0)
                    self.global_indexes[k] += v['CapacityUnits']
767742
def update_rates(self):
        
        source, created = RateSource.objects.get_or_create(name=self.get_source_name())
        source.base_currency = self.get_base_currency()
        source.save()

        for currency, value in six.iteritems(self.get_rates()):
            try:
                rate = Rate.objects.get(source=source, currency=currency)
            except Rate.DoesNotExist:
                rate = Rate(source=source, currency=currency)

            rate.value = value
            rate.save()
762986
def started_plan_summary_for(self, year, month):
		""""""
		return (
			self.started_during(year, month)
			.values("plan")
			.order_by()
			.annotate(count=models.Count("plan"))
		)
852464
def update(self, new_vals):
        
        for k, v in six.iteritems(new_vals):
            k = k.strip()
            if k in self.row:
                warnings.warn("Adding history key ({}) that is already set in this step".format(
                    k), wandb.WandbWarning)
            self.row[k] = v
464206
protected function populate()
    {
        $this->collection = AnalyticsDb::ADB_DIMS;

        // $match
        $this->pipeline['$match']['entity'] = $this->entity;
        $this->pipeline['$match']['ts'] = ['$gte' => $this->dateRange[0], '$lte' => $this->dateRange[1]];
        if(!empty($this->ref)){
            $this->pipeline['$match']['count.' . $this->ref] = ['$exists' => true];
        }else{
            $this->pipeline['$match']['count'] = ['$exists' => true];
        }


        // $project
        $this->pipeline['$project'] = [
            'ts'     => 1,
            'entity' => 1,
            'month'  => 1,
            'year'   => 1,
            'name'   => 1,
            'value'  => 1,
            'total'  => 1
        ];

        if (!empty($this->ref)) {
            $this->pipeline['$project']['count.' . $this->ref] = 1;
        }

        // $group
        $this->pipeline['$group'] = ['_id' => '$ts', 'totalCount' => ['$sum' => $this->getSumField()]];

        // $sort -> by timestamp
        $this->pipeline['$sort'] = ['_id' => 1];
    }
1098391
private void updateTimestamps(final Entry entry) {
        // We're not differenting between an update and an edit (yet)
        entry.setUpdated(new Date());

        AppModule appModule = (AppModule) entry.getModule(AppModule.URI);
        if (appModule == null) {
            appModule = new AppModuleImpl();
            final List<Module> modules = entry.getModules() == null ? new ArrayList<Module>() : entry.getModules();
            modules.add(appModule);
            entry.setModules(modules);
        }
        appModule.setEdited(entry.getUpdated());
    }
252803
def rebuildMonth( self ):
        
        # make sure we start at 0 for sunday vs. 7 for sunday
        day_map     = dict([(i+1, i+1) for i in range(7)])
        day_map[7]  = 0
        
        today   = QDate.currentDate()
        curr    = self.currentDate()
        first   = QDate(curr.year(), curr.month(), 1)
        last    = QDate(curr.year(), curr.month(), curr.daysInMonth())
        first   = first.addDays(-day_map[first.dayOfWeek()])
        last    = last.addDays(6-day_map[last.dayOfWeek()])
        
        cols    = 7
        rows    = (first.daysTo(last) + 1) / cols
        
        hlines  = []
        vlines  = []
        
        padx    = 6
        pady    = 6
        header  = 24
        
        w       = self.width() - (2 * padx)
        h       = self.height() - (2 * pady)
        
        dw      = (w / cols) - 1
        dh      = ((h - header) / rows) - 1
        
        x0      = padx
        y0      = pady + header
        
        x       = x0
        y       = y0
        
        for row in range(rows + 1):
            hlines.append(QLine(x0, y, w, y))
            y += dh
        
        for col in range(cols + 1):
            vlines.append(QLine(x, y0, x, h))
            x += dw
        
        self._buildData['grid'] = hlines + vlines
        
        # draw the date fields
        date = first
        row  = 0
        col  = 0
        
        # draw the headers
        x = x0
        y = pady
        
        regular_text = []
        mid_text     = []
        self._buildData['regular_text'] = regular_text
        self._buildData['mid_text']     = mid_text
        
        for day in ('Sun', 'Mon','Tue','Wed','Thu','Fri','Sat'):
            regular_text.append((x + 5,
                                 y,
                                 dw,
                                 y0,
                                 Qt.AlignLeft | Qt.AlignVCenter,
                                 day))
            x += dw
        
        for i in range(first.daysTo(last) + 1):
            top    = (y0 + (row * dh))
            left   = (x0 + (col * dw))
            rect   = QRectF(left - 1, top, dw, dh)
            
            # mark the current date on the calendar
            if ( date == curr ):
                self._buildData['curr_date'] = rect
            
            # mark today's date on the calendar
            elif ( date == today ):
                self._buildData['today'] = rect
            
            # determine how to draw the calendar
            format = 'd'
            if ( date.day() == 1 ):
                format = 'MMM d'
            
            # determine the color to draw the text
            if ( date.month() == curr.month() ):
                text = regular_text
            else:
                text = mid_text
            
            # draw the text
            text.append((left + 2,
                         top + 2,
                         dw - 4,
                         dh - 4,
                         Qt.AlignTop | Qt.AlignLeft,
                         date.toString(format)))
            
            # update the limits
            if ( not i ):
                self._minimumDate = date
            self._maximumDate = date
            
            self._dateGrid[date.toJulianDay()] = ((row, col), rect)
            if ( col == (cols - 1) ):
                row += 1
                col = 0
            else:
                col += 1
                
            date = date.addDays(1)
549223
def add_update_date(self, item):
        
        updated = unixtime_to_datetime(item['updated_on'])
        timestamp = unixtime_to_datetime(item['timestamp'])
        item['metadata__updated_on'] = updated.isoformat()
        # Also add timestamp used in incremental enrichment
        item['metadata__timestamp'] = timestamp.isoformat()
1170824
def updateIncomeProcess(self):
        '''
        
        '''
        original_time = self.time_flow
        self.timeFwd()
        IncomeDstn, PermShkDstn, TranShkDstn = constructLognormalIncomeProcessUnemployment(self)
        self.IncomeDstn = IncomeDstn
        self.PermShkDstn = PermShkDstn
        self.TranShkDstn = TranShkDstn
        self.addToTimeVary('IncomeDstn','PermShkDstn','TranShkDstn')
        if not original_time:
            self.timeRev()
1200718
def reinit_configurations(self, request):
        
        now = timezone.now()

        # Step 1. Collect all resources with changed configuration.
        changed_resources = []
        for resource_model in CostTrackingRegister.registered_resources:
            for resource in resource_model.objects.all():
                try:
                    pe = models.PriceEstimate.objects.get(scope=resource, month=now.month, year=now.year)
                except models.PriceEstimate.DoesNotExist:
                    changed_resources.append(resource)
                else:
                    new_configuration = CostTrackingRegister.get_configuration(resource)
                    if new_configuration != pe.consumption_details.configuration:
                        changed_resources.append(resource)

        # Step 2. Re-init configuration and recalculate estimate for changed resources.
        for resource in changed_resources:
            models.PriceEstimate.update_resource_estimate(resource, CostTrackingRegister.get_configuration(resource))

        message = _('Configuration was reinitialized for %(count)s resources') % {'count': len(changed_resources)}
        self.message_user(request, message)

        return redirect(reverse('admin:cost_tracking_defaultpricelistitem_changelist'))
1241297
private void fillMetaData() {
        metaDataBuffer.putInt(MONITOR_VERSION_OFFSET, MONITOR_VERSION);
        metaDataBuffer.putInt(GW_DATA_REFERENCE_OFFSET, GW_DATA_OFFSET);
        metaDataBuffer.putInt(SERVICE_DATA_REFERENCE_OFFSET, serviceDataOffset);
        metaDataBuffer.putStringUtf8(GW_ID_OFFSET, gatewayId, ByteOrder.nativeOrder());
        metaDataBuffer.putInt(gwCountersLblBuffersReferenceOffset, 0);
        metaDataBuffer.putInt(gwCountersLblBuffersLengthOffset, GATEWAY_COUNTER_LABELS_BUFFER_LENGTH);
        metaDataBuffer.putInt(gwCountersValueBuffersReferenceOffset, 0);
        metaDataBuffer.putInt(gwCountersValueBuffersLengthOffset, GATEWAY_COUNTER_VALUES_BUFFER_LENGTH);
        metaDataBuffer.putInt(noOfServicesOffset, 0);
    }
1150906
def update_index(entries):
    
    context = GLOBAL_TEMPLATE_CONTEXT.copy()
    context['entries'] = entries
    context['last_build'] = datetime.datetime.now().strftime(
        "%Y-%m-%dT%H:%M:%SZ")

    list(map(lambda x: _render(context, x[0],
                               os.path.join(CONFIG['output_to'], x[1])),
             (('entry_index.html', 'index.html'), ('atom.xml', 'atom.xml'))))
403329
def make_data():
    """"""
    I,d = multidict({1:80, 2:270, 3:250, 4:160, 5:180})            # demand
    J,M,f = multidict({1:[500,1000], 2:[500,1000], 3:[500,1000]}) # capacity, fixed costs
    c = {(1,1):4,  (1,2):6,  (1,3):9,    # transportation costs
         (2,1):5,  (2,2):4,  (2,3):7,
         (3,1):6,  (3,2):3,  (3,3):4,
         (4,1):8,  (4,2):5,  (4,3):3,
         (5,1):10, (5,2):8,  (5,3):4,
         }
    return I,J,d,M,f,c
679568
def update_stats_history(self):
        """"""
        # If the plugin data is a dict, the dict's key should be used
        if self.get_key() is None:
            item_name = ''
        else:
            item_name = self.get_key()
        # Build the history
        if self.get_export() and self.history_enable():
            for i in self.get_items_history_list():
                if isinstance(self.get_export(), list):
                    # Stats is a list of data
                    # Iter throught it (for exemple, iter throught network
                    # interface)
                    for l in self.get_export():
                        self.stats_history.add(
                            nativestr(l[item_name]) + '_' + nativestr(i['name']),
                            l[i['name']],
                            description=i['description'],
                            history_max_size=self._limits['history_size'])
                else:
                    # Stats is not a list
                    # Add the item to the history directly
                    self.stats_history.add(nativestr(i['name']),
                                           self.get_export()[i['name']],
                                           description=i['description'],
                                           history_max_size=self._limits['history_size'])