text:
/*

Foment

*/

#ifdef FOMENT_WINDOWS
#include <windows.h>
#endif // FOMENT_WINDOWS
#ifdef FOMENT_UNIX
#include <pthread.h>
#endif // FOMENT_UNIX
#include "foment.hpp"
#include "syncthrd.hpp"
#include "io.hpp"
#include "compile.hpp"

// Write

static inline long_t HasSlotsP(FObject obj)
{
    if (ObjectP(obj) == 0)
        return(0);

    FObjectTag tag = ObjectTag(obj);
    if (tag > FreeTag || ObjectTypes[tag].SlotCount == 0)
        return(0);
    return(1);
}

FWriteContext::FWriteContext(FObject port, long_t df)
{
    this->Port = port;
    DisplayFlag = df;
    WriteType = NoWrite;
    HashTable = NoValueObject;
    SharedCount = 0;
    PreviousLabel = 1;
}

void FWriteContext::Prepare(FObject obj, FWriteType wt)
{
    FAssert(WriteType == NoWrite);
    FAssert(wt != NoWrite);

    if (wt != SimpleWrite && HasSlotsP(obj))
    {
        HashTable = MakeEqHashTable(128, 0);
        FindSharedObjects(obj, wt);
        if (SharedCount == 0)
            WriteType = SimpleWrite;
        else
            WriteType = wt;
    }
    else
        WriteType = SimpleWrite;

    FAssert(WriteType != NoWrite);
}

void FWriteContext::Write(FObject obj)
{
    FAssert(WriteType != NoWrite);

    if (WriteType != SimpleWrite && HasSlotsP(obj))
    {
        FObject val = HashTableRef(HashTable, obj, MakeFixnum(1));

        FAssert(FixnumP(val));

        if (AsFixnum(val) > 0)
        {
            if (AsFixnum(val) > 1)
            {
                PreviousLabel -= 1;
                HashTableSet(HashTable, obj, MakeFixnum(PreviousLabel));

                WriteCh('#');
                FCh s[8];
                long_t sl = FixnumAsString(- PreviousLabel, s, 10);
                WriteString(s, sl);
                WriteCh('=');
            }

            if (PairP(obj))
            {
                WriteCh('(');
                for (;;)
                {
                    Write(First(obj));
                    if (PairP(Rest(obj))
                            && HashTableRef(HashTable, Rest(obj), MakeFixnum(1)) == MakeFixnum(1))
                    {
                        WriteCh(' ');
                        obj = Rest(obj);
                    }
                    else if (Rest(obj) == EmptyListObject)
                    {
                        WriteCh(')');
                        break;
                    }
                    else
                    {
                        WriteStringC(" . ");
                        Write(Rest(obj));
                        WriteCh(')');
                        break;
                    }
                }
            }
            else
                WriteSimple(obj);
        }
        else
        {
            FAssert(FixnumP(val) && AsFixnum(val) < 1);

            WriteCh('#');
            FCh s[8];
            long_t sl = FixnumAsString(- AsFixnum(val), s, 10);
            WriteString(s, sl);
            WriteCh('#');
        }
    }
    else
        WriteSimple(obj);
}

void FWriteContext::Display(FObject obj)
{
    long_t df = DisplayFlag;

    DisplayFlag = 1;
    Write(obj);
    DisplayFlag = df;
}

void FWriteContext::WriteCh(FCh ch)
{
    FAssert(WriteType != NoWrite);

    ::WriteCh(Port, ch);
}

void FWriteContext::WriteString(FCh * s, ulong_t sl)
{
    FAssert(WriteType != NoWrite);

    ::WriteString(Port, s, sl);
}

void FWriteContext::WriteStringC(const char * s)
{
    FAssert(WriteType != NoWrite);

    ::WriteStringC(Port, s);
}

void FWriteContext::FindSharedObjects(FObject obj, FWriteType wt)
{
    FAssert(wt == CircularWrite || wt == SharedWrite);

Again:

    if (HasSlotsP(obj))
    {
        FObject val = HashTableRef(HashTable, obj, MakeFixnum(0));

        FAssert(FixnumP(val));

        HashTableSet(HashTable, obj, MakeFixnum(AsFixnum(val) + 1));

        if (AsFixnum(val) == 0)
        {
            if (PairP(obj))
            {
                FindSharedObjects(First(obj), wt);
                if (wt == CircularWrite)
                    FindSharedObjects(Rest(obj), wt);
                else
                {
                    obj = Rest(obj);
                    goto Again;
                }
            }
            else
            {
                for (ulong_t idx = 0; idx < SlotCount(AsHeader(obj)); idx++)
                    FindSharedObjects(((FObject *) obj)[idx], wt);
            }

            if (wt == CircularWrite)
            {
                val = HashTableRef(HashTable, obj, MakeFixnum(0));

                FAssert(FixnumP(val));
                FAssert(AsFixnum(val) > 0);

                if (AsFixnum(val) == 1)
                    HashTableDelete(HashTable, obj);
            }
        }
        else
            SharedCount += 1;
    }
}

static void WriteUnknown(FWriteContext * wctx, FObject obj)
{
    FCh s[16];
    long_t sl = FixnumAsString((long_t) obj, s, 16);

    wctx->WriteStringC("#<unknown: ");
    wctx->WriteString(s, sl);
    wctx->WriteCh('>');
}

void FWriteContext::WriteSimple(FObject obj)
{
    if (ObjectP(obj))
    {
        FObjectTag tag = ObjectTag(obj);

        if (tag < FreeTag && ObjectTypes[tag].Write != 0)
            ObjectTypes[tag].Write(this, obj);
        else
            WriteUnknown(this, obj);
    }
    else if (FixnumP(obj))
    {
        FCh s[64];
        long_t sl = FixnumAsString(AsFixnum(obj), s, 10);

        WriteString(s, sl);
    }
    else if (DirectP(obj, ImmediateDirectTag))
    {
        switch (ImmediateTag(obj))
        {
        case CharacterTag:
            if (DisplayFlag)
                WriteCh(AsCharacter(obj));
            else if (AsCharacter(obj) == 0x07)
                WriteStringC("#\\alarm");
            else if (AsCharacter(obj) == 0x08)
                WriteStringC("#\\backspace");
            else if (AsCharacter(obj) == 0x7F)
                WriteStringC("#\\delete");
            else if (AsCharacter(obj) == 0x1B)
                WriteStringC("#\\escape");
            else if (AsCharacter(obj) == 0x0A)
                WriteStringC("#\\newline");
            else if (AsCharacter(obj) == 0x00)
                WriteStringC("#\\null");
            else if (AsCharacter(obj) == 0x0D)
                WriteStringC("#\\return");
            else if (AsCharacter(obj) == 0x20)
                WriteStringC("#\\space");
            else if (AsCharacter(obj) == 0x09)
                WriteStringC("#\\tab");
            else if (AsCharacter(obj) < 128)
            {
                WriteStringC("#\\");
                WriteCh(AsCharacter(obj));
            }
            else
            {
                FCh s[16];
                long_t sl = FixnumAsString(AsCharacter(obj), s, 16);
                WriteStringC("#\\x");
                WriteString(s, sl);
            }
            break;

        case MiscellaneousTag:
            if (obj == EmptyListObject)
                WriteStringC("()");
            else if (obj == EndOfFileObject)
                WriteStringC("#<end-of-file>");
            else if (obj == NoValueObject)
                WriteStringC("#<no-value>");
            else if (obj == WantValuesObject)
                WriteStringC("#<want-values>");
            else if (obj == NotFoundObject)
                WriteStringC("#<not-found>");
            else if (obj == MatchAnyObject)
                WriteStringC("#<match-any>");
            else
                WriteUnknown(this, obj);
            break;

        case SpecialSyntaxTag:
            WriteSpecialSyntax(this, obj);
            break;

        case InstructionTag:
            WriteInstruction(this, obj);
            break;

        case ValuesCountTag:
        {
            WriteStringC("#<values-count: ");

            FCh s[16];
            long_t sl = FixnumAsString(AsValuesCount(obj), s, 10);
            WriteString(s, sl);

            WriteCh('>');
            break;
        }

        case BooleanTag:
            if (obj == FalseObject)
                WriteStringC("#f");
            else if (obj == TrueObject)
                WriteStringC("#t");
            else
                WriteUnknown(this, obj);
            break;

        default:
            FAssert(0);
        }
    }
    else
    {
        FAssert(0);
    }
}

void WritePortObject(FWriteContext * wctx, FObject obj)
{
    FCh s[16];
    long_t sl = FixnumAsString((long_t) obj, s, 16);

    wctx->WriteStringC("#<");
    if (TextualPortP(obj))
        wctx->WriteStringC("textual-");
    else
    {
        FAssert(BinaryPortP(obj));

        wctx->WriteStringC("binary-");
    }

    if (InputPortP(obj))
        wctx->WriteStringC("input-");
    if (OutputPortP(obj))
        wctx->WriteStringC("output-");
    wctx->WriteStringC("port: #x");
    wctx->WriteString(s, sl);

    if (InputPortOpenP(obj) == 0 && OutputPortOpenP(obj) == 0)
        wctx->WriteStringC(" closed");

    if (StringP(AsGenericPort(obj)->Name))
    {
        wctx->WriteCh(' ');
        wctx->WriteString(AsString(AsGenericPort(obj)->Name)->String,
                StringLength(AsGenericPort(obj)->Name));
    }

    if (InputPortP(obj))
    {
        if (BinaryPortP(obj))
        {
            wctx->WriteStringC(" offset: ");
            sl = FixnumAsString(GetOffset(obj), s, 10);
            wctx->WriteString(s, sl);
        }
        else
        {
            FAssert(TextualPortP(obj));

            wctx->WriteStringC(" line: ");
            sl = FixnumAsString(GetLineColumn(obj, 0), s, 10);
            wctx->WriteString(s, sl);
        }
    }

    wctx->WriteCh('>');
}

