text:
/// <reference path="..\harness.ts" />

const expect: typeof _chai.expect = _chai.expect;

namespace ts.server {
    let lastWrittenToHost: string;
    const mockHost: ServerHost = {
        args: [],
        newLine: "\n",
        useCaseSensitiveFileNames: true,
        write(s): void { lastWrittenToHost = s; },
        readFile: () => undefined,
        writeFile: noop,
        resolvePath(): string { return void 0; },
        fileExists: () => false,
        directoryExists: () => false,
        getDirectories: () => [],
        createDirectory: noop,
        getExecutingFilePath(): string { return void 0; },
        getCurrentDirectory(): string { return void 0; },
        getEnvironmentVariable(): string { return ""; },
        readDirectory() { return []; },
        exit: noop,
        setTimeout() { return 0; },
        clearTimeout: noop,
        setImmediate: () => 0,
        clearImmediate: noop,
        createHash: Harness.mockHash,
    };

    class TestSession extends Session {
        getProjectService() {
            return this.projectService;
        }
    }

    describe("the Session class", () => {
        let session: TestSession;
        let lastSent: protocol.Message;

        function createSession(): TestSession {
            const opts: server.SessionOptions = {
                host: mockHost,
                cancellationToken: nullCancellationToken,
                useSingleInferredProject: false,
                useInferredProjectPerProjectRoot: false,
                typingsInstaller: undefined,
                byteLength: Utils.byteLength,
                hrtime: process.hrtime,
                logger: projectSystem.nullLogger,
                canUseEvents: true
            };
            return new TestSession(opts);
        }

        beforeEach(() => {
            session = createSession();
            session.send = (msg: protocol.Message) => {
                lastSent = msg;
            };
        });

        describe("executeCommand", () => {
            it("should throw when commands are executed with invalid arguments", () => {
                const req: protocol.FileRequest = {
                    command: CommandNames.Open,
                    seq: 0,
                    type: "request",
                    arguments: {
                        file: undefined
                    }
                };

                expect(() => session.executeCommand(req)).to.throw();
            });
            it("should output an error response when a command does not exist", () => {
                const req: protocol.Request = {
                    command: "foobar",
                    seq: 0,
                    type: "request"
                };

                session.executeCommand(req);

                const expected: protocol.Response = {
                    command: CommandNames.Unknown,
                    type: "response",
                    seq: 0,
                    message: "Unrecognized JSON command: foobar",
                    request_seq: 0,
                    success: false
                };
                expect(lastSent).to.deep.equal(expected);
            });
            it("should return a tuple containing the response and if a response is required on success", () => {
                const req: protocol.ConfigureRequest = {
                    command: CommandNames.Configure,
                    seq: 0,
                    type: "request",
                    arguments: {
                        hostInfo: "unit test",
                        formatOptions: {
                            newLineCharacter: "`n"
                        }
                    }
                };

                expect(session.executeCommand(req)).to.deep.equal({
                    responseRequired: false
                });
                expect(lastSent).to.deep.equal({
                    command: CommandNames.Configure,
                    type: "response",
                    success: true,
                    request_seq: 0,
                    seq: 0,
                    body: undefined
                });
            });
            it ("should handle literal types in request", () => {
                const configureRequest: protocol.ConfigureRequest = {
                    command: CommandNames.Configure,
                    seq: 0,
                    type: "request",
                    arguments: {
                        formatOptions: {
                            indentStyle: protocol.IndentStyle.Block,
                        }
                    }
                };

                session.onMessage(JSON.stringify(configureRequest));

                assert.equal(session.getProjectService().getFormatCodeOptions().indentStyle, IndentStyle.Block);

                const setOptionsRequest: protocol.SetCompilerOptionsForInferredProjectsRequest = {
                    command: CommandNames.CompilerOptionsForInferredProjects,
                    seq: 1,
                    type: "request",
                    arguments: {
                        options: {
                            module: protocol.ModuleKind.System,
                            target: protocol.ScriptTarget.ES5,
                            jsx: protocol.JsxEmit.React,
                            newLine: protocol.NewLineKind.Lf,
                            moduleResolution: protocol.ModuleResolutionKind.Node,
                        }
                    }
                };
                session.onMessage(JSON.stringify(setOptionsRequest));
                assert.deepEqual(
                    session.getProjectService().getCompilerOptionsForInferredProjects(),
                    <CompilerOptions>{
                        module: ModuleKind.System,
                        target: ScriptTarget.ES5,
                        jsx: JsxEmit.React,
                        newLine: NewLineKind.LineFeed,
                        moduleResolution: ModuleResolutionKind.NodeJs,
                        allowNonTsExtensions: true // injected by tsserver
                    });
            });
        });

        describe("onMessage", () => {
            const allCommandNames: CommandNames[] = [
                CommandNames.Brace,
                CommandNames.BraceFull,
                CommandNames.BraceCompletion,
                CommandNames.Change,
                CommandNames.Close,
                CommandNames.Completions,
                CommandNames.CompletionsFull,
                CommandNames.CompletionDetails,
                CommandNames.CompileOnSaveAffectedFileList,
                CommandNames.Configure,
                CommandNames.Definition,
                CommandNames.DefinitionFull,
                CommandNames.Implementation,
                CommandNames.ImplementationFull,
                CommandNames.Exit,
                CommandNames.Format,
                CommandNames.Formatonkey,
                CommandNames.FormatFull,
                CommandNames.FormatonkeyFull,
                CommandNames.FormatRangeFull,
                CommandNames.Geterr,
                CommandNames.GeterrForProject,
                CommandNames.SemanticDiagnosticsSync,
                CommandNames.SyntacticDiagnosticsSync,
                CommandNames.NavBar,
                CommandNames.NavBarFull,
                CommandNames.Navto,
                CommandNames.NavtoFull,
                CommandNames.NavTree,
                CommandNames.NavTreeFull,
                CommandNames.Occurrences,
                CommandNames.DocumentHighlights,
                CommandNames.DocumentHighlightsFull,
                CommandNames.Open,
                CommandNames.Quickinfo,
                CommandNames.QuickinfoFull,
                CommandNames.References,
                CommandNames.ReferencesFull,
                CommandNames.Reload,
                CommandNames.Rename,
                CommandNames.RenameInfoFull,
                CommandNames.RenameLocationsFull,
                CommandNames.Saveto,
                CommandNames.SignatureHelp,
                CommandNames.SignatureHelpFull,
                CommandNames.TypeDefinition,
                CommandNames.ProjectInfo,
                CommandNames.ReloadProjects,
                CommandNames.Unknown,
                CommandNames.OpenExternalProject,
                CommandNames.CloseExternalProject,
                CommandNames.SynchronizeProjectList,
                CommandNames.ApplyChangedToOpenFiles,
                CommandNames.EncodedSemanticClassificationsFull,
                CommandNames.Cleanup,
                CommandNames.OutliningSpans,
                CommandNames.TodoComments,
                CommandNames.Indentation,
                CommandNames.DocCommentTemplate,
                CommandNames.CompilerOptionsDiagnosticsFull,
                CommandNames.NameOrDottedNameSpan,
                CommandNames.BreakpointStatement,
                CommandNames.CompilerOptionsForInferredProjects,
                CommandNames.GetCodeFixes,
                CommandNames.GetCodeFixesFull,
                CommandNames.GetSupportedCodeFixes,
                CommandNames.GetApplicableRefactors,
                CommandNames.GetEditsForRefactor,
                CommandNames.GetEditsForRefactorFull,
            ];

            it("should not throw when commands are executed with invalid arguments", () => {
                let i = 0;
                for (const name of allCommandNames) {
                    const req: protocol.Request = {
                        command: name,
                        seq: i,
                        type: "request"
                    };
                    i++;
                    session.onMessage(JSON.stringify(req));
                    req.seq = i;
                    i++;
                    req.arguments = {};
                    session.onMessage(JSON.stringify(req));
                    req.seq = i;
                    i++;
                    /* tslint:disable no-null-keyword */
                    req.arguments = null;
                    /* tslint:enable no-null-keyword */
                    session.onMessage(JSON.stringify(req));
                    req.seq = i;
                    i++;
                    req.arguments = "";
                    session.onMessage(JSON.stringify(req));
                    req.seq = i;
                    i++;
                    req.arguments = 0;
                    session.onMessage(JSON.stringify(req));
                    req.seq = i;
                    i++;
                    req.arguments = [];
                    session.onMessage(JSON.stringify(req));
                }
                session.onMessage("GARBAGE NON_JSON DATA");
            });
            it("should output the response for a correctly handled message", () => {
                const req: protocol.ConfigureRequest = {
                    command: CommandNames.Configure,
                    seq: 0,
                    type: "request",
                    arguments: {
                        hostInfo: "unit test",
                        formatOptions: {
                            newLineCharacter: "`n"
                        }
                    }
                };

                session.onMessage(JSON.stringify(req));

                expect(lastSent).to.deep.equal(<protocol.ConfigureResponse>{
                    command: CommandNames.Configure,
                    type: "response",
                    success: true,
                    request_seq: 0,
                    seq: 0,
                    body: undefined
                });
            });
        });

        describe("send", () => {
            it("is an overrideable handle which sends protocol messages over the wire", () => {
                const msg: server.protocol.Request = { seq: 0, type: "request", command: "" };
                const strmsg = JSON.stringify(msg);
                const len = 1 + Utils.byteLength(strmsg, "utf8");
                const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`;

                session.send = Session.prototype.send;
                assert(session.send);
                expect(session.send(msg)).to.not.exist;
                expect(lastWrittenToHost).to.equal(resultMsg);
            });
        });

        describe("addProtocolHandler", () => {
            it("can add protocol handlers", () => {
                const respBody = {
                    item: false
                };
                const command = "newhandle";
                const result = {
                    response: respBody,
                    responseRequired: true
                };

                session.addProtocolHandler(command, () => result);

                expect(session.executeCommand({
                    command,
                    seq: 0,
                    type: "request"
                })).to.deep.equal(result);
            });
            it("throws when a duplicate handler is passed", () => {
                const respBody = {
                    item: false
                };
                const resp = {
                    response: respBody,
                    responseRequired: true
                };
                const command = "newhandle";

                session.addProtocolHandler(command, () => resp);

                expect(() => session.addProtocolHandler(command, () => resp))
                .to.throw(`Protocol handler already exists for command "${command}"`);
            });
        });

        describe("event", () => {
            it("can format event responses and send them", () => {
                const evt = "notify-test";
                const info = {
                    test: true
                };

                session.event(info, evt);

                expect(lastSent).to.deep.equal({
                    type: "event",
                    seq: 0,
                    event: evt,
                    body: info
                });
            });
        });

        describe("output", () => {
            it("can format command responses and send them", () => {
                const body = {
                    block: {
                        key: "value"
                    }
                };
                const command = "test";

                session.output(body, command);

                expect(lastSent).to.deep.equal({
                    seq: 0,
                    request_seq: 0,
                    type: "response",
                    command,
                    body,
                    success: true
                });
            });
        });
    });

    describe("how Session is extendable via subclassing", () => {
        class TestSession extends Session {
            lastSent: protocol.Message;
            customHandler = "testhandler";
            constructor() {
                super({
                    host: mockHost,
                    cancellationToken: nullCancellationToken,
                    useSingleInferredProject: false,
                    useInferredProjectPerProjectRoot: false,
                    typingsInstaller: undefined,
                    byteLength: Utils.byteLength,
                    hrtime: process.hrtime,
                    logger: projectSystem.nullLogger,
                    canUseEvents: true
                });
                this.addProtocolHandler(this.customHandler, () => {
                    return { response: undefined, responseRequired: true };
                });
            }
            send(msg: protocol.Message) {
                this.lastSent = msg;
            }
        }

        it("can override methods such as send", () => {
            const session = new TestSession();
            const body = {
                block: {
                    key: "value"
                }
            };
            const command = "test";

            session.output(body, command);

            expect(session.lastSent).to.deep.equal({
                seq: 0,
                request_seq: 0,
                type: "response",
                command,
                body,
                success: true
            });
        });
        it("can add and respond to new protocol handlers", () => {
            const session = new TestSession();

            expect(session.executeCommand({
                seq: 0,
                type: "request",
                command: session.customHandler
            })).to.deep.equal({
                response: undefined,
                responseRequired: true
            });
        });
        it("has access to the project service", () => {
            class ServiceSession extends TestSession {
                constructor() {
                    super();
                    assert(this.projectService);
                    expect(this.projectService).to.be.instanceOf(ProjectService);
                }
            }
            new ServiceSession();
        });
    });

    describe("an example of using the Session API to create an in-process server", () => {
        class InProcSession extends Session {
            private queue: protocol.Request[] = [];
            constructor(private client: InProcClient) {
                super({
                    host: mockHost,
                    cancellationToken: nullCancellationToken,
                    useSingleInferredProject: false,
                    useInferredProjectPerProjectRoot: false,
                    typingsInstaller: undefined,
                    byteLength: Utils.byteLength,
                    hrtime: process.hrtime,
                    logger: projectSystem.nullLogger,
                    canUseEvents: true
                });
                this.addProtocolHandler("echo", (req: protocol.Request) => ({
                    response: req.arguments,
                    responseRequired: true
                }));
            }

            send(msg: protocol.Message) {
                this.client.handle(msg);
            }

            enqueue(msg: protocol.Request) {
                this.queue.unshift(msg);
            }

            handleRequest(msg: protocol.Request) {
                let response: protocol.Response;
                try {
                    ({ response } = this.executeCommand(msg));
                }
                catch (e) {
                    this.output(undefined, msg.command, msg.seq, e.toString());
                    return;
                }
                if (response) {
                    this.output(response, msg.command, msg.seq);
                }
            }

            consumeQueue() {
                while (this.queue.length > 0) {
                    const elem = this.queue.pop();
                    this.handleRequest(elem);
                }
            }
        }

        class InProcClient {
            private server: InProcSession;
            private seq = 0;
            private callbacks: ((resp: protocol.Response) => void)[] = [];
            private eventHandlers = createMap<(args: any) => void>();

            handle(msg: protocol.Message): void {
                if (msg.type === "response") {
                    const response = <protocol.Response>msg;
                    const handler = this.callbacks[response.request_seq];
                    if (handler) {
                        handler(response);
                        delete this.callbacks[response.request_seq];
                    }
                }
                else if (msg.type === "event") {
                    const event = <protocol.Event>msg;
                    this.emit(event.event, event.body);
                }
            }

            emit(name: string, args: any): void {
                const handler = this.eventHandlers.get(name);
                if (handler) {
                    handler(args);
                }
            }

            on(name: string, handler: (args: any) => void): void {
                this.eventHandlers.set(name, handler);
            }

            connect(session: InProcSession): void {
                this.server = session;
            }

            execute(command: string, args: any, callback: (resp: protocol.Response) => void): void {
                if (!this.server) {
                    return;
                }
                this.seq++;
                this.server.enqueue({
                    seq: this.seq,
                    type: "request",
                    command,
                    arguments: args
                });
                this.callbacks[this.seq] = callback;
            }
        }

        it("can be constructed and respond to commands", (done) => {
            const cli = new InProcClient();
            const session = new InProcSession(cli);
            const toEcho = {
                data: true
            };
            const toEvent = {
                data: false
            };
            let responses = 0;

            // Connect the client
            cli.connect(session);

            // Add an event handler
            cli.on("testevent", (eventinfo) => {
                expect(eventinfo).to.equal(toEvent);
                responses++;
                expect(responses).to.equal(1);
            });

            // Trigger said event from the server
            session.event(toEvent, "testevent");

            // Queue an echo command
            cli.execute("echo", toEcho, (resp) => {
                assert(resp.success, resp.message);
                responses++;
                expect(responses).to.equal(2);
                expect(resp.body).to.deep.equal(toEcho);
            });

            // Queue a configure command
            cli.execute("configure", {
                hostInfo: "unit test",
                formatOptions: {
                    newLineCharacter: "`n"
                }
            }, (resp) => {
                assert(resp.success, resp.message);
                responses++;
                expect(responses).to.equal(3);
                done();
            });

            // Consume the queue and trigger the callbacks
            session.consumeQueue();
        });
    });
}


