Adds ``election_day`` to serializer context.
967463
def get_serializer_context(self):
        """"""
        context = super(OfficeMixin, self).get_serializer_context()
        context['election_date'] = self.kwargs['date']
        return context
731410
def write(self, outfile, encoding):
        
        """
        cal = Calendar()
        cal.add('version', '2.0')
        cal.add('calscale', 'GREGORIAN')

        for ifield, efield in FEED_FIELD_MAP:
            val = self.feed.get(ifield)
            if val is not None:
                cal.add(efield, val)

        self.write_items(cal)

        to_ical = getattr(cal, 'as_string', None)
        if not to_ical:
            to_ical = cal.to_ical
        outfile.write(to_ical())
159410
def serialize(self, value, **kwargs):
        """"""
        return [self.item_type.serialize(val, **kwargs) for val in value]
264063
def _make_serializer(meas, schema, rm_none, extra_tags, placeholder):  # noqa: C901
    """"""
    _validate_schema(schema, placeholder)
    tags = []
    fields = []
    ts = None
    meas = meas
    for k, t in schema.items():
        if t is MEASUREMENT:
            meas = f"{{i.{k}}}"
        elif t is TIMEINT:
            ts = f"{{i.{k}}}"
        elif t is TIMESTR:
            if pd:
                ts = f"{{pd.Timestamp(i.{k} or 0).value}}"
            else:
                ts = f"{{dt_to_int(str_to_dt(i.{k}))}}"
        elif t is TIMEDT:
            if pd:
                ts = f"{{pd.Timestamp(i.{k} or 0).value}}"
            else:
                ts = f"{{dt_to_int(i.{k})}}"
        elif t is TAG:
            tags.append(f"{k}={{str(i.{k}).translate(tag_escape)}}")
        elif t is TAGENUM:
            tags.append(f"{k}={{getattr(i.{k}, 'name', i.{k} or None)}}")
        elif t in (FLOAT, BOOL):
            fields.append(f"{k}={{i.{k}}}")
        elif t is INT:
            fields.append(f"{k}={{i.{k}}}i")
        elif t is STR:
            fields.append(f"{k}=\\\"{{str(i.{k}).translate(str_escape)}}\\\"")
        elif t is ENUM:
            fields.append(f"{k}=\\\"{{getattr(i.{k}, 'name', i.{k} or None)}}\\\"")
        else:
            raise SchemaError(f"Invalid attribute type {k!r}: {t!r}")
    extra_tags = extra_tags or {}
    for k, v in extra_tags.items():
        tags.append(f"{k}={v}")
    if placeholder:
        fields.insert(0, f"_=true")

    sep = ',' if tags else ''
    ts = f' {ts}' if ts else ''
    fmt = f"{meas}{sep}{','.join(tags)} {','.join(fields)}{ts}"
    if rm_none:
        # Has substantial runtime impact. Best avoided if performance is critical.
        # First field can't be removed.
        pat = r',\w+="?None"?i?'
        f = eval('lambda i: re.sub(r\'{}\', "", f"{}").encode()'.format(pat, fmt))
    else:
        f = eval('lambda i: f"{}".encode()'.format(fmt))
    f.__doc__ = "Returns InfluxDB line protocol representation of user-defined class"
    f._args = dict(meas=meas, schema=schema, rm_none=rm_none,
                   extra_tags=extra_tags, placeholder=placeholder)
    return f
553749
def xml(t)
      t.campaignId campaign.id
      t.name name
      t.status "ENABLED"
      @bids.to_xml(t) if @bids
    end
344386
def _AddSerializePartialToStringMethod(message_descriptor, cls):
  """"""

  def SerializePartialToString(self):
    out = BytesIO()
    self._InternalSerialize(out.write)
    return out.getvalue()
  cls.SerializePartialToString = SerializePartialToString

  def InternalSerialize(self, write_bytes):
    for field_descriptor, field_value in self.ListFields():
      field_descriptor._encoder(write_bytes, field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      write_bytes(tag_bytes)
      write_bytes(value_bytes)
  cls._InternalSerialize = InternalSerialize
1265295
def get_elections(self, obj):
        """"""
        election_day = ElectionDay.objects.get(
            date=self.context['election_date'])

        elections = list(obj.elections.filter(election_day=election_day))
        district = DivisionLevel.objects.get(name=DivisionLevel.DISTRICT)
        for district in obj.children.filter(level=district):
            elections.extend(
                list(district.elections.filter(
                    election_day=election_day,
                    meta__isnull=False
                ))
            )

        return ElectionSerializer(elections, many=True).data
749865
private function serializeRawData(GetResponseForControllerResultEvent $event, Request $request, $controllerResult): void
    {
        if (\is_object($controllerResult)) {
            $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $request->attributes->get('_api_normalization_context', [])));

            return;
        }

        if (!$this->serializer instanceof EncoderInterface) {
            throw new RuntimeException(sprintf('The serializer instance must implements the "%s" interface.', EncoderInterface::class));
        }

        $event->setControllerResult($this->serializer->encode($controllerResult, $request->getRequestFormat()));
    }
910057
public function addData(Serializing $event)
    {
        if ($event->isSerializer(ForumSerializer::class) && $event->actor->isAdmin()) {
            $event->attributes['datitisev-dashboard.data'] = [
                'postCount'       => Post::where('type', 'comment')->count(),
                'discussionCount' => Discussion::count(),
                'userCount'       => User::where('is_email_confirmed', 1)->count(),
            ];
        }
    }
1134946
public JsonElement serialize(Calendar src, Type typeOfSrc,
			JsonSerializationContext context) {
		int year = src.get(Calendar.YEAR);
		String month = this.formatter.format(Double.valueOf(src
				.get(Calendar.MONTH) + 1));
		String day = this.formatter.format(Double.valueOf(src
				.get(Calendar.DAY_OF_MONTH)));
		String hour = this.formatter.format(Double.valueOf(src
				.get(Calendar.HOUR_OF_DAY)));
		String minute = this.formatter.format(Double.valueOf(src
				.get(Calendar.MINUTE)));
		String formattedDate = year + "-" + month + "-" + day + "T" + hour
				+ ":" + minute;

		return context.serialize(formattedDate);
	}
789973
def _AddSerializedEvent(self, event):
    
    identifier = identifiers.SQLTableIdentifier(
        self._CONTAINER_TYPE_EVENT,
        self._serialized_event_heap.number_of_events + 1)
    event.SetIdentifier(identifier)

    serialized_data = self._SerializeAttributeContainer(event)

    self._serialized_event_heap.PushEvent(event.timestamp, serialized_data)

    if self._serialized_event_heap.data_size > self._maximum_buffer_size:
      self._WriteSerializedAttributeContainerList(self._CONTAINER_TYPE_EVENT)
1334844
def get_elections(self, obj):
        """"""
        election_day = ElectionDay.objects.get(
            date=self.context["election_date"]
        )

        kwargs = {"race__office__body": obj, "election_day": election_day}
        if self.context.get("division") and obj.slug == "senate":
            kwargs["division"] = self.context["division"]
        elif self.context.get("division") and obj.slug == "house":
            kwargs["division__parent"] = self.context["division"]

        if obj.slug == "house" and not self.context.get("division"):
            kwargs["race__special"] = False

        elections = Election.objects.filter(**kwargs)
        return ElectionSerializer(elections, many=True).data
968991
def choice_default_serializer(self, obj):
        """"""
        if not obj:
            return None
        self.choice_default_add_related_pks(obj)
        return dict((
            ('id', obj.id),
            ('choice_text', obj.choice_text),
            self.field_to_json(
                'PK', 'question', model=Question, pk=obj.question_id),
            self.field_to_json(
                'PKList', 'voters', model=User, pks=obj._voter_pks)
        ))
613151
def get_serializer(self, *args, **kwargs):
        """"""
        init_args = {
            k: v for k, v in six.iteritems(self.kwargs)
            if k in self.SERIALIZER_KWARGS
        }

        kwargs = self._inherit_parent_kwargs(kwargs)
        init_args.update(kwargs)

        if self.embed and self._is_dynamic:
            init_args['embed'] = True

        return self._get_cached_serializer(args, init_args)
624173
def bootstrap_general_election(self, election):
        
        election_day = election.election_day
        page_type, created = PageType.objects.get_or_create(
            model_type=ContentType.objects.get(
                app_label="election", model="electionday"
            ),
            election_day=election_day,
        )
        PageContent.objects.get_or_create(
            content_type=ContentType.objects.get_for_model(page_type),
            object_id=page_type.pk,
            election_day=election_day,
        )
315547
def add_nulldata(self, rawtx, hexdata):
        """"""
        tx = deserialize.unsignedtx(rawtx)
        nulldata_txout = deserialize.nulldata_txout(hexdata)
        tx = control.add_nulldata_output(tx, nulldata_txout)
        return serialize.tx(tx)
795019
def add(self, timestamp, information):
        
        try:
            item = Schema(CollectorStage.schema_event_items()).validate({
                'timestamp': timestamp, 'information': information
            })
            self.events.append(item)
        except SchemaError as exception:
            Logger.get_logger(__name__).error(exception)
            raise RuntimeError(str(exception))