void Write(FObject port, FObject obj, long_t df)
{
    FWriteContext wctx(port, df);

    wctx.Prepare(obj, CircularWrite);
    wctx.Write(obj);
}

void WriteShared(FObject port, FObject obj, long_t df)
{
    FWriteContext wctx(port, df);

    wctx.Prepare(obj, SharedWrite);
    wctx.Write(obj);
}

void WriteSimple(FObject port, FObject obj, long_t df)
{
    FWriteContext wctx(port, df);

    wctx.Prepare(obj, SimpleWrite);
    wctx.Write(obj);
}

// ---- Primitives ----

Define("write", WritePrimitive)(long_t argc, FObject argv[])
{
    OneOrTwoArgsCheck("write", argc);
    FObject port = (argc == 2 ? argv[1] : CurrentOutputPort());
    TextualOutputPortArgCheck("write", port);

    Write(port, argv[0], 0);
    return(NoValueObject);
}

Define("write-shared", WriteSharedPrimitive)(long_t argc, FObject argv[])
{
    OneOrTwoArgsCheck("write-shared", argc);
    FObject port = (argc == 2 ? argv[1] : CurrentOutputPort());
    TextualOutputPortArgCheck("write-shared", port);

    WriteShared(port, argv[0], 0);
    return(NoValueObject);
}

Define("write-simple", WriteSimplePrimitive)(long_t argc, FObject argv[])
{
    OneOrTwoArgsCheck("write-simple", argc);
    FObject port = (argc == 2 ? argv[1] : CurrentOutputPort());
    TextualOutputPortArgCheck("write-simple", port);

    WriteSimple(port, argv[0], 0);
    return(NoValueObject);
}

Define("display", DisplayPrimitive)(long_t argc, FObject argv[])
{
    OneOrTwoArgsCheck("display", argc);
    FObject port = (argc == 2 ? argv[1] : CurrentOutputPort());
    TextualOutputPortArgCheck("display", port);

    Write(port, argv[0], 1);
    return(NoValueObject);
}

Define("newline", NewlinePrimitive)(long_t argc, FObject argv[])
{
    ZeroOrOneArgsCheck("newline", argc);
    FObject port = (argc == 1 ? argv[0] : CurrentOutputPort());
    TextualOutputPortArgCheck("newline", port);

    WriteCh(port, '\n');
    return(NoValueObject);
}

Define("write-char", WriteCharPrimitive)(long_t argc, FObject argv[])
{
    OneOrTwoArgsCheck("write-char", argc);
    CharacterArgCheck("write-char", argv[0]);
    FObject port = (argc == 2 ? argv[1] : CurrentOutputPort());
    TextualOutputPortArgCheck("write-char", port);

    WriteCh(port, AsCharacter(argv[0]));
    return(NoValueObject);
}

Define("write-string", WriteStringPrimitive)(long_t argc, FObject argv[])
{
    OneToFourArgsCheck("write-string", argc);
    StringArgCheck("write-string", argv[0]);
    FObject port = (argc > 1 ? argv[1] : CurrentOutputPort());
    TextualOutputPortArgCheck("write-string", port);

    long_t strt;
    long_t end;
    if (argc > 2)
    {
        IndexArgCheck("write-string", argv[2], StringLength(argv[0]));

        strt = AsFixnum(argv[2]);

        if (argc > 3)
        {
            EndIndexArgCheck("write-string", argv[3], strt, StringLength(argv[0]));

            end = AsFixnum(argv[3]);
        }
        else
            end = (long_t) StringLength(argv[0]);
    }
    else
    {
        strt = 0;
        end = (long_t) StringLength(argv[0]);
    }

    WriteString(port, AsString(argv[0])->String + strt, end - strt);
    return(NoValueObject);
}

Define("write-u8", WriteU8Primitive)(long_t argc, FObject argv[])
{
    OneOrTwoArgsCheck("write-u8", argc);
    ByteArgCheck("write-u8", argv[0]);
    FObject port = (argc == 2 ? argv[1] : CurrentOutputPort());
    BinaryOutputPortArgCheck("write-u8", port);

    FByte b = (FByte) AsFixnum(argv[0]);
    WriteBytes(port, &b, 1);
    return(NoValueObject);
}

Define("write-bytevector", WriteBytevectorPrimitive)(long_t argc, FObject argv[])
{
    OneToFourArgsCheck("write-bytevector", argc);
    BytevectorArgCheck("write-bytevector", argv[0]);
    FObject port = (argc > 1 ? argv[1] : CurrentOutputPort());
    BinaryOutputPortArgCheck("write-bytevector", port);

    long_t strt;
    long_t end;
    if (argc > 2)
    {
        IndexArgCheck("write-bytevector", argv[2], BytevectorLength(argv[0]));

        strt = AsFixnum(argv[2]);

        if (argc > 3)
        {
            EndIndexArgCheck("write-bytevector", argv[3], strt, BytevectorLength(argv[0]));

            end = AsFixnum(argv[3]);
        }
        else
            end = (long_t) BytevectorLength(argv[0]);
    }
    else
    {
        strt = 0;
        end = (long_t) BytevectorLength(argv[0]);
    }

    WriteBytes(port, AsBytevector(argv[0])->Vector + strt, end - strt);
    return(NoValueObject);
}

Define("flush-output-port", FlushOutputPortPrimitive)(long_t argc, FObject argv[])
{
    ZeroOrOneArgsCheck("flush-output-port", argc);
    FObject port = (argc == 1 ? argv[0] : CurrentOutputPort());
    OutputPortArgCheck("flush-output-port", port);

    FlushOutput(port);
    return(NoValueObject);
}

static FObject Primitives[] =
{
    WritePrimitive,
    WriteSharedPrimitive,
    WriteSimplePrimitive,
    DisplayPrimitive,
    NewlinePrimitive,
    WriteCharPrimitive,
    WriteStringPrimitive,
    WriteU8Primitive,
    WriteBytevectorPrimitive,
    FlushOutputPortPrimitive
};

void SetupWrite()
{
    for (ulong_t idx = 0; idx < sizeof(Primitives) / sizeof(FPrimitive *); idx++)
        DefinePrimitive(Bedrock, BedrockLibrary, Primitives[idx]);
}


text:
package com.ttdevs.android.tablayout;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TabFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        TextView textView = new TextView(inflater.getContext());
        textView.setText("I'm tab content!" + Math.random());
        textView.setGravity(Gravity.CENTER);
        return textView;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.helix.controller.stages;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerProperties;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.controller.pipeline.AbstractBaseStage;
import org.apache.helix.controller.pipeline.StageException;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.Message;
import org.apache.helix.model.Partition;
import org.apache.helix.model.Resource;
import org.apache.log4j.Logger;

public class TaskAssignmentStage extends AbstractBaseStage {
  private static Logger logger = Logger.getLogger(TaskAssignmentStage.class);

  @Override
  public void process(ClusterEvent event) throws Exception {
    long startTime = System.currentTimeMillis();
    logger.info("START TaskAssignmentStage.process()");

    HelixManager manager = event.getAttribute("helixmanager");
    Map<String, Resource> resourceMap = event.getAttribute(AttributeName.RESOURCES.toString());
    MessageThrottleStageOutput messageOutput =
        event.getAttribute(AttributeName.MESSAGES_THROTTLE.toString());
    ClusterDataCache cache = event.getAttribute("ClusterDataCache");
    Map<String, LiveInstance> liveInstanceMap = cache.getLiveInstances();

    if (manager == null || resourceMap == null || messageOutput == null || cache == null
        || liveInstanceMap == null) {
      throw new StageException("Missing attributes in event:" + event
          + ". Requires HelixManager|RESOURCES|MESSAGES_THROTTLE|DataCache|liveInstanceMap");
    }

    HelixDataAccessor dataAccessor = manager.getHelixDataAccessor();
    List<Message> messagesToSend = new ArrayList<Message>();
    for (String resourceName : resourceMap.keySet()) {
      Resource resource = resourceMap.get(resourceName);
      for (Partition partition : resource.getPartitions()) {
        List<Message> messages = messageOutput.getMessages(resourceName, partition);
        messagesToSend.addAll(messages);
      }
    }

    List<Message> outputMessages =
        batchMessage(dataAccessor.keyBuilder(), messagesToSend, resourceMap, liveInstanceMap,
            manager.getProperties());
    sendMessages(dataAccessor, outputMessages);

    long cacheStart = System.currentTimeMillis();
    cache.cacheMessages(outputMessages);
    long cacheEnd = System.currentTimeMillis();
    logger.debug("Caching messages took " + (cacheEnd - cacheStart) + " ms");

    long endTime = System.currentTimeMillis();
    logger.info("END TaskAssignmentStage.process(). took: " + (endTime - startTime) + " ms");

  }

  List<Message> batchMessage(Builder keyBuilder, List<Message> messages,
      Map<String, Resource> resourceMap, Map<String, LiveInstance> liveInstanceMap,
      HelixManagerProperties properties) {
    // group messages by its CurrentState path + "/" + fromState + "/" + toState
    Map<String, Message> batchMessages = new HashMap<String, Message>();
    List<Message> outputMessages = new ArrayList<Message>();

    Iterator<Message> iter = messages.iterator();
    while (iter.hasNext()) {
      Message message = iter.next();
      String resourceName = message.getResourceName();
      Resource resource = resourceMap.get(resourceName);

      String instanceName = message.getTgtName();
      LiveInstance liveInstance = liveInstanceMap.get(instanceName);
      String participantVersion = null;
      if (liveInstance != null) {
        participantVersion = liveInstance.getHelixVersion();
      }

      if (resource == null || !resource.getBatchMessageMode() || participantVersion == null
          || !properties.isFeatureSupported("batch_message", participantVersion)) {
        outputMessages.add(message);
        continue;
      }

      String key =
          keyBuilder.currentState(message.getTgtName(), message.getTgtSessionId(),
              message.getResourceName()).getPath()
              + "/" + message.getFromState() + "/" + message.getToState();

      if (!batchMessages.containsKey(key)) {
        Message batchMessage = new Message(message.getRecord());
        batchMessage.setBatchMessageMode(true);
        outputMessages.add(batchMessage);
        batchMessages.put(key, batchMessage);
      }
      batchMessages.get(key).addPartitionName(message.getPartitionName());
    }

    return outputMessages;
  }