text:
import * as actions from './index';

describe('book actions', () => {
  it('setArchive', () => {
    const value = true;
    expect(actions.setArchive(value))
      .toEqual({
        type: actions.SET_ARCHIVE,
        value,
      });
  });
});

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"runtime/pprof"
	"github.com/magus424/codesearch/index"
	"github.com/magus424/codesearch/regexp"
)

var usageMessage = `usage: csearch [options] regexp

Options:

  -c           print only a count of selected lines to stdout
  -f PATHREGEXP
               search only files with names matching this regexp
  -h           print this help text and exit
  -i           case-insensitive search
  -l           print only the names of the files containing matches
  -0           print -l matches separated by NUL ('\0') character
  -m MAXCOUNT  limit search output results to MAXCOUNT (0: no limit)
  -n           print each output line preceded by its relative line number in
               the file, starting at 1
  -indexpath FILE
               use specified FILE as the index path. Overrides $CSEARCHINDEX.
  -verbose     print extra information
  -brute       brute force - search all files in index
  -cpuprofile FILE
               write CPU profile to FILE

As per Go's flag parsing convention, the flags cannot be combined: the option
pair -i -n cannot be abbreviated to -in.

csearch behaves like grep over all indexed files, searching for regexp,
an RE2 (nearly PCRE) regular expression.

Csearch relies on the existence of an up-to-date index created ahead of time.
To build or rebuild the index that csearch uses, run:

	cindex path...

where path... is a list of directories or individual files to be included in
the index. If no index exists, this command creates one.  If an index already
exists, cindex overwrites it.  Run cindex -help for more.

csearch uses the index stored in $CSEARCHINDEX or, if that variable is unset or
empty, $HOME/.csearchindex.
`

func usage() {
	fmt.Fprintf(os.Stderr, usageMessage)
	os.Exit(2)
}

var (
	fFlag       = flag.String("f", "", "search only files with names matching this regexp")
	iFlag       = flag.Bool("i", false, "case-insensitive search")
	verboseFlag = flag.Bool("verbose", false, "print extra information")
	bruteFlag   = flag.Bool("brute", false, "brute force - search all files in index")
	cpuProfile  = flag.String("cpuprofile", "", "write cpu profile to this file")
	indexPath   = flag.String("indexpath", "", "specifies index path")
	maxCount    = flag.Int64("m", 0, "specified maximum number of search results")

	matches bool
)