  protected void sendMessages(HelixDataAccessor dataAccessor, List<Message> messages) {
    if (messages == null || messages.isEmpty()) {
      return;
    }

    Builder keyBuilder = dataAccessor.keyBuilder();

    List<PropertyKey> keys = new ArrayList<PropertyKey>();
    for (Message message : messages) {
      logger.info("Sending Message " + message.getMsgId() + " to " + message.getTgtName()
          + " transit " + message.getPartitionName() + "|" + message.getPartitionNames() + " from:"
          + message.getFromState() + " to:" + message.getToState());

      // System.out.println("[dbg] Sending Message " + message.getMsgId() + " to " +
      // message.getTgtName()
      // + " transit " + message.getPartitionName() + "|" + message.getPartitionNames()
      // + " from: " + message.getFromState() + " to: " + message.getToState());

      keys.add(keyBuilder.message(message.getTgtName(), message.getId()));
    }

    dataAccessor.createChildren(keys, new ArrayList<Message>(messages));
  }
}


text:
module.exports = function(BaseSyncModel) {

};


text:
var connect = require('connect');
    http = require('http');

var app = connect()
  .use(filterByIp(['127.0.0.1']))
  .use(helloWorld)

function filterByIp(ips){
  var ips = ips || [];
  return function (req, res, next){
    if (ips.indexOf(req.connection.remoteAddress) == -1) {
      res.writeHead(401, {'Content-Type': 'text/plain'});
      res.write('Sorry. You are not allowed to access this server');
      res.end();
    } else {
      next();
    }
  };
};

function helloWorld(req,res){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('You can view this!');
}

http.Server(app).listen(3000);


text:
VENV_DIR=/herc_venv

source $VENV_DIR/bin/activate
herc --debug
deactivate


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unity WebGL Player | WebGLChat</title>

    <link rel="stylesheet" href="Data/style.css">
    <link rel="shortcut icon" href="Data/favicon.ico" />

Unity WebGL Player | WebGLChat

    <canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()" height="600px" width="960px"></canvas>
		<button id="name">Change Name</button>
		<button id="message">Update Message</button>

WebGLChat

« created with Unity »


text:
from flask import current_app
from potnanny_core.database import db_session

"""
Class that handles the generic CRUD calls, data serialization and validation, etc
Initialization objects are:
    - a class
    - the marshmallow schema class used to validate/serialize
"""

class CrudInterface(object):
    def __init__(self, objclass, objschema):
        self._objclass = objclass
        self._objschema = objschema

    """
    GET object/objects

    notes on the callable:
        a list or tuple ['index_name', 'method_name']

        This is to have additional data added to get(pk) output... data that is
        not immediately available in an obj on instance creation, but must be
        gathered/calculated later by a method call to the object.
        The method call is made, and whatever it retures is added to the data
        dict under the index_name key.
    """
    def get(self, pk=None, post_callable=None):
        http_code = 200
        if not pk:
            r = self._objclass.query.all()
            if not r:
                return (None, {"message": "no data"}, 404)

            serialized, errors = self._objschema(many=True).dump(r)
            if errors:
                http_code = 400
        else:
            obj = self._objclass.query.get(pk)
            if not obj:
                return (None, {"message": "object does not exist"}, 404)

            serialized, errors = self._objschema().dump(obj)

            if post_callable:
                tag, m = post_callable
                serialized[tag] = getattr(obj, m)()

            if errors:
                http_code = 400

        return (serialized, errors, http_code)

    """
    CREATE object
    """
    def create(self, data):
        http_code = 200
        obj = self._objclass(**data)
        db.session.add(obj)
        db.session.commit()
        serialized, errors = self._objschema().dump(obj)

        if errors:
            http_code = 400

        return (serialized, errors, http_code)

    """
    EDIT object

    the pre-modification callback is a function that will be called before the
    object gets been modified.
    the callback func receives the Object, and the data passed.
    If callback returns a non-None result, the obj will not be edited.
    """
    def edit(self, pk, data, premod_callback=None):
        http_code = 200
        obj = self._objclass.query.get(pk)
        if not obj:
            return (None, {"message": "object does not exist"}, 404)

        if premod_callback:
            rval = premod_callback(obj, data)
            if rval:
                return (None, {"message": rval}, 400)

        for k,v in data.items():
            setattr(obj, k, v)

        db.session.commit()
        serialized, errors = self._objschema().dump(obj)
        if errors:
            http_code = 400

        return (serialized, errors, http_code)

    """
    DELETE object
    """
    def delete(self, pk):
        obj = self._objclass.query.get(pk)
        if not obj:
            return(None, {"message": "object does not exist"}, 404)

        db.session.delete(obj)
        db.session.commit()
        return("", None, 204)


text:
//
// The MIT License (MIT)
// Copyright (c) 2016 Adriano Repetti

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// - The above copyright notice and this permission notice shall be
//   included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;

namespace MicroBench.Engine.Calculations
{
    ///
    /// Base class for objects used to calculate descriptive values from benchmarks result.
    ///
    public abstract class Statistics
    {
        ///
        /// Gets the name of the main value extracted by <see cref="Calculate"/>.
        ///
        /// <value>
        /// Name (which is also dictionary key) of the main or most important
        /// value extracted by <see cref="Calculate"/>. This is used when we need
        /// one single value which best describe benchmark result (for example average execution time).
        /// </value>
        public abstract string KeyHeader
        {
            get;
        }

        ///
        /// Gets list of all values calculated by <see cref="Calculate"/>.
        ///
        /// <returns>
        /// List of all values calculated by <c>Calculate</c>.
        /// </returns>
        public abstract IEnumerable<string> GetHeaders();

        ///
        /// Calculate a set of values to describe benchmark results.
        ///
        /// <param name="method">Method which has been benchmarked.</param>
        /// <returns>
        /// Dictionary with values which decribes results of benchmark <paramref name="method"/>. Dictionary
        /// keys are given by <see cref="GetHeaders"/> and values can be both <see cref="Double"/> or <see cref="TimeSpan"/>.
        /// Unit of measure must always be milliseconds.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="method"/> is <see langword="null"/>.
        /// </exception>
        public abstract Dictionary<string, object> Calculate(BenchmarkedMethod method);
    }
}


text: Trying to get SFML to work inside a WPF window


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace DynamicVsLambda
{
    public class Event1 { }
    public class Event2 { }
    public class Event3 { }
    public class Event4 { }
    public class Event5 { }
    public class Event6 { }

    public class Handler
    {
        public bool Handle(Event1 x) { return true; }
        public bool Handle(Event2 x) { return true; }
        public bool Handle(Event3 x) { return true; }
        public bool Handle(Event4 x) { return true; }
        public bool Handle(Event5 x) { return true; }
        public bool Handle(Event6 x) { return true; }
    }
    public class Handler2
    {
        public bool Handle(Event1 x) { return true; }
        public bool Handle(Event2 x) { return true; }
        public bool Handle(Event3 x) { return true; }
        public bool Handle(Event4 x) { return true; }
        public bool Handle(Event5 x) { return true; }
        public bool Handle(Event6 x) { return true; }
    }

    class Program
    {
        public static int counter = 0;

        static Dictionary<Type, LateBoundMethod> calls = new Dictionary<Type, LateBoundMethod>();

        static void Main(string[] args)
        {
            //List<object> events = new List<object>() { new Event1(), new Event2(), new Event3(), new Event4(), new Event5(), new Event6() };
            Dictionary<object, Type> events = new Dictionary<object, Type>()
            {
                {new Event1(),typeof(Event1)},
            {new Event2(),typeof(Event2)},
            {new Event3(),typeof(Event3)},
            {new Event4(),typeof(Event4)},
            {new Event5(),typeof(Event5)},
            {new Event6(),typeof(Event6)}

            };
            var obj = new Handler();
            var mis = obj.GetType().GetMethods().Where(x => x.Name == "Handle");

            foreach (var mi in mis)
            {
                LateBoundMethod callback = DelegateFactory.Create(mi);
                var parType = mi.GetParameters().First().ParameterType;
                calls.Add(parType, callback);
            }

            var dynamicResults = MeasureExecutionTime.Start(() =>
            {
                dynamic handler = FastActivator.CreateInstance(typeof(Handler));
                foreach (var evnt in events)
                {
                    handler.Handle((dynamic)evnt.Key);
                }

            }, 1000000);

            var lambdaResults = MeasureExecutionTime.Start(() =>
            {
                var handler = FastActivator.CreateInstance(typeof(Handler));
                foreach (var evnt in events)
                {

                    calls[evnt.Value](handler, new object[] { evnt.Key });
                }

            }, 1000000);

            Console.WriteLine(dynamicResults);
            Console.WriteLine(lambdaResults);
            Console.ReadLine();
        }
    }

    public static class FastActivator
    {
        static System.Collections.Concurrent.ConcurrentDictionary<Type, ObjectActivator> activators = new System.Collections.Concurrent.ConcurrentDictionary<Type, ObjectActivator>();

        public delegate object ObjectActivator(params object[] args);

        static ObjectActivator GetActivator(ConstructorInfo ctor)
        {
            ParameterInfo[] paramsInfo = ctor.GetParameters();
            ParameterExpression param = Expression.Parameter(typeof(object[]), "args");
            Expression[] argsExp = new Expression[paramsInfo.Length];
            for (int i = 0; i < paramsInfo.Length; i++)
            {
                Expression index = Expression.Constant(i);
                Type paramType = paramsInfo[i].ParameterType;
                Expression paramAccessorExp = Expression.ArrayIndex(param, index);
                Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType);
                argsExp[i] = paramCastExp;
            }
            NewExpression newExp = Expression.New(ctor, argsExp);
            LambdaExpression lambda = Expression.Lambda(typeof(ObjectActivator), newExp, param);
            return (ObjectActivator)lambda.Compile();
        }

        public static void WarmInstanceConstructor(Type type)
        {
            if (!activators.ContainsKey(type))
            {
                var constructors = type.GetConstructors();
                if (constructors.Length == 1)
                {
                    ConstructorInfo ctor = constructors.First();
                    activators.TryAdd(type, GetActivator(ctor));
                }
            }
        }

        public static object CreateInstance(Type type, params object[] args)
        {
            ObjectActivator activator;
            if (!activators.TryGetValue(type, out activator))
            {
                var constructors = type.GetConstructors();
                if (constructors.Length == 1)
                {
                    ConstructorInfo ctor = type.GetConstructors().First();
                    activator = GetActivator(ctor);
                    activators.TryAdd(type, activator);
                }
                else
                {
                    activator = (a) => Activator.CreateInstance(type, a);
                }

            }
            return activator(args);
        }
    }

    public delegate object LateBoundMethod(object target, object[] arguments);

    public static class DelegateFactory
    {
        public static LateBoundMethod Create(MethodInfo method)
        {
            ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "target");
            ParameterExpression argumentsParameter = Expression.Parameter(typeof(object[]), "arguments");

            MethodCallExpression call = Expression.Call(
              Expression.Convert(instanceParameter, method.DeclaringType),
              method,
              CreateParameterExpressions(method, argumentsParameter));

            Expression<LateBoundMethod> lambda = Expression.Lambda<LateBoundMethod>(
              Expression.Convert(call, typeof(object)),
              instanceParameter,
              argumentsParameter);

            return lambda.Compile();
        }

        private static Expression[] CreateParameterExpressions(MethodInfo method, Expression argumentsParameter)
        {
            return method.GetParameters().Select((parameter, index) =>
              Expression.Convert(
                Expression.ArrayIndex(argumentsParameter, Expression.Constant(index)), parameter.ParameterType)).ToArray();
        }
    }

    public static class MeasureExecutionTime
    {
        public static string Start(System.Action action)
        {
            string result = string.Empty;

            var stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            action();
            stopWatch.Stop();
            System.TimeSpan ts = stopWatch.Elapsed;
            result = System.String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            return result;
        }

        public static string Start(System.Action action, int repeat, bool showTicksInfo = false)
        {
            var stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            for (int i = 0; i < repeat; i++)
            {
                action();
            }
            stopWatch.Stop();
            System.TimeSpan total = stopWatch.Elapsed;
            System.TimeSpan average = new System.TimeSpan(stopWatch.Elapsed.Ticks / repeat);

            System.Text.StringBuilder perfResultsBuilder = new System.Text.StringBuilder();
            perfResultsBuilder.AppendLine("--------------------------------------------------------------");
            perfResultsBuilder.AppendFormat("  Total Time => {0}\r\nAverage Time => {1}", Align(total), Align(average));
            perfResultsBuilder.AppendLine();
            perfResultsBuilder.AppendLine("--------------------------------------------------------------");
            if (showTicksInfo)
                perfResultsBuilder.AppendLine(TicksInfo());
            return perfResultsBuilder.ToString();
        }

        static string Align(System.TimeSpan interval)
        {
            string intervalStr = interval.ToString();
            int pointIndex = intervalStr.IndexOf(':');

            pointIndex = intervalStr.IndexOf('.', pointIndex);
            if (pointIndex < 0) intervalStr += "        ";
            return intervalStr;
        }

        static string TicksInfo()
        {
            System.Text.StringBuilder ticksInfoBuilder = new System.Text.StringBuilder("\r\n\r\n");
            ticksInfoBuilder.AppendLine("Ticks Info");
            ticksInfoBuilder.AppendLine("--------------------------------------------------------------");
            const string numberFmt = "{0,-22}{1,18:N0}";
            const string timeFmt = "{0,-22}{1,26}";

            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Field", "Value"));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "-----", "-----"));

            // Display the maximum, minimum, and zero TimeSpan values.
            ticksInfoBuilder.AppendLine(System.String.Format(timeFmt, "Maximum TimeSpan", Align(System.TimeSpan.MaxValue)));
            ticksInfoBuilder.AppendLine(System.String.Format(timeFmt, "Minimum TimeSpan", Align(System.TimeSpan.MinValue)));
            ticksInfoBuilder.AppendLine(System.String.Format(timeFmt, "Zero TimeSpan", Align(System.TimeSpan.Zero)));
            ticksInfoBuilder.AppendLine();

            // Display the ticks-per-time-unit fields.
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per day", System.TimeSpan.TicksPerDay));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per hour", System.TimeSpan.TicksPerHour));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per minute", System.TimeSpan.TicksPerMinute));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per second", System.TimeSpan.TicksPerSecond));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per millisecond", System.TimeSpan.TicksPerMillisecond));
            ticksInfoBuilder.AppendLine("--------------------------------------------------------------");
            return ticksInfoBuilder.ToString();
        }
    }
}


text:
@interface WYSearchPopularCollectionViewCell : UICollectionViewCell

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIImageView *iconImageView;

@end

@implementation WYSearchPopularCollectionViewCell

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupSubviews];
        [self setupObserver];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubviews];
        [self setupObserver];
    }
    return self;
}

- (void)dealloc {
    [self.iconImageView removeObserver:self forKeyPath:@"image"];
}

#pragma mark - Observer
- (void)setupObserver {
    [self.iconImageView addObserver:self
                         forKeyPath:@"image"
                            options:NSKeyValueObservingOptionNew
                            context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context {

    if (object == self.iconImageView) {
        if ([keyPath isEqualToString:@"image"]) {
            if (self.iconImageView.image) {
                __weak WYSearchPopularCollectionViewCell *weakSelf = self;
                [self.iconImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                    __strong WYSearchPopularCollectionViewCell *strongSelf = weakSelf;
                    make.width.equalTo(strongSelf.iconImageView.mas_height);
                }];
            } else {
                [self.iconImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.width.equalTo(@(0.01));
                }];
            }
        }
    }
}

#pragma mark - Setup Subviews
- (void)setupSubviews {

    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.textColor = [UIColor darkGrayColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;

    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.contentMode = UIViewContentModeScaleAspectFit;

    self.iconImageView = imageView;
    self.titleLabel = titleLabel;

    [self addSubview:titleLabel];
    [self addSubview:imageView];

    UIEdgeInsets padding = UIEdgeInsetsMake(5, 5, 5, 0);

    __weak WYSearchPopularCollectionViewCell *weakSelf = self;
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        __strong WYSearchPopularCollectionViewCell *strongSelf = weakSelf;
        make.left.equalTo(strongSelf.contentView.mas_left).with.offset(padding.left);
        make.top.equalTo(strongSelf.contentView.mas_top).with.offset(padding.top);
        make.bottom.equalTo(strongSelf.contentView.mas_bottom).with.offset(-padding.bottom);
//        make.width.equalTo(strongSelf.iconImageView.mas_height);
        make.width.equalTo(@(0.01));
    }];

    padding = UIEdgeInsetsMake(5, 5, 5, 5);
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        __strong WYSearchPopularCollectionViewCell *strongSelf = weakSelf;
        make.left.equalTo(strongSelf.contentView.mas_left).with.offset(padding.left);
        make.right.equalTo(strongSelf.contentView.mas_right).with.offset(-padding.right);
        make.top.equalTo(strongSelf.contentView.mas_top).with.offset(padding.top);
        make.bottom.equalTo(strongSelf.contentView.mas_bottom).with.offset(-padding.bottom);
    }];

}

@end

@interface WYSearchPopularViewCollectionHeaderView : UICollectionReusableView

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIButton *cleanButton;

@end

@implementation WYSearchPopularViewCollectionHeaderView

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:14];
    }
    return _titleLabel;
}

- (UIButton *)cleanButton {
    if (!_cleanButton) {
        _cleanButton = [[UIButton alloc] init];
        _cleanButton.hidden = YES;
        [_cleanButton setImage:[UIImage imageNamed:@"ic_basic_delete"]
                      forState:UIControlStateNormal];
    }
    return _cleanButton;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {

    [self addSubview:self.titleLabel];
    [self addSubview:self.cleanButton];
    self.backgroundColor = [UIColor whiteColor];

    UIEdgeInsets padding = UIEdgeInsetsMake(0, 0, 0, 5);

    __weak WYSearchPopularViewCollectionHeaderView *weakSelf = self;
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        __strong WYSearchPopularViewCollectionHeaderView *strongSelf = weakSelf;
        make.left.equalTo(strongSelf.mas_left).with.offset(padding.left);
        make.right.equalTo(strongSelf.cleanButton.mas_right).with.offset(-padding.right);
        make.top.equalTo(strongSelf.mas_top).with.offset(padding.top);
        make.bottom.equalTo(strongSelf.mas_bottom).with.offset(-padding.bottom);
    }];

    padding = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.cleanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        __strong UIView *strongSelf = weakSelf;
        make.width.equalTo(strongSelf.mas_height);
        make.right.equalTo(strongSelf.mas_right).with.offset(-padding.right);
        make.top.equalTo(strongSelf.mas_top).with.offset(padding.top);
        make.bottom.equalTo(strongSelf.mas_bottom).with.offset(-padding.bottom);
    }];
}

@end

@interface WYSearchPopularViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, copy) NSString *historySearchKey;
@property (nonatomic) WYSearchPopularComponentOption componentOption;

@property (nonatomic, strong) NSMutableArray *sectionOptions;