func Main() {
	g := regexp.Grep{
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	g.AddFlags()

	flag.Usage = usage
	flag.Parse()
	args := flag.Args()

	if len(args) != 1 {
		usage()
	}

	if *cpuProfile != "" {
		f, err := os.Create(*cpuProfile)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	if *indexPath != "" {
		err := os.Setenv("CSEARCHINDEX", *indexPath)
		if err != nil {
			log.Fatal(err)
		}
	}

	pat := "(?m)" + args[0]
	if *iFlag {
		pat = "(?i)" + pat
	}
	re, err := regexp.Compile(pat)
	if err != nil {
		log.Fatal(err)
	}
	g.Regexp = re
	var fre *regexp.Regexp
	if *fFlag != "" {
		fre, err = regexp.Compile(*fFlag)
		if err != nil {
			log.Fatal(err)
		}
	}
	q := index.RegexpQuery(re.Syntax)
	if *verboseFlag {
		log.Printf("query: %s\n", q)
	}

	ix := index.Open(index.File())
	ix.Verbose = *verboseFlag
	var post []uint32
	if *bruteFlag {
		post = ix.PostingQuery(&index.Query{Op: index.QAll})
	} else {
		post = ix.PostingQuery(q)
	}
	if *verboseFlag {
		log.Printf("post query identified %d possible files\n", len(post))
	}

	if fre != nil {
		fnames := make([]uint32, 0, len(post))

		for _, fileid := range post {
			name := ix.Name(fileid)
			if fre.MatchString(name, true, true) < 0 {
				continue
			}
			fnames = append(fnames, fileid)
		}

		if *verboseFlag {
			log.Printf("filename regexp matched %d files\n", len(fnames))
		}
		post = fnames
	}

	g.Limit(*maxCount)

	for _, fileid := range post {
		name := ix.Name(fileid)
		g.File(name)
		// short circuit here too
		if g.Done {
			break
		}
	}

	matches = g.Match
}

func main() {
	Main()
	if !matches {
		os.Exit(1)
	}
	os.Exit(0)
}


text:
.. _azure_gettingstarted:

Getting Started
===============

.. _azure_write-policy:

Write your first policy
-----------------------

Cloud Custodian is a stateless rules engine that filters Azure resources and takes actions on based on policies that you define.

Cloud Custodian policies are expressed in YAML and include the following:

* The type of resource to run the policy against
* Filters to narrow down the set of resources
* Actions to take on the filtered set of resources

Our first policy filters to a VM of a specific name, then adds the tag ``Hello: World``.

Create a file named ``custodian.yml`` with the following content. Update ``my_vm_name`` to match an existing VM.

*Note: Some text editors (VSCode) inject invalid whitespace characters when copy/pasting YAML from a browser*

.. code-block:: yaml

    policies:
        - name: my-first-policy
          description: |
            Adds a tag to a virtual machines
          resource: azure.vm
          filters:
            - type: value
              key: name
              value: my_vm_name
          actions:
           - type: tag
             tag: Hello
             value: World

.. _azure_run-policy:

Run your policy
---------------

**Choose one of the supported authentication mechanisms**, and either log in to Azure CLI or set
environment variables as documented in :ref:`azure_authentication`.

.. code-block:: bash

    custodian run --output-dir=. custodian.yml

If successful, you should see output like the following on the command line::

    2016-12-20 08:35:06,133: custodian.policy:INFO Running policy my-first-policy resource: azure.vm
    2016-12-20 08:35:07,514: custodian.policy:INFO policy: my-first-policy resource:azure.vm has count:1 time:1.38
    2016-12-20 08:35:08,188: custodian.policy:INFO policy: my-first-policy action: tag: 1 execution_time: 0.67

You should also find a new ``my-first-policy`` directory with a log and a ``resources.json`` file.

See :ref:`filters` for more information on the features of the Value filter used in this sample.

.. _monitor-azure-cc:

(Optional) Run your policy with Azure Monitoring
""""""""""""""""""""""""""""""""""""""""""""""""

Cloud Custodian policies can emit logs and metrics to Application Insights when the policy executes.
Please refer to the :ref:`azure_monitoring` section for further details.

.. _azure_view_policy_reults:

View policy results
-------------------

The ``resources.json`` file shows you the raw data that results from your policy after filtering.  This file can help you understand the
fields available for your resources while developing your policy.

Custodian Report
"""""""""""""""""""""
Custodian has a report feature that allows the ``resources.json`` file to be viewed more concisely.
By default, this will output data in a CSV format, but report also provides other output formats such as ``grid`` that are more digestable.

When run, the result will look like this::

    +------------+------------+-----------------+-------------------------------------+
    | name       | location   | resourceGroup   | properties.hardwareProfile.vmSize   |
    +============+============+=================+=====================================+
    | my_vm_name | westus     | my_vm_rg        | Standard_D2_v2                      |
    +------------+------------+-----------------+-------------------------------------+

The fields produced by ``custodian report`` vary by resource (i.e. properties.hardwareProfile.vmSize); however, you can add additional fields to your report
by using the ``--field`` parameter. For example, if you want to see a list of tags on this resource:

.. code-block:: bash

    custodian report --output-dir=. --format grid --field tags=tags custodian.yml

Result::

    +------------+------------+-----------------+-------------------------------------+----------------------------+
    | name       | location   | resourceGroup   | properties.hardwareProfile.vmSize   | tagHeader                  |
    +============+============+=================+=====================================+============================+
    | my_vm_name | westus     | my_vm_rg        | Standard_D2_v2                      | {'custodian-tagged': True} |
    +------------+------------+-----------------+-------------------------------------+----------------------------+

The ``field`` parameter has the format ``--field header=field`` where header is the name of the column header in the report,
and field is the JMESPath of a specific field to include in the output. All available fields for a resource can be found in the ``resources.json`` file.

Next Steps
----------
* :ref:`Notify users of policy violations using a Logic App <azure_examples_notifications_logic_app>`
* :ref:`More example policies <azure_examples>`


text:
using Web.Models;

namespace Web.Migrations
{
    using System.Data.Entity.Migrations;

    internal sealed class Configuration : DbMigrationsConfiguration<Web.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            ContextKey = "Web.Models.ApplicationDbContext";
        }

        protected override void Seed(Web.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.
            context.Users.AddOrUpdate(
                new ApplicationUser {
                    MdUser = new MDUser{ InGameName = "Admin" },
                    Email = "admin@moral.dk",
                    PasswordHash = "ACiYR/hF/EC6JFIC/XOgQJinBoASYI/XhUwXKFJhUqSfWCT68l9Ya6dmyZxa+lGsRQ==",
                    SecurityStamp = "7fbcf980-9ae7-44ed-9b34-770741fe7465",
                    UserName = "admin@moral.dk"
                }
            );

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}


text:
package org.test.shop.model.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.test.shop.controller.data.types.ScrollableSettings;
import org.test.shop.model.dao.TmContactDao;
import org.test.shop.model.domain.entity.TmContact;
import org.test.shop.util.data.types.DateCompare;

@Service
@Transactional
public class TmContactService {

	@Autowired
	private TmContactDao tmcontactDao;

	@Transactional
	public TmContact create(TmContact data) {
		return tmcontactDao.create(data);
	}

	@Transactional
	public TmContact update(TmContact data) {
		return tmcontactDao.update(data);
	}

	@Transactional
	public Boolean delete(Object id) {
		return tmcontactDao.delete(id);
	}

	@Transactional
	public void popularity(TmContact data) {
		tmcontactDao.popularity(data);
	}

	@Transactional
	public void popularityByKey(Object data) {
		tmcontactDao.popularityByKey(data);
	}

	@Transactional(readOnly = true)
	public Integer todayNumber(ScrollableSettings settings) throws Exception {
		return tmcontactDao.todayNumber(settings);
	}

	@Transactional(readOnly = true)
	public Integer total(ScrollableSettings settings) throws Exception {
		return tmcontactDao.total(settings);
	}

	@Transactional(readOnly = true)
	public List<TmContact> namedFilter(ScrollableSettings settings) {
		return tmcontactDao.namedFilter(settings);
	}

	@Transactional(readOnly = true)
	public List<TmContact> search(ScrollableSettings settings){
		return  tmcontactDao.search(settings);
	}

	@Transactional(readOnly = true)
	public List<TmContact> findByExample(TmContact example, String delimitter, ScrollableSettings settings) {
		return tmcontactDao.findByExample(example, delimitter, settings);
	}

	@Transactional(readOnly = true)
	public List<TmContact> findByExample2(TmContact example, DateCompare type) {
		return tmcontactDao.findByExample2(example, type);
	}

	@Transactional(readOnly = true)
	public List<TmContact> findAll() {
		return tmcontactDao.findAll(new ScrollableSettings());
	}

	@Transactional(readOnly = true)
	public List<TmContact> findAll(ScrollableSettings settings) {
		return tmcontactDao.findAll(settings);
	}

	@Transactional(readOnly = true)
	public List<TmContact> findAllScrollable(ScrollableSettings settings) {
		return tmcontactDao.findAllScrollable(settings);
	}

	@Transactional(readOnly = true)
	public TmContact findById(ScrollableSettings scrollableSettings) {
		return tmcontactDao.findById(scrollableSettings);
	}

	@Transactional(readOnly = true)
	public TmContact findById(Object key, Boolean initAll) {
		return tmcontactDao.findById(key, initAll);
	}

}


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// tpcc_payment.cpp
//
// Identification: src/main/tpcc/tpcc_payment.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <chrono>
#include <iostream>
#include <ctime>
#include <cassert>
#include <thread>
#include <algorithm>
#include <random>
#include <cstddef>
#include <limits>

#include "benchmark/tpcc/tpcc_workload.h"
#include "benchmark/tpcc/tpcc_configuration.h"
#include "benchmark/tpcc/tpcc_loader.h"

#include "catalog/manager.h"
#include "catalog/schema.h"

#include "type/types.h"
#include "type/value.h"
#include "type/value_factory.h"
#include "common/logger.h"
#include "common/timer.h"
#include "common/generator.h"

#include "concurrency/transaction.h"
#include "concurrency/transaction_manager_factory.h"

#include "executor/executor_context.h"
#include "executor/abstract_executor.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "executor/materialization_executor.h"
#include "executor/update_executor.h"
#include "executor/index_scan_executor.h"
#include "executor/insert_executor.h"

#include "expression/abstract_expression.h"
#include "expression/constant_value_expression.h"
#include "expression/tuple_value_expression.h"
#include "expression/comparison_expression.h"
#include "expression/expression_util.h"
#include "common/container_tuple.h"

#include "index/index_factory.h"

#include "logging/log_manager.h"

#include "planner/abstract_plan.h"
#include "planner/materialization_plan.h"
#include "planner/insert_plan.h"
#include "planner/update_plan.h"
#include "planner/index_scan_plan.h"

#include "storage/data_table.h"
#include "storage/table_factory.h"

namespace peloton {
namespace benchmark {
namespace tpcc {

bool RunPayment(const size_t &thread_id){
  /*
     "PAYMENT": {
     "getWarehouse": "SELECT W_NAME, W_STREET_1, W_STREET_2, W_CITY, W_STATE, W_ZIP FROM WAREHOUSE WHERE W_ID = ?", # w_id
     "updateWarehouseBalance": "UPDATE WAREHOUSE SET W_YTD = W_YTD + ? WHERE W_ID = ?", # h_amount, w_id
     "getDistrict": "SELECT D_NAME, D_STREET_1, D_STREET_2, D_CITY, D_STATE, D_ZIP FROM DISTRICT WHERE D_W_ID = ? AND D_ID = ?", # w_id, d_id
     "updateDistrictBalance": "UPDATE DISTRICT SET D_YTD = D_YTD + ? WHERE D_W_ID = ? AND D_ID = ?", # h_amount, d_w_id, d_id
     "getCustomerByCustomerId": "SELECT C_ID, C_FIRST, C_MIDDLE, C_LAST, C_STREET_1, C_STREET_2, C_CITY, C_STATE, C_ZIP, C_PHONE, C_SINCE, C_CREDIT, C_CREDIT_LIM, C_DISCOUNT, C_BALANCE, C_YTD_PAYMENT, C_PAYMENT_CNT, C_DATA FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?", # w_id, d_id, c_id
     "getCustomersByLastName": "SELECT C_ID, C_FIRST, C_MIDDLE, C_LAST, C_STREET_1, C_STREET_2, C_CITY, C_STATE, C_ZIP, C_PHONE, C_SINCE, C_CREDIT, C_CREDIT_LIM, C_DISCOUNT, C_BALANCE, C_YTD_PAYMENT, C_PAYMENT_CNT, C_DATA FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_LAST = ? ORDER BY C_FIRST", # w_id, d_id, c_last
     "updateBCCustomer": "UPDATE CUSTOMER SET C_BALANCE = ?, C_YTD_PAYMENT = ?, C_PAYMENT_CNT = ?, C_DATA = ? WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?", # c_balance, c_ytd_payment, c_payment_cnt, c_data, c_w_id, c_d_id, c_id
     "updateGCCustomer": "UPDATE CUSTOMER SET C_BALANCE = ?, C_YTD_PAYMENT = ?, C_PAYMENT_CNT = ? WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?", # c_balance, c_ytd_payment, c_payment_cnt, c_w_id, c_d_id, c_id
     "insertHistory": "INSERT INTO HISTORY VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
     }
   */

  LOG_TRACE("-------------------------------------");

  /////////////////////////////////////////////////////////
  // PREPARE ARGUMENTS
  /////////////////////////////////////////////////////////
  int warehouse_id = GenerateWarehouseId(thread_id);
  int district_id = GetRandomInteger(0, state.districts_per_warehouse - 1);
  int customer_warehouse_id;
  int customer_district_id;
  int customer_id = -1;
  std::string customer_lastname;
  double h_amount = GetRandomFixedPoint(2, payment_min_amount, payment_max_amount);
  // WARN: Hard code the date as 0. may cause problem
  int h_date = 0;

  int x = GetRandomInteger(1, 100);
  // currently we only retrieve data by id.
  int y = 100; // GetRandomInteger(1, 100);

  // 85%: paying through own warehouse ( or there is only 1 warehosue)
  if (state.warehouse_count == 1 || x <= 85) {
    customer_warehouse_id = warehouse_id;
    customer_district_id = district_id;
  }
  // 15%: paying through another warehouse
  else {
    customer_warehouse_id = GetRandomIntegerExcluding(0, state.warehouse_count - 1, warehouse_id);
    PL_ASSERT(customer_warehouse_id != warehouse_id);
    customer_district_id = GetRandomInteger(0, state.districts_per_warehouse - 1);
  }

  // 60%: payment by last name
  if (y <= 60) {
    LOG_TRACE("By last name");
    customer_lastname = GetRandomLastName(state.customers_per_district);
  }
  // 40%: payment by id
  else {
    LOG_TRACE("By id");
    customer_id = GetRandomInteger(0, state.customers_per_district - 1);
  }

  std::vector<expression::AbstractExpression *> runtime_keys;

  /////////////////////////////////////////////////////////
  // BEGIN TRANSACTION
  /////////////////////////////////////////////////////////

  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();

  auto txn = txn_manager.BeginTransaction();

  std::unique_ptr<executor::ExecutorContext> context(
    new executor::ExecutorContext(txn));

  std::vector<type::Value > customer;

  if (customer_id >= 0) {
    LOG_TRACE("getCustomerByCustomerId:  WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ? , # w_id = %d, d_id = %d, c_id = %d", warehouse_id, district_id, customer_id);

    std::vector<oid_t> customer_column_ids = {0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20};

    std::vector<oid_t> customer_pkey_column_ids = {0, 1, 2};
    std::vector<ExpressionType> customer_pexpr_types;
    customer_pexpr_types.push_back(
      ExpressionType::COMPARE_EQUAL);
    customer_pexpr_types.push_back(
      ExpressionType::COMPARE_EQUAL);
    customer_pexpr_types.push_back(
      ExpressionType::COMPARE_EQUAL);

    std::vector<type::Value > customer_pkey_values;

    customer_pkey_values.push_back(type::ValueFactory::GetIntegerValue(customer_id).Copy());
    customer_pkey_values.push_back(type::ValueFactory::GetIntegerValue(district_id).Copy());
    customer_pkey_values.push_back(type::ValueFactory::GetIntegerValue(warehouse_id).Copy());

    auto customer_pkey_index = customer_table->GetIndexWithOid(customer_table_pkey_index_oid);

    planner::IndexScanPlan::IndexScanDesc customer_pindex_scan_desc(
      customer_pkey_index, customer_pkey_column_ids, customer_pexpr_types,
      customer_pkey_values, runtime_keys);

    planner::IndexScanPlan customer_pindex_scan_node(customer_table, nullptr,
      customer_column_ids,
      customer_pindex_scan_desc);

    executor::IndexScanExecutor customer_pindex_scan_executor(&customer_pindex_scan_node, context.get());

    auto customer_list = ExecuteRead(&customer_pindex_scan_executor);

    // Check if aborted
    if (txn->GetResult() != ResultType::SUCCESS) {
      LOG_TRACE("abort transaction");
      txn_manager.AbortTransaction(txn);
      return false;
    }

    if (customer_list.size() != 1) {
      PL_ASSERT(false);
    }

    customer = customer_list[0];

  } else {
    PL_ASSERT(customer_lastname.empty() == false);

    LOG_TRACE("getCustomersByLastName: WHERE C_W_ID = ? AND C_D_ID = ? AND C_LAST = ? ORDER BY C_FIRST, # w_id = %d, d_id = %d, c_last = %s", warehouse_id, district_id, customer_lastname.c_str());

    std::vector<oid_t> customer_column_ids = {0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20};

    std::vector<oid_t> customer_key_column_ids = {1, 2, 5};
    std::vector<ExpressionType> customer_expr_types;
    customer_expr_types.push_back(
      ExpressionType::COMPARE_EQUAL);
    customer_expr_types.push_back(
      ExpressionType::COMPARE_EQUAL);
    customer_expr_types.push_back(
      ExpressionType::COMPARE_EQUAL);

    std::vector<type::Value > customer_key_values;

    customer_key_values.push_back(type::ValueFactory::GetIntegerValue(district_id).Copy());
    customer_key_values.push_back(type::ValueFactory::GetIntegerValue(warehouse_id).Copy());
    customer_key_values.push_back(type::ValueFactory::GetVarcharValue(customer_lastname).Copy());

    auto customer_skey_index = customer_table->GetIndexWithOid(customer_table_skey_index_oid);
    PL_ASSERT(customer_skey_index != nullptr);

    planner::IndexScanPlan::IndexScanDesc customer_index_scan_desc(
      customer_skey_index, customer_key_column_ids, customer_expr_types,
      customer_key_values, runtime_keys);

    planner::IndexScanPlan customer_index_scan_node(customer_table, nullptr,
      customer_column_ids,
      customer_index_scan_desc);

    executor::IndexScanExecutor customer_index_scan_executor(&customer_index_scan_node, context.get());

    auto customer_list = ExecuteRead(&customer_index_scan_executor);

    // Check if aborted
    if (txn->GetResult() != ResultType::SUCCESS) {
      LOG_TRACE("abort transaction");
      txn_manager.AbortTransaction(txn);
      return false;
    }

    if (customer_list.size() < 1) {
      LOG_INFO("C_W_ID=%d, C_D_ID=%d", warehouse_id, district_id);
      PL_ASSERT(false);
    }

    // Get the midpoint customer's id
    auto mid_pos = (customer_list.size() - 1) / 2;
    customer = customer_list[mid_pos];
  }

  LOG_TRACE("getWarehouse:WHERE W_ID = ? # w_id = %d", warehouse_id);

  std::vector<oid_t> warehouse_key_column_ids = {0};
  std::vector<ExpressionType> warehouse_expr_types;
  warehouse_expr_types.push_back(
      ExpressionType::COMPARE_EQUAL);

  std::vector<type::Value > warehouse_key_values;

  warehouse_key_values.push_back(type::ValueFactory::GetIntegerValue(warehouse_id).Copy());

  auto warehouse_pkey_index = warehouse_table->GetIndexWithOid(warehouse_table_pkey_index_oid);

  planner::IndexScanPlan::IndexScanDesc warehouse_index_scan_desc(
    warehouse_pkey_index, warehouse_key_column_ids, warehouse_expr_types,
    warehouse_key_values, runtime_keys);

  std::vector<oid_t> warehouse_column_ids = {1, 2, 3, 4, 5, 6, 8};

  planner::IndexScanPlan warehouse_index_scan_node(warehouse_table, nullptr,
    warehouse_column_ids,
    warehouse_index_scan_desc);

  executor::IndexScanExecutor warehouse_index_scan_executor(&warehouse_index_scan_node, context.get());

  // Execute the query
  auto warehouse_list = ExecuteRead(&warehouse_index_scan_executor);

  // Check if aborted
  if (txn->GetResult() != ResultType::SUCCESS) {
    LOG_TRACE("abort transaction");
    txn_manager.AbortTransaction(txn);
    return false;
  }

  if (warehouse_list.size() != 1) {
    PL_ASSERT(false);
  }

  LOG_TRACE("getDistrict: WHERE D_W_ID = ? AND D_ID = ?, # w_id = %d, d_id = %d", warehouse_id, district_id);
  // We also retrieve the original D_YTD from this query,
  // which is not the standard TPCC approach

  std::vector<oid_t> district_key_column_ids = {0, 1};
  std::vector<ExpressionType> district_expr_types;
  district_expr_types.push_back(
    ExpressionType::COMPARE_EQUAL);
  district_expr_types.push_back(
    ExpressionType::COMPARE_EQUAL);

  std::vector<type::Value > district_key_values;

  district_key_values.push_back(type::ValueFactory::GetIntegerValue(district_id).Copy());
  district_key_values.push_back(type::ValueFactory::GetIntegerValue(warehouse_id).Copy());

  auto district_pkey_index = district_table->GetIndexWithOid(district_table_pkey_index_oid);

  planner::IndexScanPlan::IndexScanDesc district_index_scan_desc(
    district_pkey_index, district_key_column_ids, district_expr_types,
    district_key_values, runtime_keys);

  std::vector<oid_t> district_column_ids = {2, 3, 4, 5, 6, 7, 9};

  planner::IndexScanPlan district_index_scan_node(district_table, nullptr,
    district_column_ids,
    district_index_scan_desc);

  executor::IndexScanExecutor district_index_scan_executor(&district_index_scan_node, context.get());

  // Execute the query
  auto district_list = ExecuteRead(&district_index_scan_executor);

  // Check if aborted
  if (txn->GetResult() != ResultType::SUCCESS) {
    LOG_TRACE("abort transaction");
    txn_manager.AbortTransaction(txn);
    return false;
  }

  if (district_list.size() != 1) {
    PL_ASSERT(false);
  }

  double warehouse_new_balance = type::ValuePeeker::PeekDouble(warehouse_list[0][6]) + h_amount;

  LOG_TRACE("updateWarehouseBalance: UPDATE WAREHOUSE SET W_YTD = W_YTD + ? WHERE W_ID = ?,# h_amount = %f, w_id = %d", h_amount, warehouse_id);

  std::vector<oid_t> warehouse_update_column_ids = {8};

  std::vector<type::Value > warehouse_update_key_values;

  warehouse_update_key_values.push_back(type::ValueFactory::GetIntegerValue(warehouse_id).Copy());

  planner::IndexScanPlan::IndexScanDesc warehouse_update_index_scan_desc(
    warehouse_pkey_index, warehouse_key_column_ids, warehouse_expr_types,
    warehouse_update_key_values, runtime_keys);

  planner::IndexScanPlan warehouse_update_index_scan_node(warehouse_table, nullptr,
    warehouse_update_column_ids,
    warehouse_update_index_scan_desc);

  executor::IndexScanExecutor warehouse_update_index_scan_executor(&warehouse_update_index_scan_node, context.get());

  TargetList warehouse_target_list;
  DirectMapList warehouse_direct_map_list;

  // Keep the first 8 columns unchanged
  for (oid_t col_itr = 0; col_itr < 8; ++col_itr) {
    warehouse_direct_map_list.emplace_back(col_itr, std::pair<oid_t, oid_t>(0, col_itr));
  }
  // Update the 9th column
  type::Value  warehouse_new_balance_value = type::ValueFactory::GetDecimalValue(warehouse_new_balance).Copy();

  warehouse_target_list.emplace_back(
    8, expression::ExpressionUtil::ConstantValueFactory(warehouse_new_balance_value)
  );

  std::unique_ptr<const planner::ProjectInfo> warehouse_project_info(
    new planner::ProjectInfo(std::move(warehouse_target_list),
                             std::move(warehouse_direct_map_list)));
  planner::UpdatePlan warehouse_update_node(warehouse_table, std::move(warehouse_project_info));

  executor::UpdateExecutor warehouse_update_executor(&warehouse_update_node, context.get());

  warehouse_update_executor.AddChild(&warehouse_update_index_scan_executor);

  // Execute the query
  ExecuteUpdate(&warehouse_update_executor);

  // Check if aborted
  if (txn->GetResult() != ResultType::SUCCESS) {
    LOG_TRACE("abort transaction");
    txn_manager.AbortTransaction(txn);
    return false;
  }

  double district_new_balance = type::ValuePeeker::PeekDouble(district_list[0][6]) + h_amount;

  LOG_TRACE("updateDistrictBalance: UPDATE DISTRICT SET D_YTD = D_YTD + ? WHERE D_W_ID = ? AND D_ID = ?,# h_amount = %f, d_w_id = %d, d_id = %d",
           h_amount, district_id, warehouse_id);

  std::vector<oid_t> district_update_column_ids = {9};

  std::vector<type::Value > district_update_key_values;

  district_update_key_values.push_back(type::ValueFactory::GetIntegerValue(district_id).Copy());
  district_update_key_values.push_back(type::ValueFactory::GetIntegerValue(warehouse_id).Copy());

  planner::IndexScanPlan::IndexScanDesc district_update_index_scan_desc(
    district_pkey_index, district_key_column_ids, district_expr_types,
    district_update_key_values, runtime_keys);

  planner::IndexScanPlan district_update_index_scan_node(district_table, nullptr,
    district_update_column_ids, district_update_index_scan_desc);

  executor::IndexScanExecutor district_update_index_scan_executor(&district_update_index_scan_node, context.get());

  TargetList district_target_list;
  DirectMapList district_direct_map_list;

  // Keep all columns unchanged except for the
  for (oid_t col_itr = 0; col_itr < 11; ++col_itr) {
    if (col_itr != 9) {
      district_direct_map_list.emplace_back(col_itr, std::pair<oid_t, oid_t>(0, col_itr));
    }
  }
  // Update the 10th column
  type::Value  district_new_balance_value = type::ValueFactory::GetDecimalValue(district_new_balance).Copy();

  district_target_list.emplace_back(
    9, expression::ExpressionUtil::ConstantValueFactory(district_new_balance_value)
  );

  std::unique_ptr<const planner::ProjectInfo> district_project_info(
    new planner::ProjectInfo(std::move(district_target_list),
                             std::move(district_direct_map_list)));
  planner::UpdatePlan district_update_node(district_table, std::move(district_project_info));

  executor::UpdateExecutor district_update_executor(&district_update_node, context.get());

  district_update_executor.AddChild(&district_update_index_scan_executor);

  // Execute the query
  ExecuteUpdate(&district_update_executor);

  // Check the result
  if (txn->GetResult() != ResultType::SUCCESS) {
    LOG_TRACE("abort transaction");
    txn_manager.AbortTransaction(txn);
    return false;
  }

  std::string customer_credit = type::ValuePeeker::PeekVarchar(customer[11]);

  double customer_balance = type::ValuePeeker::PeekDouble(customer[14]) - h_amount;
  double customer_ytd_payment = type::ValuePeeker::PeekDouble(customer[15]) + h_amount;
  int customer_payment_cnt = type::ValuePeeker::PeekInteger(customer[16]) + 1;

  customer_id = type::ValuePeeker::PeekInteger(customer[0]);

  // NOTE: Workaround, we assign a constant to the customer's data field

  // Check the credit record of the user
  if (customer_credit == customers_bad_credit) {
    LOG_TRACE("updateBCCustomer:# c_balance = %f, c_ytd_payment = %f, c_payment_cnt = %d, c_data = %s, c_w_id = %d, c_d_id = %d, c_id = %d",
               customer_balance, customer_ytd_payment, customer_payment_cnt, data_constant.c_str(),
               customer_warehouse_id, customer_district_id, customer_id);

    std::vector<oid_t> customer_pkey_column_ids = {0, 1, 2};
    std::vector<ExpressionType> customer_pexpr_types;
    customer_pexpr_types.push_back(
      ExpressionType::COMPARE_EQUAL);
    customer_pexpr_types.push_back(
      ExpressionType::COMPARE_EQUAL);
    customer_pexpr_types.push_back(
      ExpressionType::COMPARE_EQUAL);

    std::vector<type::Value > customer_pkey_values;

    customer_pkey_values.push_back(type::ValueFactory::GetIntegerValue(customer_id).Copy());
    customer_pkey_values.push_back(type::ValueFactory::GetIntegerValue(customer_district_id).Copy());
    customer_pkey_values.push_back(type::ValueFactory::GetIntegerValue(customer_warehouse_id).Copy());

    auto customer_pkey_index = customer_table->GetIndexWithOid(customer_table_pkey_index_oid);

    planner::IndexScanPlan::IndexScanDesc customer_pindex_scan_desc(
      customer_pkey_index, customer_pkey_column_ids, customer_pexpr_types,
      customer_pkey_values, runtime_keys);

    std::vector<oid_t> customer_update_bc_column_ids = {16, 17, 18, 20};

    // Create update executor
    planner::IndexScanPlan customer_update_bc_index_scan_node(customer_table, nullptr,
      customer_update_bc_column_ids,
      customer_pindex_scan_desc);

    executor::IndexScanExecutor customer_update_bc_index_scan_executor(&customer_update_bc_index_scan_node, context.get());

    TargetList customer_bc_target_list;
    DirectMapList customer_bc_direct_map_list;

    // Only update the 17th to 19th and the 21th columns
    for (oid_t col_itr = 0; col_itr < 21; ++col_itr) {
      if ((col_itr >= 16 && col_itr <= 18) || (col_itr == 20)) {
        continue;
      }
      customer_bc_direct_map_list.emplace_back(col_itr, std::pair<oid_t, oid_t>(0, col_itr));
    }

    type::Value customer_new_balance_value = type::ValueFactory::GetDecimalValue(customer_balance).Copy();
    type::Value customer_new_ytd_value = type::ValueFactory::GetDecimalValue(customer_ytd_payment).Copy();
    type::Value customer_new_paycnt_value = type::ValueFactory::GetIntegerValue(customer_payment_cnt).Copy();
    type::Value customer_new_data_value = type::ValueFactory::GetVarcharValue(data_constant.c_str()).Copy();

    customer_bc_target_list.emplace_back(16, expression::ExpressionUtil::ConstantValueFactory(customer_new_balance_value));
    customer_bc_target_list.emplace_back(17, expression::ExpressionUtil::ConstantValueFactory(customer_new_ytd_value));
    customer_bc_target_list.emplace_back(18, expression::ExpressionUtil::ConstantValueFactory(customer_new_paycnt_value));
    customer_bc_target_list.emplace_back(20, expression::ExpressionUtil::ConstantValueFactory(customer_new_data_value));

    std::unique_ptr<const planner::ProjectInfo> customer_bc_project_info(
      new planner::ProjectInfo(
        std::move(customer_bc_target_list),
        std::move(customer_bc_direct_map_list)
      )
    );

    planner::UpdatePlan customer_update_bc_node(customer_table, std::move(customer_bc_project_info));

    executor::UpdateExecutor customer_update_bc_executor(&customer_update_bc_node, context.get());

    customer_update_bc_executor.AddChild(&customer_update_bc_index_scan_executor);

    // Execute the query
    ExecuteUpdate(&customer_update_bc_executor);
  }
  else {
    LOG_TRACE("updateGCCustomer: # c_balance = %f, c_ytd_payment = %f, c_payment_cnt = %d, c_w_id = %d, c_d_id = %d, c_id = %d",
               customer_balance, customer_ytd_payment, customer_payment_cnt,
               customer_warehouse_id, customer_district_id, customer_id);

    std::vector<oid_t> customer_pkey_column_ids = {0, 1, 2};
    std::vector<ExpressionType> customer_pexpr_types;
    customer_pexpr_types.push_back(
      ExpressionType::COMPARE_EQUAL);
    customer_pexpr_types.push_back(
      ExpressionType::COMPARE_EQUAL);
    customer_pexpr_types.push_back(
      ExpressionType::COMPARE_EQUAL);

    std::vector<type::Value > customer_pkey_values;

    customer_pkey_values.push_back(type::ValueFactory::GetIntegerValue(customer_id).Copy());
    customer_pkey_values.push_back(type::ValueFactory::GetIntegerValue(customer_district_id).Copy());
    customer_pkey_values.push_back(type::ValueFactory::GetIntegerValue(customer_warehouse_id).Copy());

    auto customer_pkey_index = customer_table->GetIndexWithOid(customer_table_pkey_index_oid);

    planner::IndexScanPlan::IndexScanDesc customer_pindex_scan_desc(
      customer_pkey_index, customer_pkey_column_ids, customer_pexpr_types,
      customer_pkey_values, runtime_keys);

    std::vector<oid_t> customer_update_gc_column_ids = {16, 17, 18};

    // Create update executor
    planner::IndexScanPlan customer_update_gc_index_scan_node(customer_table, nullptr,
      customer_update_gc_column_ids,
      customer_pindex_scan_desc);

    executor::IndexScanExecutor customer_update_gc_index_scan_executor(&customer_update_gc_index_scan_node, context.get());

    TargetList customer_gc_target_list;
    DirectMapList customer_gc_direct_map_list;

    // Only update the 17th to 19th columns
    for (oid_t col_itr = 0; col_itr < 21; ++col_itr) {
      if (col_itr >= 16 && col_itr <= 18) {
        continue;
      }
      customer_gc_direct_map_list.emplace_back(col_itr, std::pair<oid_t, oid_t>(0, col_itr));
    }
    type::Value  customer_new_balance_value = type::ValueFactory::GetDecimalValue(customer_balance).Copy();
    type::Value  customer_new_ytd_value = type::ValueFactory::GetDecimalValue(customer_ytd_payment).Copy();
    type::Value  customer_new_paycnt_value = type::ValueFactory::GetIntegerValue(customer_payment_cnt).Copy();

    customer_gc_target_list.emplace_back(16, expression::ExpressionUtil::ConstantValueFactory(customer_new_balance_value));
    customer_gc_target_list.emplace_back(17, expression::ExpressionUtil::ConstantValueFactory(customer_new_ytd_value));
    customer_gc_target_list.emplace_back(18, expression::ExpressionUtil::ConstantValueFactory(customer_new_paycnt_value));

    std::unique_ptr<const planner::ProjectInfo> customer_gc_project_info(
      new planner::ProjectInfo(
        std::move(customer_gc_target_list),
        std::move(customer_gc_direct_map_list)
      )
    );

    planner::UpdatePlan customer_update_gc_node(customer_table, std::move(customer_gc_project_info));

    executor::UpdateExecutor customer_update_gc_executor(&customer_update_gc_node, context.get());

    customer_update_gc_executor.AddChild(&customer_update_gc_index_scan_executor);

    // Execute the query
    ExecuteUpdate(&customer_update_gc_executor);
  }

  // Check the result
  if (txn->GetResult() != ResultType::SUCCESS) {
    LOG_TRACE("abort transaction");
    txn_manager.AbortTransaction(txn);
    return false;
  }

  LOG_TRACE("insertHistory: INSERT INTO HISTORY VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
  std::unique_ptr<storage::Tuple> history_tuple(new storage::Tuple(history_table->GetSchema(), true));

  // H_C_ID
  history_tuple->SetValue(0, type::ValueFactory::GetIntegerValue(customer_id), nullptr);
  // H_C_D_ID
  history_tuple->SetValue(1, type::ValueFactory::GetIntegerValue(customer_district_id), nullptr);
  // H_C_W_ID
  history_tuple->SetValue(2, type::ValueFactory::GetIntegerValue(customer_warehouse_id), nullptr);
  // H_D_ID
  history_tuple->SetValue(3, type::ValueFactory::GetIntegerValue(district_id), nullptr);
  // H_W_ID
  history_tuple->SetValue(4, type::ValueFactory::GetIntegerValue(warehouse_id), nullptr);
  // H_DATE
  history_tuple->SetValue(5, type::ValueFactory::GetTimestampValue(h_date), nullptr);
  // H_AMOUNT
  history_tuple->SetValue(6, type::ValueFactory::GetDecimalValue(h_amount), nullptr);
  // H_DATA
  // Note: workaround
  history_tuple->SetValue(7, type::ValueFactory::GetVarcharValue(data_constant), context.get()->GetPool());

  planner::InsertPlan history_insert_node(history_table, std::move(history_tuple));
  executor::InsertExecutor history_insert_executor(&history_insert_node, context.get());

  // Execute
  history_insert_executor.Execute();

  // Check result
  if (txn->GetResult() != ResultType::SUCCESS) {
    LOG_TRACE("abort transaction");
    txn_manager.AbortTransaction(txn);
    return false;
  }

  PL_ASSERT(txn->GetResult() == ResultType::SUCCESS);

  auto result = txn_manager.CommitTransaction(txn);

  if (result == ResultType::SUCCESS) {
    return true;
  } else {
    PL_ASSERT(result == ResultType::ABORTED ||
           result == ResultType::FAILURE);
    return false;
  }
}

}
}
}


text:
<!DOCTYPE html>

  <title>Aakash DBC Blog</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="https://aakashl.github.io/default.css">

Welcome to My DBC Blog!

Home

About Me

Blog

Projects

Contact

E-Commerce Fraud Detection

August 23, 2015

      Believe it or not, the e-commerce industry has lost over $3.5 billion in losses in year 2012 alone!

      As more and more businesses start having an online presence, the number of targets for frauders to attack increases. Businesses of any size are open target for online fraud, but solutions do exists to help businesses determine whether or not a payment may be fraudulent. By catching fraudsters before they strike, businesses can increase their bottom line and save lots of potentially lost dollars.

      Luckily, there are various fraud detection systems which exist to help companies weed out and gauge to see if a particular customer or order is fraudulent. A common way these systems work is by identifying various characteristics about the customer such as IP geo-location, proxy detection, device fingerprint, etc. to determine whether or not a customer may be fraudulent. By using a mix of this information, as well as cross-checking between prior cases in their database, fraud detection systems either catch or give a potential risk score to a customer.

      Having a solid fraud detection method or system is key for any sized e-commerce store and can save a company lost time & especially lost dollars.


text:
package com.DKB.shutupdrive.tutorial;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.DKB.shutupdrive.R;

/**
 * Created by kyle on 9/6/15.
 */
public class MainTutorialContent extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.layout_tutorial_content, container, false);

        TextView title = (TextView) rootView.findViewById(R.id.feature_name);
        TextView content = (TextView) rootView.findViewById(R.id.description);
        ImageView pic = (ImageView) rootView.findViewById(R.id.photo);

        title.setText(getString(R.string.app_name));
        content.setText(getString(R.string.stay_safe));
        pic.setImageResource(R.drawable.icon_opt);

        return rootView;
    }
}


text:
package org.apache.avalon.fortress.util;

import org.apache.avalon.framework.CascadingException;

/**
 * This is an exception made up of one or more subexceptions.
 */
public final class CompositeException extends CascadingException
{
    private final Exception[] m_ex;
    private final String m_message;

    public CompositeException( final Exception[] ex )
    {
        this( ex, null );
    }

    public CompositeException( final Exception[] ex, final String message )
    {
        super( message, null );
        m_ex = ex;
        if ( ex == null || ex.length < 1 )
        {
            throw new IllegalArgumentException( "you must specify a contained exception!" );
        }
        if ( message == null )
        {
            final StringBuffer msg = new StringBuffer();
            for ( int i = 0; i < ex.length; i++ )
            {
                if (i > 0) msg.append('\n');
                msg.append( ex[i].getMessage() );
            }
            m_message = msg.toString();
        }
        else
            m_message = message;
    }

    public String getMessage()
    {
        return m_message;
    }

    public Exception[] getExceptions()
    {
        return m_ex;
    }
}


text:
using System;
using System.Collections.Generic;
using NorwegianBlue.Data.Sample;
using NorwegianBlue.Data.SampleSet;
using NorwegianBlue.Notes.AnalysisNotes;

namespace NorwegianBlue.Data.Experiment
{
    public interface IExperimentAnalysis<out T> : IExperimentValues<T> where T : ISampleAnalysis
    {
        dynamic AnalysisScratchPad { get; }
        void AddAnalysisNote(AnalysisNote note);

        // An experiment is the outer-most layer, it is responsible for performing the analysis of each set it holds.
        // NB- this doesn't declare how to specify which algorithms to run on the datasets contained.
        //     Assumed to be via the config file.

        void Analyze( List<Tuple<List<SetAnalyzer<ISampleSetAnalysis<ISampleAnalysis>, ISampleAnalysis>>, List<SampleInSetAnalyzer<ISampleSetAnalysis<ISampleAnalysis>, ISampleAnalysis>>>> commonDataSetsAnalysis,

                      List<Tuple<Type,
                          List<SetAnalyzer<ISampleSetAnalysis<ISampleAnalysis>, ISampleAnalysis>>,
                          List<SampleInSetAnalyzer<ISampleSetAnalysis<ISampleAnalysis>, ISampleAnalysis>>>> dataSetsAnalysis,

                      List<ExperimentAnalyzer<IExperimentAnalysis<ISampleAnalysis>, ISampleAnalysis>> experimentAnalysis
            );
    }
}


text:
/**
 * \file
 * \brief Kernel round-robin scheduling policy
 */

/*
 * Copyright (c) 2007, 2008, 2009, 2010, 2013, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Universitaetstr. 6, CH-8092 Zurich. Attn: Systems Group.
 */

#include <kernel.h>
#include <dispatch.h>
#include <kcb.h>

#include <timer.h> // update_sched_timer

/**
 * \brief Scheduler policy.
 *
 * \return Next DCB to schedule or NULL if wait for interrupts.
 */
struct dcb *schedule(void)
{
    // empty ring
    if(kcb_current->ring_current == NULL) {
        return NULL;
    }

    assert(kcb_current->ring_current->next != NULL);
    assert(kcb_current->ring_current->prev != NULL);

    kcb_current->ring_current = kcb_current->ring_current->next;
    #ifdef CONFIG_ONESHOT_TIMER
    update_sched_timer(kernel_now + kernel_timeslice);
    #endif
    return ring_current;
}

void make_runnable(struct dcb *dcb)
{
    // Insert into schedule ring if not in there already
    if(dcb->prev == NULL || dcb->next == NULL) {
        assert(dcb->prev == NULL && dcb->next == NULL);

        // Ring empty
        if(kcb_current->ring_current == NULL) {
            kcb_current->ring_current = dcb;
            dcb->next = dcb;
        }

        // Insert after current ring position
        dcb->prev = kcb_current->ring_current;
        dcb->next = kcb_current->ring_current->next;
        kcb_current->ring_current->next->prev = dcb;
        kcb_current->ring_current->next = dcb;
    }
}

/**
 * \brief Remove 'dcb' from scheduler ring.
 *
 * Removes dispatcher 'dcb' from the scheduler ring. If it was not in
 * the ring, this function is a no-op. The postcondition for this
 * function is that dcb is not in the ring.
 *
 * \param dcb   Pointer to DCB to remove.
 */
void scheduler_remove(struct dcb *dcb)
{
    // No-op if not in scheduler ring
    if(dcb->prev == NULL || dcb->next == NULL) {
        assert(dcb->prev == NULL && dcb->next == NULL);
        return;
    }

    struct dcb *next = kcb_current->ring_current->next;

    // Remove dcb from scheduler ring
    dcb->prev->next = dcb->next;
    dcb->next->prev = dcb->prev;
    dcb->prev = dcb->next = NULL;

    // Removing ring_current
    if(dcb == kcb_current->ring_current) {
        if(dcb == next) {
            // Only guy in the ring
            kcb_current->ring_current = NULL;
        } else {
            // Advance ring_current
            kcb_current->ring_current = next;
        }
    }
}

/**
 * \brief Yield 'dcb' for the rest of the current timeslice.
 *
 * Re-sorts 'dcb' into the scheduler queue with its release time increased by
 * the timeslice period. It is an error to yield a dispatcher not in the
 * scheduler queue.
 *
 * \param dcb   Pointer to DCB to remove.
 */
void scheduler_yield(struct dcb *dcb)
{
    if(dcb->prev == NULL || dcb->next == NULL) {
        struct dispatcher_shared_generic *dsg =
            get_dispatcher_shared_generic(dcb->disp);
        panic("Yield of %.*s not in scheduler queue", DISP_NAME_LEN,
              dsg->name);
    }

    // No-op for the round-robin scheduler
}

void scheduler_reset_time(void)
{
    // No-Op in RR scheduler
}

void scheduler_convert(void)
{
    enum sched_state from = kcb_current->sched;
    switch (from) {
        case SCHED_RBED:
        {
            // initialize RR ring
            struct dcb *last = NULL;
            for (struct dcb *i = kcb_current->queue_head; i; i = i->next)
            {
                i->prev = last;
                last = i;
            }
            // at this point: we have a dll, but need to close the ring
            kcb_current->queue_head->prev = kcb_current->queue_tail;
            kcb_current->queue_tail->next = kcb_current->queue_head;
            break;
        }
        case SCHED_RR:
            // do nothing
            break;
        default:
            printf("don't know how to convert %d to RBED state\n", from);
            break;
    }
    kcb_current->ring_current = kcb_current->queue_head;
    for (struct dcb *i = kcb_current->ring_current; i != kcb_current->ring_current; i=i->next) {
        printf("dcb %p\n  prev=%p\n  next=%p\n", i, i->prev, i->next);
    }
}

void scheduler_restore_state(void)
{
    // No-Op in RR scheduler
}


text:
'use strict';

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _promise = require('babel-runtime/core-js/promise');

var _promise2 = _interopRequireDefault(_promise);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _getIterator2 = require('babel-runtime/core-js/get-iterator');

var _getIterator3 = _interopRequireDefault(_getIterator2);

// Func to attempt the connection
var handleConnect = function () {
  var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2(opt) {
    return _regenerator2.default.wrap(function _callee2$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            return _context3.abrupt('return', _promise2.default.race([

            // global timeout
            new _promise2.default(function timeout(_, reject) {
              setTimeout(function didTimeout() {
                reject(new Error('Timed out after ' + opt.options.timeout + 'ms'));
              }, opt.options.timeout);
            }),

            // connection handler
            new _promise2.default(function () {
              var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(resolve) {
                var _this = this;

                var _loop;

                return _regenerator2.default.wrap(function _callee$(_context2) {
                  while (1) {
                    switch (_context2.prev = _context2.next) {
                      case 0:
                        _loop = _regenerator2.default.mark(function _loop() {
                          var client;
                          return _regenerator2.default.wrap(function _loop$(_context) {
                            while (1) {
                              switch (_context.prev = _context.next) {
                                case 0:
                                  client = _net2.default.connect(opt.socket, function hasConnected() {
                                    client.end();
                                    resolve(opt.socket.host + ':' + opt.socket.port + ' connected');
                                  });

                                  // Set socket timeout

                                  client.setTimeout(opt.options.socketTimeout);

                                  // Error handler - catch and ignore
                                  client.on('error', function () {});

                                  // Retry after a delay...
                                  _context.next = 5;
                                  return (0, _delay2.default)(opt.options.retry);

                                case 5:
                                case 'end':
                                  return _context.stop();
                              }
                            }
                          }, _loop, _this);
                        });

                      case 1:
                        if (!true) {
                          _context2.next = 5;
                          break;
                        }

                        return _context2.delegateYield(_loop(), 't0', 3);

                      case 3:
                        _context2.next = 1;
                        break;

                      case 5:
                      case 'end':
                        return _context2.stop();
                    }
                  }
                }, _callee, this);
              }));

              function handleConnectResolver(_x3) {
                return _ref2.apply(this, arguments);
              }

              return handleConnectResolver;
            }())]));

          case 1:
          case 'end':
            return _context3.stop();
        }
      }
    }, _callee2, this);
  }));

  return function handleConnect(_x2) {
    return _ref.apply(this, arguments);
  };
}();

var _net = require('net');

var _net2 = _interopRequireDefault(_net);

var _delay = require('delay');

var _delay2 = _interopRequireDefault(_delay);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// Recursively flatten an array
function recursiveFlatten(arr) {
  var res = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = (0, _getIterator3.default)(arr), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var val = _step.value;

      Array.isArray(val) && recursiveFlatten(val, res) || res.push(val);
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return res;
}

module.exports = function () {
  var _ref3 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee3() {
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    var promises, options, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, hosts, _hosts$split, _hosts$split2, host, port;

    return _regenerator2.default.wrap(function _callee3$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:

            // Promises to resolve
            promises = [];

            // Set up our default options

            options = {
              retry: 500, // half a second
              timeout: 30 * 1000, // 30 seconds
              socketTimeout: 1000 };

            // Is the last type an object? Overwrite our defaults with
            // whatever is passed in

            if (!!args[args.length - 1] && args[args.length - 1].constructor === Object) {
              (0, _assign2.default)(options, args.pop());
            }

            // Whatever remains, we'll treat as our hosts -- we'll treat arrays
            // as collections of strings, so flatten
            _iteratorNormalCompletion2 = true;
            _didIteratorError2 = false;
            _iteratorError2 = undefined;
            _context4.prev = 6;
            for (_iterator2 = (0, _getIterator3.default)(recursiveFlatten(args)); !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
              hosts = _step2.value;
              _hosts$split = hosts.split(':');
              _hosts$split2 = (0, _slicedToArray3.default)(_hosts$split, 2);
              host = _hosts$split2[0];
              port = _hosts$split2[1];

              promises.push(handleConnect({
                socket: {
                  host: host,
                  port: port
                },
                options: options
              }));
            }

            // Resolve once all of the promises are ready to go
            _context4.next = 14;
            break;

          case 10:
            _context4.prev = 10;
            _context4.t0 = _context4['catch'](6);
            _didIteratorError2 = true;
            _iteratorError2 = _context4.t0;

          case 14:
            _context4.prev = 14;
            _context4.prev = 15;

            if (!_iteratorNormalCompletion2 && _iterator2.return) {
              _iterator2.return();
            }

          case 17:
            _context4.prev = 17;

            if (!_didIteratorError2) {
              _context4.next = 20;
              break;
            }

            throw _iteratorError2;

          case 20:
            return _context4.finish(17);

          case 21:
            return _context4.finish(14);

          case 22:
            return _context4.abrupt('return', _promise2.default.all(promises));

          case 23:
          case 'end':
            return _context4.stop();
        }
      }
    }, _callee3, this, [[6, 10, 14, 22], [15,, 17, 21]]);
  }));

  function hollaback(_x4) {
    return _ref3.apply(this, arguments);
  }

  return hollaback;
}();


text:
import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;

import java.util.Collection;
import java.util.Set;
import java.util.Arrays;

import static java.util.Collections.*;

/*
 * This class is used to test the ability to store static state across
 * apt rounds.
 */
public class StaticApf implements AnnotationProcessorFactory {
    static int round = -1;

    // Process any set of annotations
    private static final Collection<String> supportedAnnotations
        = unmodifiableCollection(Arrays.asList("*"));

    // No supported options
    private static final Collection<String> supportedOptions = emptySet();

    public Collection<String> supportedAnnotationTypes() {
        return supportedAnnotations;
    }

    public Collection<String> supportedOptions() {
        return supportedOptions;
    }

    public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds,
                                               AnnotationProcessorEnvironment env) {
        return new StaticAp(env);
    }

    private static class StaticAp implements AnnotationProcessor {
        private final AnnotationProcessorEnvironment env;
        StaticAp(AnnotationProcessorEnvironment env) {
            this.env = env;
        }

        public void process() {
            int size = env.getSpecifiedTypeDeclarations().size();

            try {
                round++;
                switch (size) {
                case 0:
                    if (round == 0) {
                        env.getFiler().createSourceFile("Round1").print("class Round1 {}");
                    } else
                        throw new RuntimeException("Got " + size + " decl's in round " + round);
                    break;

                case 1:
                    if (round == 1) {
                        env.getFiler().createSourceFile("AhOne").print("class AhOne {}");
                        env.getFiler().createSourceFile("AndAhTwo").print("class AndAhTwo {}");
                        env.getFiler().createClassFile("Foo");
                    } else
                        throw new RuntimeException("Got " + size + " decl's in round " + round);
                    break;
                case 2:
                    if (round != 2) {
                        throw new RuntimeException("Got " + size + " decl's in round " + round);
                    }
                    break;
                }

            } catch (java.io.IOException ioe) {
                    throw new RuntimeException();
                }

            }

    }
}


text:
'use strict';

import * as actions from './actions';
import R from 'ramda';

let reducer = (state = {}, action) => {
  let newState = (update, remove) => {
    let updatedState = Object.assign({}, state, update);
    const result = R.omit(remove || [], updatedState);
    return result;
  };

  switch(action.type) {
    case actions.FILTER:
      return newState({ filter: action.filter });

    case actions.SELECT_CHARACTER:
      return newState({ selectedCharacter: action.character });

    case actions.CLOSE_MODAL:
      return newState(null, 'selectedCharacter');

    default:
      return state;
  }
};

export default reducer;


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Picker, Platform } from 'react-native'

import Collapsible from '../../components/Collapsible'
import { TYPES as expenseTypes, valueOfKey } from '../../models/expense'

class ExpenseTypePicker extends Component {
  static propTypes = {
    type: PropTypes.string.isRequired,
    updateType: PropTypes.func.isRequired
  }

  updateType = (type) => {
    this.props.updateType(type)
    if (this.collapsible) this.collapsible.collapse()
  }

  render () {
    const isAndroid = Platform.OS === 'android'
    const picker = (
      <Picker
        selectedValue={this.props.type}
        onValueChange={(itemValue, itemIndex) => this.updateType(itemValue)}
      >
        <Picker.Item label={expenseTypes.TRANSPORT.label} value={expenseTypes.TRANSPORT.key} />
        <Picker.Item label={expenseTypes.ACCOMMODATION.label} value={expenseTypes.ACCOMMODATION.key} />
        <Picker.Item label={expenseTypes.EATING.label} value={expenseTypes.EATING.key} />
        <Picker.Item label={expenseTypes.OTHER.label} value={expenseTypes.OTHER.key} />
      </Picker>
    )

    return !isAndroid ? (
      <Collapsible
        ref={(elem) => { this.collapsible = elem }}
        value={valueOfKey(this.props.type)}
      >
        {picker}
      </Collapsible>
    ) : picker
  }
}

export default ExpenseTypePicker


text:
namespace autoboost { namespace accumulators
{

AUTOBOOST_PARAMETER_KEYWORD(tag, sample)
AUTOBOOST_ACCUMULATORS_IGNORE_GLOBAL(sample)

}} // namespace autoboost::accumulators

#endif


text:
currentMenu: milagro-mfa-email-verification
---

#Email Verification

**1.** Stop all the M-Pin services by running the following command in the M-Pin installation directory (default is /opt/mpin):

```
sudo ./mpin stop all</div>
```

You need to edit /opt/mpin/config_demo.py

Scroll down to the **# Verification emails settings;** section and amend/add the following parameters:

**_forceActivate:_** change this to **False**

**_emailSubject:_** set this to the subject you wish your verification email to have. The default subject is
set as: 'M-Pin demo: New user activation'

**_emailSender:_** set this to the email address that you want the verification email to be sent from

**_smtpServer:_** the name of the SMTP server you are using

**_smtpPort:_** the port of the SMTP server you are using. Default is ***25***

**_smtpUser:_** the username of your SMTP account

**_smtpPassword:_** the password for the above account

**_smtpUseTLS:_** change this to **True** and uncomment it to enable it.

**2.** Now start all the M-Pin services:
```
sudo ./mpin start all
```
**3.** Visit the following URL again:

```
http://IP ADDRESS:8005
```

Your identity already exists in the browser, so the PIN pad will immediately ask you for your PIN to login.

However, as we now want to show email verification working, instead of entering your PIN, take the following steps:

- Click the menu icon at the top-right of the PIN pad to display the identity management screen.
- Click the pencil icon next to your identity, then **Remove identity**
- Confirm it by clicking **Yes, Remove it.**
- You will then see the screen which prompts you to create a new identity.
- Enter your email address, then **Setup M-Pin**
- You should get an email with an activation link. Click that activation link in your email to confirm your identity.
- Click **Confirm and activate** to activate your identity.
- Once you have activated it, close this screen and go back to your Identity page and click **I confirmed my email**.
- The next screen with your new email address indicates that it has been verified.

**4.** Now just set up your pin and knock yourselves out!


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.operator.scalar;

import com.facebook.presto.common.QualifiedObjectName;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.metadata.BoundVariables;
import com.facebook.presto.metadata.FunctionAndTypeManager;
import com.facebook.presto.metadata.SqlScalarFunction;
import com.facebook.presto.spi.function.FunctionKind;
import com.facebook.presto.spi.function.Signature;
import com.facebook.presto.spi.function.SqlFunctionVisibility;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;

import java.lang.invoke.MethodHandle;

import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature;
import static com.facebook.presto.metadata.BuiltInTypeAndFunctionNamespaceManager.DEFAULT_NAMESPACE;
import static com.facebook.presto.operator.scalar.BuiltInScalarFunctionImplementation.ArgumentProperty.valueTypeArgumentProperty;
import static com.facebook.presto.operator.scalar.BuiltInScalarFunctionImplementation.NullConvention.RETURN_NULL_ON_NULL;
import static com.facebook.presto.spi.function.Signature.typeVariable;
import static com.facebook.presto.spi.function.SqlFunctionVisibility.PUBLIC;
import static com.facebook.presto.util.Reflection.methodHandle;

public class ArrayToElementConcatFunction
        extends SqlScalarFunction
{
    public static final ArrayToElementConcatFunction ARRAY_TO_ELEMENT_CONCAT_FUNCTION = new ArrayToElementConcatFunction();

    private static final MethodHandle METHOD_HANDLE_BOOLEAN = methodHandle(ArrayConcatUtils.class, "appendElement", Type.class, Block.class, boolean.class);
    private static final MethodHandle METHOD_HANDLE_LONG = methodHandle(ArrayConcatUtils.class, "appendElement", Type.class, Block.class, long.class);
    private static final MethodHandle METHOD_HANDLE_DOUBLE = methodHandle(ArrayConcatUtils.class, "appendElement", Type.class, Block.class, double.class);
    private static final MethodHandle METHOD_HANDLE_SLICE = methodHandle(ArrayConcatUtils.class, "appendElement", Type.class, Block.class, Slice.class);
    private static final MethodHandle METHOD_HANDLE_OBJECT = methodHandle(ArrayConcatUtils.class, "appendElement", Type.class, Block.class, Object.class);

    public ArrayToElementConcatFunction()
    {
        super(new Signature(
                QualifiedObjectName.valueOf(DEFAULT_NAMESPACE, "concat"),
                FunctionKind.SCALAR,
                ImmutableList.of(typeVariable("E")),
                ImmutableList.of(),
                parseTypeSignature("array(E)"),
                ImmutableList.of(parseTypeSignature("array(E)"), parseTypeSignature("E")),
                false));
    }

    @Override
    public SqlFunctionVisibility getVisibility()
    {
        return PUBLIC;
    }

    @Override
    public boolean isDeterministic()
    {
        return true;
    }

    @Override
    public String getDescription()
    {
        return "Concatenates an array to an element";
    }

    @Override
    public BuiltInScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, FunctionAndTypeManager functionAndTypeManager)
    {
        Type type = boundVariables.getTypeVariable("E");
        MethodHandle methodHandle;
        if (type.getJavaType() == boolean.class) {
            methodHandle = METHOD_HANDLE_BOOLEAN;
        }
        else if (type.getJavaType() == long.class) {
            methodHandle = METHOD_HANDLE_LONG;
        }
        else if (type.getJavaType() == double.class) {
            methodHandle = METHOD_HANDLE_DOUBLE;
        }
        else if (type.getJavaType() == Slice.class) {
            methodHandle = METHOD_HANDLE_SLICE;
        }
        else {
            methodHandle = METHOD_HANDLE_OBJECT;
        }
        methodHandle = methodHandle.bindTo(type);

        return new BuiltInScalarFunctionImplementation(
                false,
                ImmutableList.of(
                        valueTypeArgumentProperty(RETURN_NULL_ON_NULL),
                        valueTypeArgumentProperty(RETURN_NULL_ON_NULL)),
                methodHandle);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Wingfield, Wyk & Wingfield, Trans. Br. mycol. Soc. 89(4): 517 (1987)

#### Original name
Phialocephala truncata B. Sutton, 1975

### Remarks
null


text:
package com.digitalplay.network.ireader.common.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import com.digitalplay.network.ireader.common.domain.IdEntity;
import com.digitalplay.network.ireader.common.repository.BaseRepository;
import com.digitalplay.network.ireader.common.search.SearchRequest;

public abstract class BaseService<M extends IdEntity<ID>, ID extends Serializable> {

    protected BaseRepository<M, ID> baseRepository;

    @Autowired
    public void setBaseRepository(BaseRepository<M, ID> baseRepository) {
        this.baseRepository = baseRepository;
    }

    /**
     * 保存单个实体
     *
     * @param m 实体
     * @return 返回保存的实体
     */
    public M save(M m) {
        return baseRepository.save(m);
    }

    public M saveAndFlush(M m) {
        m = save(m);
        baseRepository.flush();
        return m;
    }

    /**
     * 更新单个实体
     *
     * @param m 实体
     * @return 返回更新的实体
     */
    public M update(M m) {
        return baseRepository.save(m);
    }

    /**
     * 根据主键删除相应实体
     *
     * @param id 主键
     */
    public void delete(ID id) {
        baseRepository.delete(id);
    }

    /**
     * 删除实体
     *
     * @param m 实体
     */
    public void delete(M m) {
        baseRepository.delete(m);
    }

    /**
     * 根据主键删除相应实体
     *
     * @param ids 实体
     */
    public void delete(ID[] ids) {
        baseRepository.delete(ids);
    }

    /**
     * 按照主键查询
     *
     * @param id 主键
     * @return 返回id对应的实体
     */
    public M findOne(ID id) {
        return baseRepository.findOne(id);
    }

    /**
     * 实体是否存在
     *
     * @param id 主键
     * @return 存在 返回true,否则false
     */
    public boolean exists(ID id) {
        return baseRepository.exists(id);
    }

    /**
     * 统计实体总数
     *
     * @return 实体总数
     */
    public long count() {
        return baseRepository.count();
    }

    public List<M> findAll() {
        return baseRepository.findAll();
    }

    /**
     * 分页及排序查询实体
     *
     * @param pageable 分页及排序数据
     * @return
     */
    public Page<M> findAll(Pageable pageable) {
        return baseRepository.findAll(pageable);
    }

    /**
     * 按条件分页排序查询实体
     *
     * @param SearchRequest 条件
     * @return
     */
    public List<M> findAll(SearchRequest searchRequest) {
    	return baseRepository.findAll(searchRequest);
    }

    public List<M> findAll(SearchRequest searchRequest, Sort sort){
    	return baseRepository.findAll(searchRequest, sort);
    }

    public Page<M> findAll(SearchRequest searchRequest ,Pageable pageable){
    	return baseRepository.findAll(searchRequest,pageable);
    }

    /**
     * 按条件分页并排序统计实体数量
     *
     * @param SearchRequest 条件
     * @return
     */
    public Long count(SearchRequest SearchRequest) {
        return baseRepository.count(SearchRequest);
    }

}