@property (nonatomic, strong) NSMutableArray *hotSearchKeywords;
@property (nonatomic, strong) NSMutableArray *historyKeywords;

@end

static NSUInteger kMaxHistoryKeywordCount = 10;
static NSUInteger kMaxKeywordLength = 10;

static NSString *WYSearchPopularViewControllerDefaultHistoryKey = @"WYSearchPopularViewControllerDefaultHistoryKey";

@implementation WYSearchPopularViewController
#pragma mark - Getter Setter
- (NSMutableArray *)historyKeywords {
    if (!_historyKeywords) {
        @synchronized (self) {
            _historyKeywords = [[NSUserDefaults standardUserDefaults] objectForKey:self.historySearchKey];
            _historyKeywords = [NSMutableArray arrayWithArray:_historyKeywords];

            if (!_historyKeywords) {
                _historyKeywords = [NSMutableArray array];
                [[NSUserDefaults standardUserDefaults] setObject:_historyKeywords
                                                          forKey:self.historySearchKey];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }
    }
    return _historyKeywords;
}

- (void)addHistoryKeyword:(NSString *)keyword {
    @synchronized (self) {
//        NSMutableArray *record = [[NSUserDefaults standardUserDefaults] objectForKey:self.historySearchKey];
        // delete equal keyword from records
        __block NSInteger index = -1;
        [self.historyKeywords enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isEqualToString:keyword]) {
                index = idx;
            }
        }];

        if (index > -1)
            [self.historyKeywords removeObjectAtIndex:index];
        // add new keyword
        [self.historyKeywords insertObject:keyword atIndex:0];

        if (self.historyKeywords.count > kMaxHistoryKeywordCount) {
            [self.historyKeywords removeObjectsInRange:NSMakeRange(kMaxHistoryKeywordCount, self.historyKeywords.count-kMaxHistoryKeywordCount)];
        }

//        [[NSUserDefaults standardUserDefaults] setObject:self.historyKeywords
//                                                  forKey:self.historySearchKey];
//        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

#pragma mark - Intial
- (instancetype)init {
    return [self initWithOption:WYSearchPopularComponentOptionHistory];
}

- (instancetype)initWithOption:(WYSearchPopularComponentOption)option {
    return [self initWithHistoryIdentifier:WYSearchPopularViewControllerDefaultHistoryKey
                             option:option];
}

- (instancetype)initWithHistoryIdentifier:(NSString *)historyIdentifier
                                   option:(WYSearchPopularComponentOption)option {
    self = [super init];
    if (self) {
        self.historySearchKey = historyIdentifier;
        self.componentOption = option;

        self.sectionOptions = [NSMutableArray array];
        if (option & WYSearchPopularComponentOptionHot)
            [self.sectionOptions addObject:@(WYSearchPopularComponentOptionHot)];
        if (option & WYSearchPopularComponentOptionHistory)
            [self.sectionOptions addObject:@(WYSearchPopularComponentOptionHistory)];
    }
    return self;
}

#pragma mark - Lifecyle
- (void)loadView {
    self.view = [[UIView alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 1;
    layout.minimumInteritemSpacing = 1;

    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor whiteColor];

    self.collectionView = collectionView;

    [collectionView registerClass:[WYSearchPopularCollectionViewCell class]
       forCellWithReuseIdentifier:@"Cell"];
    [collectionView registerClass:[WYSearchPopularViewCollectionHeaderView class]
       forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
              withReuseIdentifier:@"HeaderView"];
    [collectionView registerClass:[UICollectionReusableView class]
       forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
              withReuseIdentifier:@"FooterView"];

    [self.view addSubview:collectionView];

    UIEdgeInsets padding = UIEdgeInsetsMake(15, 25, 15, 25);

    __weak UIViewController *weakSelf = self;
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        __strong UIViewController *strongSelf = weakSelf;
        make.left.equalTo(strongSelf.view.mas_left).with.offset(padding.left);
        make.right.equalTo(strongSelf.view.mas_right).with.offset(-padding.right);
        make.top.equalTo(strongSelf.view.mas_top).with.offset(padding.top);
        make.bottom.equalTo(strongSelf.view.mas_bottom).with.offset(-padding.bottom);
    }];

}

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)dealloc {
    [[NSUserDefaults standardUserDefaults] setObject:self.historyKeywords
                                              forKey:self.historySearchKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - Event
- (void)handleCleanButtonAction:(UIButton *)sender {
    [self.historyKeywords removeAllObjects];
    [[NSUserDefaults standardUserDefaults] setObject:self.historyKeywords
                                              forKey:self.historySearchKey];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [self.collectionView reloadData];
}

#pragma mark - Notification

#pragma mark - WYSearchViewControllerPopular Delegate
- (void)wy_searchControllerWillShowPopularView:(WYSearchViewController *)searchController {
    [self.collectionView reloadData];
}

- (void)wy_searchController:(WYSearchViewController *)searchController
  didStartSearchWithKeyword:(NSString *)keyword {
    [self addHistoryKeyword:keyword];
}

#pragma mark - UICollectionView Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSUInteger itemCount = 0;

    WYSearchPopularComponentOption option;
    option = [self.sectionOptions[section] unsignedIntegerValue];
    switch (option) {
        case WYSearchPopularComponentOptionHot:
            itemCount = self.hotSearchKeywords.count;
            break;
        case WYSearchPopularComponentOptionHistory:
            itemCount = self.historyKeywords.count;
            break;
        default:
            break;
    }

    return itemCount;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.sectionOptions.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    WYSearchPopularComponentOption option;
    option = [self.sectionOptions[indexPath.section] unsignedIntegerValue];

    if (option == WYSearchPopularComponentOptionHistory) {
        if (self.quickSearchForKeyword) {
            NSString *keyword = self.historyKeywords[indexPath.row];
            [self addHistoryKeyword:keyword];
            self.quickSearchForKeyword(keyword);
        }
    }
}

#pragma mark - UICollectionView DelegateLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    NSString *keyword;
    WYSearchPopularComponentOption option;
    option = [self.sectionOptions[indexPath.section] unsignedIntegerValue];
    switch (option) {
        case WYSearchPopularComponentOptionHot:
            keyword = @"";
            break;
        case WYSearchPopularComponentOptionHistory:
            keyword = self.historyKeywords[indexPath.row];
            break;
        default:
            break;
    }

    CGSize size;
    CGFloat width = 12*MIN(kMaxKeywordLength, keyword.length)+12;
    size = CGSizeMake(width, 30);

    return size;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {

    CGFloat boundsWidth = CGRectGetWidth(self.view.bounds);
    return CGSizeMake(boundsWidth, 30);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    CGFloat boundsWidth = CGRectGetWidth(self.view.bounds);
    return CGSizeMake(boundsWidth, 8);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 8;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 8;
}

#pragma mark - UICollectionView DataSource
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WYSearchPopularCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    NSString *keyword;
    WYSearchPopularComponentOption option;
    option = [self.sectionOptions[indexPath.section] unsignedIntegerValue];
    switch (option) {
        case WYSearchPopularComponentOptionHot:
            keyword = @"";
            break;
        case WYSearchPopularComponentOptionHistory:
            keyword = self.historyKeywords[indexPath.row];
            break;
        default:
            break;
    }

    cell.iconImageView.image = indexPath.item%2 ? [UIImage imageNamed:@"ic_basic_search_blue"] : nil;
    cell.titleLabel.text = keyword.length <= kMaxKeywordLength ? keyword : [keyword substringWithRange:NSMakeRange(0, kMaxKeywordLength)];

    cell.layer.cornerRadius = 4;
    cell.layer.masksToBounds = YES;
    cell.contentView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.8];

    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        WYSearchPopularViewCollectionHeaderView *headerView =
        [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                           withReuseIdentifier:@"HeaderView"
                                                  forIndexPath:indexPath];

        WYSearchPopularComponentOption option;
        option = [self.sectionOptions[indexPath.section] unsignedIntegerValue];
        switch (option) {
            case WYSearchPopularComponentOptionHot:
                headerView.titleLabel.text = @"热门搜索";
                headerView.cleanButton.hidden = YES;
                break;
            case WYSearchPopularComponentOptionHistory:
                headerView.titleLabel.text = @"历史搜索";
                headerView.cleanButton.hidden = NO;
                [headerView.cleanButton addTarget:self
                                           action:@selector(handleCleanButtonAction:)
                                 forControlEvents:UIControlEventTouchUpInside];
                break;
            default:
                break;
        }
        return headerView;
    }

    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                                                        withReuseIdentifier:@"FooterView"
                                                                               forIndexPath:indexPath];
    return view;
}

#pragma mark - Other

@end


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * TravelReimbursementDetail Schema
 */
var TravelReimbursementDetailSchema = new Schema({

  sno: {
		type: Number,
		required: 'Please fill sno name'
	},

  clientLocation: {
		type: String,
		required: 'Please fill clientLocation name'
	},

  jobNumber: {
		type: Number,
		required: 'Please fill jobNumber name'
	},

  fromDate: {
		type: Date,
		required: 'Please fill fromDate name'
	},

  toDate: {
		type: Date,
		required: 'Please fill toDate name'
	},

  noOfDays: {
		type: Number,
		required: 'Please fill noOfDays name'
	},

  conveyance: {
		type: Number,
		required: 'Please fill conveyance name'
	},

  foodAllowance: {
		type: Number,
		required: 'Please fill foodAllowance name'
	},

  otherExpenses: {
		type: Number,
		required: 'Please fill otherExpenses name'
	},

  totalAmount: {
		type: Number,
		required: 'Please fill totalAmount name'
	},

	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	}
});

mongoose.model('TravelReimbursementDetail', TravelReimbursementDetailSchema);


text:
require 'lurker/spy'

if defined?(RSpec) && RSpec.respond_to?(:configure)
  when_tagged_with_lurker = { :lurker => lambda { |v| !!v } }

  RSpec.configure do |config|
    config.around(:each, when_tagged_with_lurker) do |ex|
      example = ex.respond_to?(:metadata) ? ex : ex.example
      options = example.metadata[:lurker]
      options = if options.is_a?(Hash)
        options.dup
      elsif options.is_a?(String)
        { suffix: options }
      else
        {}
      end
      Lurker::Spy.on(options, &example)
    end

    unless RSpec::Core::Version::STRING > '3'
      config.treat_symbols_as_metadata_keys_with_true_values = true
    end
  end
end


text:
package org.apache.flink.compiler.plan;

import static org.apache.flink.compiler.plan.PlanNode.SourceAndDamReport.FOUND_SOURCE;
import static org.apache.flink.compiler.plan.PlanNode.SourceAndDamReport.FOUND_SOURCE_AND_DAM;
import static org.apache.flink.compiler.plan.PlanNode.SourceAndDamReport.NOT_FOUND;

import java.util.Collections;
import java.util.HashMap;

import org.apache.flink.compiler.costs.Costs;
import org.apache.flink.compiler.dag.BulkPartialSolutionNode;
import org.apache.flink.compiler.dag.OptimizerNode;
import org.apache.flink.compiler.dataproperties.GlobalProperties;
import org.apache.flink.compiler.dataproperties.LocalProperties;
import org.apache.flink.runtime.operators.DamBehavior;
import org.apache.flink.runtime.operators.DriverStrategy;
import org.apache.flink.util.Visitor;

/**
 * Plan candidate node for partial solution of a bulk iteration.
 */
public class BulkPartialSolutionPlanNode extends PlanNode {

	private static final Costs NO_COSTS = new Costs();

	private BulkIterationPlanNode containingIterationNode;

	private Channel initialInput;

	public Object postPassHelper;

	public BulkPartialSolutionPlanNode(BulkPartialSolutionNode template, String nodeName,
			GlobalProperties gProps, LocalProperties lProps,
			Channel initialInput)
	{
		super(template, nodeName, DriverStrategy.NONE);

		this.globalProps = gProps;
		this.localProps = lProps;
		this.initialInput = initialInput;

		// the partial solution does not cost anything
		this.nodeCosts = NO_COSTS;
		this.cumulativeCosts = NO_COSTS;

		if (initialInput.getSource().branchPlan != null && initialInput.getSource().branchPlan.size() > 0) {
			if (this.branchPlan == null) {
				this.branchPlan = new HashMap<OptimizerNode, PlanNode>();
			}

			this.branchPlan.putAll(initialInput.getSource().branchPlan);
		}
	}

	// --------------------------------------------------------------------------------------------

	public BulkPartialSolutionNode getPartialSolutionNode() {
		return (BulkPartialSolutionNode) this.template;
	}

	public BulkIterationPlanNode getContainingIterationNode() {
		return this.containingIterationNode;
	}

	public void setContainingIterationNode(BulkIterationPlanNode containingIterationNode) {
		this.containingIterationNode = containingIterationNode;
	}

	// --------------------------------------------------------------------------------------------

	@Override
	public void accept(Visitor<PlanNode> visitor) {
		if (visitor.preVisit(this)) {
			visitor.postVisit(this);
		}
	}

	@Override
	public Iterable<PlanNode> getPredecessors() {
		return Collections.<PlanNode>emptyList();
	}

	@Override
	public Iterable<Channel> getInputs() {
		return Collections.<Channel>emptyList();
	}

	@Override
	public SourceAndDamReport hasDamOnPathDownTo(PlanNode source) {
		if (source == this) {
			return FOUND_SOURCE;
		}
		SourceAndDamReport res = this.initialInput.getSource().hasDamOnPathDownTo(source);
		if (res == FOUND_SOURCE_AND_DAM) {
			return FOUND_SOURCE_AND_DAM;
		}
		else if (res == FOUND_SOURCE) {
			return (this.initialInput.getLocalStrategy().dams() ||
					this.initialInput.getTempMode().breaksPipeline() ||
					getDriverStrategy().firstDam() == DamBehavior.FULL_DAM) ?
				FOUND_SOURCE_AND_DAM : FOUND_SOURCE;
		}
		else {
			return NOT_FOUND;
		}
	}
}


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/autofill/save_address_profile_view.h"

#include <memory>

#include "base/strings/string_util.h"
#include "chrome/app/vector_icons/vector_icons.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/autofill/save_update_address_profile_bubble_controller.h"
#include "chrome/browser/ui/hats/hats_service.h"
#include "chrome/browser/ui/hats/hats_service_factory.h"
#include "chrome/browser/ui/views/accessibility/theme_tracking_non_accessible_image_view.h"
#include "chrome/browser/ui/views/autofill/autofill_bubble_utils.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/grit/theme_resources.h"
#include "components/autofill/core/browser/autofill_address_util.h"
#include "components/autofill/core/browser/data_model/autofill_profile.h"
#include "components/autofill/core/browser/field_types.h"
#include "components/autofill/core/browser/geo/address_i18n.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/strings/grit/components_strings.h"
#include "components/vector_icons/vector_icons.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/simple_combobox_model.h"
#include "ui/color/color_id.h"
#include "ui/gfx/color_utils.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/button/image_button_factory.h"
#include "ui/views/controls/editable_combobox/editable_combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/view_class_properties.h"

namespace autofill {

namespace {

constexpr int kIconSize = 16;

// Maps an AddressField to a ServerFieldType making sure
// NAME_FULL_WITH_HONORIFIC_PREFIX is returned instead of NAME_FULL for
// RECIPIENT type.
ServerFieldType AddressFieldToServerFieldTypeWithHonorificPrefix(
    ::i18n::addressinput::AddressField address_field) {
  ServerFieldType type = autofill::i18n::TypeForField(address_field);
  return type == NAME_FULL ? NAME_FULL_WITH_HONORIFIC_PREFIX : type;
}

int ComboboxIconSize() {
  // Use the line height of the body small text. This allows the icons to adapt
  // if the user changes the font size.
  return views::style::GetLineHeight(views::style::CONTEXT_MENU,
                                     views::style::STYLE_PRIMARY);
}

std::unique_ptr<views::ImageView> CreateAddressSectionIcon(
    const gfx::VectorIcon& icon) {
  auto icon_view = std::make_unique<views::ImageView>();
  icon_view->SetImage(
      ui::ImageModel::FromVectorIcon(icon, ui::kColorIconSecondary, kIconSize));
  return icon_view;
}

void AddAddressSection(views::View* parent_view,
                       std::unique_ptr<views::ImageView> icon_view,
                       std::unique_ptr<views::View> view) {
  views::View* row = parent_view->AddChildView(std::make_unique<views::View>());
  views::FlexLayout* row_layout =
      row->SetLayoutManager(std::make_unique<views::FlexLayout>());
  row_layout->SetOrientation(views::LayoutOrientation::kHorizontal)
      .SetIgnoreDefaultMainAxisMargins(true)
      .SetCrossAxisAlignment(views::LayoutAlignment::kStart)
      .SetCollapseMargins(true)
      .SetDefault(
          views::kMarginsKey,
          gfx::Insets::VH(0, ChromeLayoutProvider::Get()->GetDistanceMetric(
                                 views::DISTANCE_RELATED_CONTROL_HORIZONTAL)));
  row->AddChildView(std::move(icon_view));
  row->AddChildView(std::move(view));
}

void AddAddressSection(views::View* parent_view,
                       std::unique_ptr<views::ImageView> icon_view,
                       const std::u16string& text) {
  auto text_label =
      std::make_unique<views::Label>(text, views::style::CONTEXT_LABEL);
  text_label->SetMultiLine(true);
  text_label->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT);
  return AddAddressSection(parent_view, std::move(icon_view),
                           std::move(text_label));
}

std::unique_ptr<views::View> CreateAddressLineView() {
  auto line = std::make_unique<views::View>();
  views::FlexLayout* line_layout =
      line->SetLayoutManager(std::make_unique<views::FlexLayout>());
  line_layout->SetOrientation(views::LayoutOrientation::kHorizontal)
      .SetIgnoreDefaultMainAxisMargins(true)
      .SetCollapseMargins(true);
  return line;
}

std::unique_ptr<views::Label> CreateAddressComponentLabel(
    const std::u16string& text) {
  auto text_label =
      std::make_unique<views::Label>(text, views::style::CONTEXT_LABEL);
  text_label->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT);
  text_label->SetMultiLine(true);
  return text_label;
}

// Create a view that contains the address in an envelope style format. Returns
// nullptr if the address is empty.
std::unique_ptr<views::View> CreateStreetAddressView(
    const AutofillProfile& profile,
    const std::string& locale) {
  auto address_view = std::make_unique<views::View>();
  views::FlexLayout* flex_layout =
      address_view->SetLayoutManager(std::make_unique<views::FlexLayout>());
  flex_layout->SetOrientation(views::LayoutOrientation::kVertical)
      .SetCrossAxisAlignment(views::LayoutAlignment::kStart)
      .SetCollapseMargins(true)
      .SetDefault(views::kMarginsKey, gfx::Insets());

  const AutofillType kCountryCode(HtmlFieldType::kCountryCode,
                                  HtmlFieldMode::kNone);
  const std::u16string& country_code = profile.GetInfo(kCountryCode, locale);

  std::vector<std::vector<::i18n::addressinput::AddressUiComponent>> components;
  autofill::GetAddressComponents(base::UTF16ToUTF8(country_code), locale,
                                 /*include_literals=*/true, &components,
                                 nullptr);

  for (const std::vector<::i18n::addressinput::AddressUiComponent>& line :
       components) {
    std::unique_ptr<views::View> line_view = CreateAddressLineView();
    std::vector<std::u16string> components_str;
    for (const ::i18n::addressinput::AddressUiComponent& component : line) {
      // AddressUiComponent can represent an address field such as City, or a
      // formatting literal such as "," or "-". If the literal field is empty,
      // then it represents a field, otherwise, it is a literal.
      std::u16string field_value =
          component.literal.empty()
              ? profile.GetInfo(
                    AddressFieldToServerFieldTypeWithHonorificPrefix(
                        component.field),
                    locale)
              : base::UTF8ToUTF16(component.literal);
      if (!field_value.empty())
        line_view->AddChildView(CreateAddressComponentLabel(field_value));
    }
    if (!line_view->children().empty())
      address_view->AddChildView(std::move(line_view));
  }
  // Append the country to the end.
  std::u16string country = profile.GetInfo(ADDRESS_HOME_COUNTRY, locale);
  if (!country.empty()) {
    std::unique_ptr<views::View> line_view = CreateAddressLineView();
    line_view->AddChildView(CreateAddressComponentLabel(country));
    address_view->AddChildView(std::move(line_view));
  }
  if (!address_view->children().empty())
    return address_view;
  return nullptr;
}

std::unique_ptr<views::EditableCombobox> CreateNicknameEditableCombobox() {
  // TODO(crbug.com/1167060): Update the icons
  // TODO(crbug.com/1167060): Use internationalized string.
  ui::SimpleComboboxModel::Item home(
      /*text=*/u"Home",
      /*dropdown_secondary_text=*/std::u16string(),
      /*icon=*/
      ui::ImageModel::FromVectorIcon(kNavigateHomeIcon, ui::kColorIcon,
                                     ComboboxIconSize()));

  ui::SimpleComboboxModel::Item work(
      /*text=*/u"Work",
      /*dropdown_secondary_text=*/std::u16string(),
      /*icon=*/
      ui::ImageModel::FromVectorIcon(vector_icons::kBusinessIcon,
                                     ui::kColorIcon, ComboboxIconSize()));

  std::vector<ui::SimpleComboboxModel::Item> nicknames{std::move(home),
                                                       std::move(work)};

  auto combobox = std::make_unique<views::EditableCombobox>(
      std::make_unique<ui::SimpleComboboxModel>(std::move(nicknames)),
      /*filter_on_edit=*/true);

  combobox->SetProperty(
      views::kFlexBehaviorKey,
      views::FlexSpecification(views::MinimumFlexSizeRule::kScaleToZero,
                               views::MaximumFlexSizeRule::kUnbounded));
  // TODO(crbug.com/1167060): Use internationalized string.
  combobox->SetAccessibleName(u"Address Label");
  return combobox;
}

}  // namespace

SaveAddressProfileView::SaveAddressProfileView(
    views::View* anchor_view,
    content::WebContents* web_contents,
    SaveUpdateAddressProfileBubbleController* controller)
    : LocationBarBubbleDelegateView(anchor_view, web_contents),
      controller_(controller) {
  // Since this is a save prompt, original profile must not be set. Otherwise,
  // it would have been an update prompt.
  DCHECK(!controller_->GetOriginalProfile());

  // TODO(crbug.com/1167060): Accept action should consider the selected
  // nickname when saving the address.
  SetAcceptCallback(base::BindOnce(
      &SaveUpdateAddressProfileBubbleController::OnUserDecision,
      base::Unretained(controller_),
      AutofillClient::SaveAddressProfileOfferUserDecision::kAccepted));
  SetCancelCallback(base::BindOnce(
      &SaveUpdateAddressProfileBubbleController::OnUserDecision,
      base::Unretained(controller_),
      AutofillClient::SaveAddressProfileOfferUserDecision::kDeclined));

  SetTitle(controller_->GetWindowTitle());
  SetButtonLabel(ui::DIALOG_BUTTON_OK,
                 l10n_util::GetStringUTF16(
                     IDS_AUTOFILL_SAVE_ADDRESS_PROMPT_OK_BUTTON_LABEL));
  SetButtonLabel(ui::DIALOG_BUTTON_CANCEL,
                 l10n_util::GetStringUTF16(
                     IDS_AUTOFILL_SAVE_ADDRESS_PROMPT_CANCEL_BUTTON_LABEL));

  SetLayoutManager(std::make_unique<views::FlexLayout>())
      ->SetOrientation(views::LayoutOrientation::kHorizontal)
      .SetCrossAxisAlignment(views::LayoutAlignment::kStart)
      .SetIgnoreDefaultMainAxisMargins(true)
      .SetCollapseMargins(true);

  address_components_view_ = AddChildView(std::make_unique<views::View>());
  address_components_view_->SetProperty(
      views::kFlexBehaviorKey,
      views::FlexSpecification(
          views::MinimumFlexSizeRule::kPreferredSnapToMinimum,
          views::MaximumFlexSizeRule::kUnbounded));

  edit_button_ = AddChildView(CreateEditButton(base::BindRepeating(
      &SaveUpdateAddressProfileBubbleController::OnEditButtonClicked,
      base::Unretained(controller_))));

  address_components_view_
      ->SetLayoutManager(std::make_unique<views::FlexLayout>())
      ->SetOrientation(views::LayoutOrientation::kVertical)
      .SetCrossAxisAlignment(views::LayoutAlignment::kStretch)
      .SetIgnoreDefaultMainAxisMargins(true)
      .SetCollapseMargins(true)
      .SetDefault(
          views::kMarginsKey,
          gfx::Insets::VH(ChromeLayoutProvider::Get()->GetDistanceMetric(
                              DISTANCE_CONTROL_LIST_VERTICAL),
                          0));

  const std::string locale = g_browser_process->GetApplicationLocale();
  const AutofillProfile& profile = controller_->GetProfileToSave();

  std::unique_ptr<views::View> street_address_view =
      CreateStreetAddressView(profile, locale);
  if (street_address_view) {
    std::unique_ptr<views::ImageView> icon =
        CreateAddressSectionIcon(vector_icons::kLocationOnIcon);
    address_section_icons_.push_back(icon.get());
    AddAddressSection(
        /*parent_view=*/address_components_view_, std::move(icon),
        std::move(street_address_view));
  }

  std::u16string phone = profile.GetInfo(PHONE_HOME_WHOLE_NUMBER, locale);
  if (!phone.empty()) {
    std::unique_ptr<views::ImageView> icon =
        CreateAddressSectionIcon(vector_icons::kCallIcon);
    address_section_icons_.push_back(icon.get());
    AddAddressSection(/*parent_view=*/address_components_view_, std::move(icon),
                      phone);
  }

  std::u16string email = profile.GetInfo(EMAIL_ADDRESS, locale);
  if (!email.empty()) {
    std::unique_ptr<views::ImageView> icon =
        CreateAddressSectionIcon(vector_icons::kEmailIcon);
    address_section_icons_.push_back(icon.get());
    AddAddressSection(/*parent_view=*/address_components_view_, std::move(icon),
                      email);
  }

  if (base::FeatureList::IsEnabled(
          features::kAutofillAddressProfileSavePromptNicknameSupport)) {
    // TODO(crbug.com/1167060): Make sure the icon is vertically centered with
    // the editable combobox.
    AddAddressSection(/*parent_view=*/address_components_view_,
                      CreateAddressSectionIcon(vector_icons::kExtensionIcon),
                      CreateNicknameEditableCombobox());
  }

  Profile* browser_profile =
      Profile::FromBrowserContext(web_contents->GetBrowserContext());
  HatsService* hats_service = HatsServiceFactory::GetForProfile(
      browser_profile, /*create_if_necessary=*/true);
  CHECK(hats_service);
  hats_service->LaunchDelayedSurveyForWebContents(
      kHatsSurveyTriggerAutofillAddress, web_contents, 10000);
}

SaveAddressProfileView::~SaveAddressProfileView() = default;

bool SaveAddressProfileView::ShouldShowCloseButton() const {
  return true;
}

void SaveAddressProfileView::WindowClosing() {
  if (controller_) {
    controller_->OnBubbleClosed();
    controller_ = nullptr;
  }
}

void SaveAddressProfileView::Show(DisplayReason reason) {
  ShowForReason(reason);
}

void SaveAddressProfileView::Hide() {
  CloseBubble();

  // If |controller_| is null, WindowClosing() won't invoke OnBubbleClosed(), so
  // do that here. This will clear out |controller_|'s reference to |this|. Note
  // that WindowClosing() happens only after the _asynchronous_ Close() task
  // posted in CloseBubble() completes, but we need to fix references sooner.
  if (controller_)
    controller_->OnBubbleClosed();

  controller_ = nullptr;
}

void SaveAddressProfileView::AddedToWidget() {
  // Set the header image.
  ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
  auto image_view = std::make_unique<ThemeTrackingNonAccessibleImageView>(
      *bundle.GetImageSkiaNamed(IDR_SAVE_ADDRESS),
      *bundle.GetImageSkiaNamed(IDR_SAVE_ADDRESS_DARK),
      base::BindRepeating(&views::BubbleDialogDelegate::GetBackgroundColor,
                          base::Unretained(this)));
  GetBubbleFrameView()->SetHeaderView(std::move(image_view));
}

void SaveAddressProfileView::OnThemeChanged() {
  LocationBarBubbleDelegateView::OnThemeChanged();
  AlignIcons();
}

void SaveAddressProfileView::AlignIcons() {
  DCHECK(edit_button_);
  DCHECK(address_components_view_);
  // Adjust margins to make sure the edit button is vertically centered with the
  // first line in the address components view.
  int label_line_height = views::style::GetLineHeight(
      views::style::CONTEXT_LABEL, views::style::STYLE_PRIMARY);
  for (views::ImageView* icon_view : address_section_icons_) {
    DCHECK(icon_view);
    // Set views::kMarginsKey for flex layout to center the icon vertically with
    // the text in front of it. Label line height are guaranteed to be bigger
    // than kIconSize.
    icon_view->SetProperty(
        views::kMarginsKey,
        gfx::Insets::VH((label_line_height - kIconSize) / 2, 0));
  }

  int edit_button_height = edit_button_->GetPreferredSize().height();
  int height_difference = (edit_button_height - label_line_height) / 2;
  if (height_difference > 0) {
    // We need to push the `address_components_view` down.
    address_components_view_->SetProperty(
        views::kMarginsKey, gfx::Insets::VH(height_difference, 0));
    edit_button_->SetProperty(views::kMarginsKey, gfx::Insets());
  } else {
    // We need to push the `edit_button` down.
    address_components_view_->SetProperty(views::kMarginsKey, gfx::Insets());
    edit_button_->SetProperty(views::kMarginsKey,
                              gfx::Insets::VH(-height_difference, 0));
  }
}

}  // namespace autofill


text:
declare module google {
    export interface GoogleApis {
        gan(version: string): any;
        gan(version: 'v1beta1'): gan.v1beta1.Gan;
    }

    namespace gan {
        namespace v1beta1 {
            export interface Gan {
                new(options: any): Gan;

                'advertisers': {
                    'get': (parameters: {'advertiserId'?: string, 'role': string, 'roleId': string}, callback: (error: any, body: Advertiser, response: any) => void) => Request;
                    'list': (parameters: {'advertiserCategory'?: string, 'maxResults'?: number, 'minNinetyDayEpc'?: number, 'minPayoutRank'?: number, 'minSevenDayEpc'?: number, 'pageToken'?: string, 'relationshipStatus'?: string, 'role': string, 'roleId': string}, callback: (error: any, body: Advertisers, response: any) => void) => Request;
                };
                'ccOffers': {
                    'list': (parameters: {'advertiser'?: string, 'projection'?: string, 'publisher': string}, callback: (error: any, body: CcOffers, response: any) => void) => Request;
                };
                'events': {
                    'list': (parameters: {'advertiserId'?: string, 'chargeType'?: string, 'eventDateMax'?: string, 'eventDateMin'?: string, 'linkId'?: string, 'maxResults'?: number, 'memberId'?: string, 'modifyDateMax'?: string, 'modifyDateMin'?: string, 'orderId'?: string, 'pageToken'?: string, 'productCategory'?: string, 'publisherId'?: string, 'role': string, 'roleId': string, 'sku'?: string, 'status'?: string, 'type'?: string}, callback: (error: any, body: Events, response: any) => void) => Request;
                };
                'links': {
                    'get': (parameters: {'linkId': string, 'role': string, 'roleId': string}, callback: (error: any, body: Link, response: any) => void) => Request;
                    'insert': (parameters: {'role': string, 'roleId': string}, callback: (error: any, body: Link, response: any) => void) => Request;
                    'list': (parameters: {'advertiserId'?: string, 'assetSize'?: string, 'authorship'?: string, 'createDateMax'?: string, 'createDateMin'?: string, 'linkType'?: string, 'maxResults'?: number, 'pageToken'?: string, 'promotionType'?: string, 'relationshipStatus'?: string, 'role': string, 'roleId': string, 'searchText'?: string, 'startDateMax'?: string, 'startDateMin'?: string}, callback: (error: any, body: Links, response: any) => void) => Request;
                };
                'publishers': {
                    'get': (parameters: {'publisherId'?: string, 'role': string, 'roleId': string}, callback: (error: any, body: Publisher, response: any) => void) => Request;
                    'list': (parameters: {'maxResults'?: number, 'minNinetyDayEpc'?: number, 'minPayoutRank'?: number, 'minSevenDayEpc'?: number, 'pageToken'?: string, 'publisherCategory'?: string, 'relationshipStatus'?: string, 'role': string, 'roleId': string}, callback: (error: any, body: Publishers, response: any) => void) => Request;
                };
                'reports': {
                    'get': (parameters: {'advertiserId'?: string, 'calculateTotals'?: boolean, 'endDate'?: string, 'eventType'?: string, 'linkId'?: string, 'maxResults'?: number, 'orderId'?: string, 'publisherId'?: string, 'reportType': string, 'role': string, 'roleId': string, 'startDate'?: string, 'startIndex'?: number, 'status'?: string}, callback: (error: any, body: Report, response: any) => void) => Request;
                };

            }

            export interface Advertiser {
                'allowPublisherCreatedLinks': boolean;
                'category': string;
                'commissionDuration': number;
                'contactEmail': string;
                'contactPhone': string;
                'defaultLinkId': string;
                'description': string;
                'epcNinetyDayAverage': Money;
                'epcSevenDayAverage': Money;
                'id': string;
                'item': Advertiser;
                'joinDate': string;
                'kind': string;
                'logoUrl': string;
                'merchantCenterIds': string[];
                'name': string;
                'payoutRank': string;
                'productFeedsEnabled': boolean;
                'redirectDomains': string[];
                'siteUrl': string;
                'status': string;
            }

            export interface Advertisers {
                'items': Advertiser[];
                'kind': string;
                'nextPageToken': string;
            }

            export interface CcOffer {
                'additionalCardBenefits': string[];
                'additionalCardHolderFee': string;
                'ageMinimum': number;
                'ageMinimumDetails': string;
                'annualFee': number;
                'annualFeeDisplay': string;
                'annualRewardMaximum': number;
                'approvedCategories': string[];
                'aprDisplay': string;
                'balanceComputationMethod': string;
                'balanceTransferTerms': string;
                'bonusRewards': {
                    'amount': number;
                    'details': string;
                }[];
                'carRentalInsurance': string;
                'cardBenefits': string[];
                'cardName': string;
                'cardType': string;
                'cashAdvanceTerms': string;
                'creditLimitMax': number;
                'creditLimitMin': number;
                'creditRatingDisplay': string;
                'defaultFees': {
                    'category': string;
                    'maxRate': number;
                    'minRate': number;
                    'rateType': string;
                }[];
                'disclaimer': string;
                'emergencyInsurance': string;
                'existingCustomerOnly': boolean;
                'extendedWarranty': string;
                'firstYearAnnualFee': number;
                'flightAccidentInsurance': string;
                'foreignCurrencyTransactionFee': string;
                'fraudLiability': string;
                'gracePeriodDisplay': string;
                'imageUrl': string;
                'initialSetupAndProcessingFee': string;
                'introBalanceTransferTerms': string;
                'introCashAdvanceTerms': string;
                'introPurchaseTerms': string;
                'issuer': string;
                'issuerId': string;
                'issuerWebsite': string;
                'kind': string;
                'landingPageUrl': string;
                'latePaymentFee': string;
                'luggageInsurance': string;
                'maxPurchaseRate': number;
                'minPurchaseRate': number;
                'minimumFinanceCharge': string;
                'network': string;
                'offerId': string;
                'offersImmediateCashReward': boolean;
                'overLimitFee': string;
                'prohibitedCategories': string[];
                'purchaseRateAdditionalDetails': string;
                'purchaseRateType': string;
                'returnedPaymentFee': string;
                'rewardPartner': string;
                'rewardUnit': string;
                'rewards': {
                    'additionalDetails': string;
                    'amount': number;
                    'category': string;
                    'expirationMonths': number;
                    'maxRewardTier': number;
                    'minRewardTier': number;
                }[];
                'rewardsExpire': boolean;
                'rewardsHaveBlackoutDates': boolean;
                'statementCopyFee': string;
                'trackingUrl': string;
                'travelInsurance': string;
                'variableRatesLastUpdated': string;
                'variableRatesUpdateFrequency': string;
            }

            export interface CcOffers {
                'items': CcOffer[];
                'kind': string;
            }

            export interface Event {
                'advertiserId': string;
                'advertiserName': string;
                'chargeId': string;
                'chargeType': string;
                'commissionableSales': Money;
                'earnings': Money;
                'eventDate': string;
                'kind': string;
                'memberId': string;
                'modifyDate': string;
                'networkFee': Money;
                'orderId': string;
                'products': {
                    'categoryId': string;
                    'categoryName': string;
                    'earnings': Money;
                    'networkFee': Money;
                    'publisherFee': Money;
                    'quantity': string;
                    'sku': string;
                    'skuName': string;
                    'unitPrice': Money;
                }[];
                'publisherFee': Money;
                'publisherId': string;
                'publisherName': string;
                'status': string;
                'type': string;
            }

            export interface Events {
                'items': Event[];
                'kind': string;
                'nextPageToken': string;
            }

            export interface Link {
                'advertiserId': string;
                'authorship': string;
                'availability': string;
                'clickTrackingUrl': string;
                'createDate': string;
                'description': string;
                'destinationUrl': string;
                'duration': string;
                'endDate': string;
                'epcNinetyDayAverage': Money;
                'epcSevenDayAverage': Money;
                'id': string;
                'imageAltText': string;
                'impressionTrackingUrl': string;
                'isActive': boolean;
                'kind': string;
                'linkType': string;
                'name': string;
                'promotionType': string;
                'specialOffers': {
                    'freeGift': boolean;
                    'freeShipping': boolean;
                    'freeShippingMin': Money;
                    'percentOff': number;
                    'percentOffMin': Money;
                    'priceCut': Money;
                    'priceCutMin': Money;
                    'promotionCodes': string[];
                };
                'startDate': string;
            }

            export interface Links {
                'items': Link[];
                'kind': string;
                'nextPageToken': string;
            }

            export interface Money {
                'amount': number;
                'currencyCode': string;
            }

            export interface Publisher {
                'classification': string;
                'epcNinetyDayAverage': Money;
                'epcSevenDayAverage': Money;
                'id': string;
                'item': Publisher;
                'joinDate': string;
                'kind': string;
                'name': string;
                'payoutRank': string;
                'sites': string[];
                'status': string;
            }

            export interface Publishers {
                'items': Publisher[];
                'kind': string;
                'nextPageToken': string;
            }

            export interface Report {
                'column_names': string[];
                'end_date': string;
                'kind': string;
                'matching_row_count': string;
                'rows': any[][];
                'start_date': string;
                'totals_rows': any[][];
                'type': string;
            }

        }
    }
}