text:
package org.apache.jena.sparql.algebra ;

import static org.apache.jena.sparql.core.Vars.addVar ;

import java.util.* ;

import org.apache.jena.atlas.lib.SetUtils ;
import org.apache.jena.atlas.lib.tuple.Tuple ;
import org.apache.jena.atlas.lib.tuple.TupleFactory ;
import org.apache.jena.graph.Node ;
import org.apache.jena.graph.Triple ;
import org.apache.jena.sparql.algebra.OpWalker.WalkerVisitor ;
import org.apache.jena.sparql.algebra.op.* ;
import org.apache.jena.sparql.core.BasicPattern ;
import org.apache.jena.sparql.core.Var ;
import org.apache.jena.sparql.expr.ExprVars ;
import org.apache.jena.sparql.pfunction.PropFuncArg ;
import org.apache.jena.sparql.util.VarUtils ;

/** Get vars for a pattern */

public class OpVars
{
    // Choose the default collector - LinkedHashSet is predictable and
    // keeps the "found" order
    private static Set<Var> collector() {
        return new LinkedHashSet<>() ;
    }

    public static Set<Var> visibleVars(Op op) {
        Set<Var> acc = collector() ;
        visibleVars(op, acc) ;
        return acc ;
    }

    public static void visibleVars(Op op, Set<Var> acc) {
        OpVarsPattern visitor = new OpVarsPattern(acc, true) ;
        OpWalker.walk(new WalkerVisitorVisible(visitor, acc), op) ;
    }

    /** The set of variables that wil be in every solution of this Op */
    public static Set<Var> fixedVars(Op op) {
        Set<Var> acc = collector() ;
        fixedVars(op, acc) ;
        return acc ;
    }

    public static void fixedVars(Op op, Set<Var> acc) {
        OpVarsPattern visitor = new OpVarsPattern(acc, true) ;
        OpWalker.walk(new WalkerVisitorFixed(visitor, acc), op) ;
    }

    public static Tuple<Set<Var>> mentionedVarsByPosition(Op op) {
        Set<Var> graphAcc = collector() ;
        Set<Var> subjAcc = collector() ;
        Set<Var> predAcc = collector() ;
        Set<Var> objAcc = collector() ;
        Set<Var> unknownAcc = collector() ;
        OpVarsPatternWithPositions visitor = new OpVarsPatternWithPositions(graphAcc, subjAcc, predAcc, objAcc, unknownAcc, false);
        OpWalker.walk(op, visitor);
        return TupleFactory.tuple(graphAcc, subjAcc, predAcc, objAcc, unknownAcc);
    }

    public static Tuple<Set<Var>> mentionedVarsByPosition(Op... ops) {
        Set<Var> graphAcc = collector() ;
        Set<Var> subjAcc = collector() ;
        Set<Var> predAcc = collector() ;
        Set<Var> objAcc = collector() ;
        Set<Var> unknownAcc = collector() ;
        OpVarsPatternWithPositions visitor = new OpVarsPatternWithPositions(graphAcc, subjAcc, predAcc, objAcc, unknownAcc, false);
        for (Op op : ops)
            OpWalker.walk(op, visitor);
        return TupleFactory.tuple(graphAcc, subjAcc, predAcc, objAcc, unknownAcc);
    }

    // All mentioned variables regardless of scope/visibility.
    public static Collection<Var> mentionedVars(Op op) {
        Set<Var> acc = collector() ;
        mentionedVars(op, acc) ;
        return acc ;
    }

    // All mentioned variables regardless of scope/visibility.
    public static void mentionedVars(Op op, Set<Var> acc) {
        OpVarsMentioned visitor = new OpVarsMentioned(acc) ;
        OpWalker.walk(op, visitor) ;
    }

    /** Do project and don't walk into it. MINUS vars aren't visible either */
    private static class WalkerVisitorVisible extends WalkerVisitor
    {
        private final Collection<Var> acc ;

        public WalkerVisitorVisible(OpVarsPattern visitor, Collection<Var> acc) {
            super(visitor) ;
            this.acc = acc ;
        }

        @Override
        public void visit(OpProject op) {
            before(op) ;
            // Skip Project subop.
            acc.addAll(op.getVars()) ;
            after(op) ;
        }

        @Override
        public void visit(OpMinus op) {
            before(op) ;
            if (op.getLeft() != null)
                op.getLeft().visit(this) ;
            // Skip right.
            // if ( op.getRight() != null ) op.getRight().visit(this) ;
            if (visitor != null)
                op.visit(visitor) ;
            after(op) ;
        }
    }

    // Only consider variables that are visible and definitely defined.
    // OPTIONAL (2 forms) and UNION are the interesting cases.
    private static class WalkerVisitorFixed extends WalkerVisitor
    {
        private final Collection<Var> acc ;

        public WalkerVisitorFixed(OpVarsPattern visitor, Collection<Var> acc) {
            super(visitor) ;
            this.acc = acc ;
        }

        @Override
        public void visit(OpLeftJoin x) {
            x.getLeft().visit(this);
        }

        @Override
        public void visit(OpConditional x) {
            x.getLeft().visit(this);
        }

        @Override
        public void visit(OpUnion x) {
            Set<Var> left = fixedVars(x.getLeft()) ;
            Set<Var> right = fixedVars(x.getRight()) ;
            Set<Var> r = SetUtils.intersection(left,  right) ;
            acc.addAll(r) ;
        }

        @Override
        public void visit(OpProject op) {
            before(op) ;
            // Skip Project subop.
            acc.addAll(op.getVars()) ;
            after(op) ;
        }

        @Override
        public void visit(OpMinus op) {
            before(op) ;
            if (op.getLeft() != null)
                op.getLeft().visit(this) ;
            // Skip right.
            // if ( op.getRight() != null ) op.getRight().visit(this) ;
            if (visitor != null)
                op.visit(visitor) ;
            after(op) ;
        }
    }

    private static class OpVarsPattern extends OpVisitorBase
    {
        // The possibly-set-vars
        protected Set<Var> acc ;
        final boolean      visibleOnly ;

        OpVarsPattern(Set<Var> acc, boolean visibleOnly) {
            this.acc = acc ;
            this.visibleOnly = visibleOnly ;
        }

        @Override
        public void visit(OpBGP opBGP) {
            VarUtils.addVars(acc, opBGP.getPattern()) ;
        }

        @Override
        public void visit(OpPath opPath) {
            addVar(acc, opPath.getTriplePath().getSubject()) ;
            addVar(acc, opPath.getTriplePath().getObject()) ;
        }

        @Override
        public void visit(OpQuadPattern quadPattern) {
            addVar(acc, quadPattern.getGraphNode()) ;
            VarUtils.addVars(acc, quadPattern.getBasicPattern()) ;
//            // Pure quading
//            for (Iterator<Quad> iter = quadPattern.getQuads().iterator(); iter.hasNext();) {
//                Quad quad = iter.next() ;
//                addVarsFromQuad(acc, quad) ;
//            }
        }

        @Override
        public void visit(OpGraph opGraph) {
            addVar(acc, opGraph.getNode()) ;
        }

        @Override
        public void visit(OpDatasetNames dsNames) {
            addVar(acc, dsNames.getGraphNode()) ;
        }

        @Override
        public void visit(OpTable opTable) {
            // Only the variables with values in the tables
            // (When building, undefs didn't get into bindings so no variable
            // mentioned)
            Table t = opTable.getTable() ;
            acc.addAll(t.getVars()) ;
        }

        @Override
        public void visit(OpProject opProject) {
            // The walker (WalkerVisitorVisible) handles this
            // for visible variables, not mentioned variable colelcting.
            // The visibleOnly/clear is simply to be as general as possible.
            if (visibleOnly)
                acc.clear() ;
            acc.addAll(opProject.getVars()) ;
        }

        @Override
        public void visit(OpAssign opAssign) {
            acc.addAll(opAssign.getVarExprList().getVars()) ;
        }

        @Override
        public void visit(OpExtend opExtend) {
            acc.addAll(opExtend.getVarExprList().getVars()) ;
        }

        @Override
        public void visit(OpPropFunc opPropFunc) {
            PropFuncArg.addVars(acc, opPropFunc.getSubjectArgs()) ;
            PropFuncArg.addVars(acc, opPropFunc.getObjectArgs()) ;
        }

        @Override
        public void visit(OpProcedure opProc) {
            opProc.getArgs().varsMentioned(acc) ;
        }

    }

    private static class OpVarsPatternWithPositions extends OpVisitorBase
    {
        // The possibly-set-vars
        protected Set<Var> graphAcc, subjAcc, predAcc, objAcc, unknownAcc ;
        final boolean      visibleOnly ;

        OpVarsPatternWithPositions(Set<Var> graphAcc, Set<Var> subjAcc, Set<Var> predAcc, Set<Var> objAcc, Set<Var> unknownAcc, boolean visibleOnly) {
            this.graphAcc = graphAcc;
            this.subjAcc = subjAcc;
            this.predAcc = predAcc;
            this.objAcc = objAcc;
            this.unknownAcc = unknownAcc;
            this.visibleOnly = visibleOnly ;
        }

        @Override
        public void visit(OpBGP opBGP) {
            vars(opBGP.getPattern()) ;
        }

        @Override
        public void visit(OpPath opPath) {
            addVar(subjAcc, opPath.getTriplePath().getSubject()) ;
            addVar(objAcc, opPath.getTriplePath().getObject()) ;
        }

        @Override
        public void visit(OpQuadPattern quadPattern) {
            addVar(graphAcc, quadPattern.getGraphNode()) ;
            vars(quadPattern.getBasicPattern()) ;
        }

        @Override
        public void visit(OpGraph opGraph) {
            addVar(graphAcc, opGraph.getNode()) ;
        }

        @Override
        public void visit(OpDatasetNames dsNames) {
            addVar(graphAcc, dsNames.getGraphNode()) ;
        }

        @Override
        public void visit(OpTable opTable) {
            // Only the variables with values in the tables
            // (When building, undefs didn't get into bindings so no variable
            // mentioned)
            Table t = opTable.getTable() ;
            // Treat as unknown position
            unknownAcc.addAll(t.getVars()) ;
        }

        @Override
        public void visit(OpProject opProject) {
            // The walker (WalkerVisitorVisible) handles this
            // for visible variables, not mentioned variable collecting.
            // The visibleOnly/clear is simply to be as general as possible.
            List<Var> vs = opProject.getVars();
            if (visibleOnly) {
                clear(graphAcc, vs);
                clear(subjAcc, vs);
                clear(predAcc, vs);
                clear(objAcc, vs);

            }
            for (Var v : vs) {
                if (!graphAcc.contains(v) && !subjAcc.contains(v) && !predAcc.contains(v) && !objAcc.contains(v)) {
                    addVar(unknownAcc, v);
                }
            }
        }

        @Override
        public void visit(OpAssign opAssign) {
            // Unknown position
            unknownAcc.addAll(opAssign.getVarExprList().getVars()) ;
        }

        @Override
        public void visit(OpExtend opExtend) {
            // Unknown position
            unknownAcc.addAll(opExtend.getVarExprList().getVars()) ;
        }

        @Override
        public void visit(OpPropFunc opPropFunc) {
            addvars(subjAcc, opPropFunc.getSubjectArgs()) ;
            addvars(objAcc, opPropFunc.getObjectArgs()) ;
        }

        private void addvars(Set<Var> acc, PropFuncArg pfArg) {
            if (pfArg.isNode()) {
                addVar(acc, pfArg.getArg()) ;
                return ;
            }
            for (Node n : pfArg.getArgList())
                addVar(acc, n) ;
        }

        @Override
        public void visit(OpProcedure opProc) {
            unknownAcc.addAll(OpVars.mentionedVars(opProc));
        }

        private void vars(BasicPattern bp) {
            for (Triple t : bp.getList())
            {
                addVar(subjAcc, t.getSubject());
                addVar(predAcc, t.getPredicate());
                addVar(objAcc, t.getObject());
            }
        }

        private void clear(Set<Var> acc, List<Var> visible) {
            List<Var> toRemove = new ArrayList<>();
            for (Var found : acc)
            {
                if (!visible.contains(found)) {
                    toRemove.add(found);
                }
            }
            for (Var v : toRemove) {
                acc.remove(v);
            }
        }

    }

    private static class OpVarsMentioned extends OpVarsPattern
    {
        OpVarsMentioned(Set<Var> acc) {
            super(acc, false) ;
        }

        @Override
        public void visit(OpFilter opFilter) {
            opFilter.getExprs().varsMentioned(acc) ;
        }

        @Override
        public void visit(OpOrder opOrder) {
            ExprVars.varsMentioned(acc, opOrder.getConditions()) ;
        }
    }
}


text:
package com.mandel.storecast;

import android.content.Intent;
import android.os.SystemClock;
import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.intent.rule.IntentsTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;

import com.mandel.storecast.activity.MainActivity;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.InstrumentationRegistry.getTargetContext;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.action.ViewActions.pressKey;

import static android.support.test.espresso.intent.Intents.intended;
import static android.support.test.espresso.intent.Intents.times;

import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.contrib.RecyclerViewActions.scrollToPosition;
import static android.support.test.espresso.assertion.ViewAssertions.matches;

import	android.view.KeyEvent;

@RunWith(AndroidJUnit4.class)
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity>
{

        private MainActivity mActivity;

	public MainActivityTest() {
		super(MainActivity.class);
	}

	@Before
	public void setUp() throws Exception {
		super.setUp();
		injectInstrumentation(InstrumentationRegistry.getInstrumentation());
		mActivity = (MainActivity)getActivity();
	}

	@Test
	public void testScrollTest() {

		onView(withId(R.id.search)).perform(typeText("mobile"));
		SystemClock.sleep(2000);
		onView(withId(R.id.search)).perform(click(), pressKey(KeyEvent.KEYCODE_ENTER));
		SystemClock.sleep(4000);

		onView(withId(R.id.listview))
			.perform(scrollToPosition(10000));
		SystemClock.sleep(6000);

		onView(withId(R.id.listview))
			.perform(scrollToPosition(10));

		SystemClock.sleep(6000);

		onView(withId(R.id.listview)).check(matches(isDisplayed()));
	}

	@Test
	public void testEmpty() {

		onView(withId(R.id.search)).perform(typeText("ssdffghjkjkmobile"));
		SystemClock.sleep(2000);
		onView(withId(R.id.search)).perform(click(), pressKey(KeyEvent.KEYCODE_ENTER));
		SystemClock.sleep(4000);

		onView(withId(R.id.listview))
			.perform(scrollToPosition(100));
		SystemClock.sleep(6000);

		onView(withId(R.id.listview))
			.perform(scrollToPosition(10));

		SystemClock.sleep(6000);

		onView(withId(R.id.listview)).check(matches(isDisplayed()));
	}

}

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
from setuptools import setup

os.system('make rst')
try:
    readme = open('README.rst').read()
except FileNotFoundError:
    # fallback when installing from source package
    readme = ''

setup(
    name='kodetest',
    version=open(os.path.join('kodetest', 'VERSION')).read().strip(),
    description='Tilhørende tester for programmeringsoppgavene på kodeklubben.github.io',
    long_description=readme,
    author='Arve Seljebu',
    author_email='arve.seljebu@gmail.com',
    url='https://github.com/arve0/kodetest',
    packages=[
        'kodetest',
    ],
    package_dir={'kodetest': 'kodetest'},
    package_data={'kodetest': ['VERSION']},
    include_package_data=True,
    install_requires=[
    ],
    license='MIT',
    zip_safe=False,
    keywords='kodetest',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
    ],
)


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>Quartz.Jobs</name>
    </assembly>
    <members>
        <member name="T:Quartz.Job.DirectoryScanJob">

             Inspects a directory and compares whether any files' "last modified dates"
             have changed since the last time it was inspected.  If one or more files
             have been updated (or created), the job invokes a "call-back" method on an
             identified <see cref="T:Quartz.Job.IDirectoryScanListener"/> that can be found in the
             <see cref="T:Quartz.SchedulerContext"/>.

             <author>pl47ypus</author>
             <author>James House</author>
             <author>Marko Lahma (.NET)</author>
             <author>Chris Knight (.NET)</author>
        </member>
        <member name="F:Quartz.Job.DirectoryScanJob.DirectoryName">
            <see cref="T:Quartz.JobDataMap"/> key with which to specify the directory to be
             monitored - an absolute path is recommended.
        </member>
        <member name="F:Quartz.Job.DirectoryScanJob.DirectoryNames">
            <see cref="T:Quartz.JobDataMap"/> key with which to specify the directories to be
             monitored. Directory paths should be separated by a semi-colon (;) - absolute paths are recommended.
        </member>
        <member name="F:Quartz.Job.DirectoryScanJob.DirectoryProviderName">
            <see cref="T:Quartz.JobDataMap"/> key with which to specify the
            <see cref="T:Quartz.Spi.IDirectoryProvider"/> to be used to provide
            the directory paths to be monitored - absolute paths are recommended.
        </member>
        <member name="F:Quartz.Job.DirectoryScanJob.DirectoryScanListenerName">
            <see cref="T:Quartz.JobDataMap"/> key with which to specify the
            <see cref="T:Quartz.Job.IDirectoryScanListener"/> to be
            notified when the directory contents change.
        </member>
        <member name="F:Quartz.Job.DirectoryScanJob.MinimumUpdateAge">
            <see cref="T:Quartz.JobDataMap"/> key with which to specify a <see cref="T:System.Int64"/>
            value that represents the minimum number of milliseconds that must have
            passed since the file's last modified time in order to consider the file
            new/altered.  This is necessary because another process may still be
            in the middle of writing to the file when the scan occurs, and the
             file may therefore not yet be ready for processing.
            <para>If this parameter is not specified, a default value of 5000 (five seconds) will be used.</para>
        </member>
        <member name="M:Quartz.Job.DirectoryScanJob.Execute(Quartz.IJobExecutionContext)">

            This is the main entry point for job execution. The scheduler will call this method on the
            job once it is triggered.

            <param name="context">The <see cref="T:Quartz.IJobExecutionContext"/> that
            the job will use during execution.</param>
        </member>
        <member name="T:Quartz.Job.DirectoryScanJobModel">

            Internal model to hold settings used by <see cref="T:Quartz.Job.DirectoryScanJob"/>

        </member>
        <member name="M:Quartz.Job.DirectoryScanJobModel.#ctor">

            We only want this type of object to be instantiated by inspecting the data
            of a IJobExecutionContext <see cref="T:Quartz.IJobExecutionContext"/>. Use the
            GetInstance() <see cref="M:Quartz.Job.DirectoryScanJobModel.GetInstance(Quartz.IJobExecutionContext)"/> method to create an instance of this
            object type

        </member>
        <member name="M:Quartz.Job.DirectoryScanJobModel.GetInstance(Quartz.IJobExecutionContext)">

            Creates an instance of DirectoryScanJobModel by inspecting the provided IJobExecutionContext <see cref="T:Quartz.IJobExecutionContext"/>

            <param name="context">Content of the job execution <see cref="T:Quartz.IJobExecutionContext"/></param>
            <returns>Instance of DirectoryScanJobModel based on the IJobExecutionContext <see cref="T:Quartz.IJobExecutionContext"/> passed in</returns>
        </member>
        <member name="M:Quartz.Job.DirectoryScanJobModel.UpdateLastModifiedDate(System.DateTime)">

            Updates the last modified date to the date provided, unless the currently set one is later

            <param name="lastWriteTimeFromFiles">Latest LastWriteTime of the files scanned</param>
        </member>
        <member name="T:Quartz.Job.FileScanJob">

            Inspects a file and compares whether it's "last modified date" has changed
            since the last time it was inspected.  If the file has been updated, the
            job invokes a "call-back" method on an identified
            <see cref="T:Quartz.Job.IFileScanListener" /> that can be found in the
            <see cref="T:Quartz.SchedulerContext" />.

            <author>James House</author>
            <author>Marko Lahma (.NET)</author>
            <seealso cref="T:Quartz.Job.IFileScanListener" />
        </member>
        <member name="F:Quartz.Job.FileScanJob.FileName">

            JobDataMap key with which to specify the name of the file to monitor.

        </member>
        <member name="F:Quartz.Job.FileScanJob.FileScanListenerName">

            JobDataMap key with which to specify the <see cref="T:Quartz.Job.IFileScanListener" />
            to be notified when the file contents change.

        </member>
        <member name="F:Quartz.Job.FileScanJob.MinimumUpdateAge">

            <see cref="T:Quartz.JobDataMap" /> key with which to specify a long
            value that represents the minimum number of milliseconds that must have
            past since the file's last modified time in order to consider the file
            new/altered.  This is necessary because another process may still be
            in the middle of writing to the file when the scan occurs, and the
            file may therefore not yet be ready for processing.

            <para>If this parameter is not specified, a default value of
            5000 (five seconds) will be used.</para>

        </member>
        <member name="P:Quartz.Job.FileScanJob.Log">

            Gets the log.

            <value>The log.</value>
        </member>
        <member name="M:Quartz.Job.FileScanJob.#ctor">

            Initializes a new instance of the <see cref="T:Quartz.Job.FileScanJob"/> class.

        </member>
        <member name="M:Quartz.Job.FileScanJob.Execute(Quartz.IJobExecutionContext)">

            Called by the <see cref="T:Quartz.IScheduler" /> when a <see cref="T:Quartz.ITrigger" />
            fires that is associated with the <see cref="T:Quartz.IJob" />.
            <para>
            The implementation may wish to set a  result object on the
            JobExecutionContext before this method exits.  The result itself
            is meaningless to Quartz, but may be informative to
            <see cref="T:Quartz.IJobListener" />s or
            <see cref="T:Quartz.ITriggerListener" />s that are watching the job's
            execution.
            </para>

            <param name="context">The execution context.</param>
            <seealso cref="T:Quartz.IJob">
            </seealso>
        </member>
        <member name="M:Quartz.Job.FileScanJob.GetLastModifiedDate(System.String)">

            Gets the last modified date.

            <param name="fileName">Name of the file.</param>
            <returns></returns>
        </member>
        <member name="T:Quartz.Job.IDirectoryScanListener">

             Interface for objects wishing to receive a 'call-back' from a <see cref="T:Quartz.Job.DirectoryScanJob"/>

             <remarks>
             <para>Instances should be stored in the <see cref="T:Quartz.SchedulerContext"/> such that the
             <see cref="T:Quartz.Job.DirectoryScanJob"/> can find it.</para>
             </remarks>
             <author>Marko Lahma (.NET)</author>
        </member>
        <member name="M:Quartz.Job.IDirectoryScanListener.FilesUpdatedOrAdded(System.Collections.Generic.IReadOnlyCollection{System.IO.FileInfo})">
            <param name="updatedFiles">
            An array of <see cref="T:System.IO.FileInfo"/> objects that were updated/added since the last scan of the directory
            </param>
        </member>
        <member name="T:Quartz.Job.IFileScanListener">

            Interface for objects wishing to receive a 'call-back' from a
            <see cref="T:Quartz.Job.FileScanJob" />.

            <author>James House</author>
            <author>Marko Lahma (.NET)</author>
            <seealso cref="T:Quartz.Job.FileScanJob" />
        </member>
        <member name="M:Quartz.Job.IFileScanListener.FileUpdated(System.String,System.Threading.CancellationToken)">

            Informs that certain file has been updated.

        </member>
        <member name="T:Quartz.Job.NativeJob">

            Built in job for executing native executables in a separate process.

            <remarks>
            <example>
                JobDetail job = new JobDetail("dumbJob", null, typeof(Quartz.Jobs.NativeJob));
                job.JobDataMap.Put(Quartz.Jobs.NativeJob.PropertyCommand, "echo \"hi\" >> foobar.txt");
                Trigger trigger = TriggerUtils.MakeSecondlyTrigger(5);
                trigger.Name = "dumbTrigger";
                sched.ScheduleJob(job, trigger);
            </example>
            If PropertyWaitForProcess is true, then the integer exit value of the process
            will be saved as the job execution result in the JobExecutionContext.
            </remarks>
            <author>Matthew Payne</author>
            <author>James House</author>
            <author>Steinar Overbeck Cook</author>
            <author>Marko Lahma (.NET)</author>
        </member>
        <member name="F:Quartz.Job.NativeJob.PropertyCommand">

            Required parameter that specifies the name of the command (executable)
            to be ran.

        </member>
        <member name="F:Quartz.Job.NativeJob.PropertyParameters">

            Optional parameter that specifies the parameters to be passed to the
            executed command.

        </member>
        <member name="F:Quartz.Job.NativeJob.PropertyWaitForProcess">

             Optional parameter (value should be 'true' or 'false') that specifies
             whether the job should wait for the execution of the native process to
             complete before it completes.

             <para>Defaults to <see langword="true" />.</para>

        </member>
        <member name="F:Quartz.Job.NativeJob.PropertyConsumeStreams">

             Optional parameter (value should be 'true' or 'false') that specifies
             whether the spawned process's stdout and stderr streams should be
             consumed.  If the process creates output, it is possible that it might
             'hang' if the streams are not consumed.

             <para>Defaults to <see langword="false" />.</para>

        </member>
        <member name="F:Quartz.Job.NativeJob.PropertyWorkingDirectory">

            Optional parameter that specifies the working directory to be used by
            the executed command.

        </member>
        <member name="P:Quartz.Job.NativeJob.Log">

            Gets the log.

            <value>The log.</value>
        </member>
        <member name="M:Quartz.Job.NativeJob.#ctor">

            Initializes a new instance of the <see cref="T:Quartz.Job.NativeJob"/> class.

        </member>
        <member name="M:Quartz.Job.NativeJob.Execute(Quartz.IJobExecutionContext)">

            Called by the <see cref="T:Quartz.IScheduler" /> when a <see cref="T:Quartz.ITrigger" />
            fires that is associated with the <see cref="T:Quartz.IJob" />.
            <para>
            The implementation may wish to set a  result object on the
            JobExecutionContext before this method exits.  The result itself
            is meaningless to Quartz, but may be informative to
            <see cref="T:Quartz.IJobListener" />s or
            <see cref="T:Quartz.ITriggerListener" />s that are watching the job's
            execution.
            </para>

            <param name="context"></param>
        </member>
        <member name="T:Quartz.Job.NativeJob.StreamConsumer">

            Consumes data from the given input stream until EOF and prints the data to stdout

            <author>cooste</author>
            <author>James House</author>
        </member>
        <member name="M:Quartz.Job.NativeJob.StreamConsumer.#ctor(Quartz.Job.NativeJob,System.IO.Stream,System.String)">

            Initializes a new instance of the <see cref="T:Quartz.Job.NativeJob.StreamConsumer"/> class.

            <param name="enclosingInstance">The enclosing instance.</param>
            <param name="inputStream">The input stream.</param>
            <param name="type">The type.</param>
        </member>
        <member name="M:Quartz.Job.NativeJob.StreamConsumer.Run">

            Runs this object as a separate thread, printing the contents of the input stream
            supplied during instantiation, to either Console. or stderr

        </member>
        <member name="T:Quartz.Job.NoOpJob">

            An implementation of Job, that does absolutely nothing - useful for system
            which only wish to use <see cref="T:Quartz.ITriggerListener" />s
            and <see cref="T:Quartz.IJobListener" />s, rather than writing
            Jobs that perform work.

            <author>James House</author>
            <author>Marko Lahma (.NET)</author>
        </member>
        <member name="M:Quartz.Job.NoOpJob.Execute(Quartz.IJobExecutionContext)">

            Do nothing.

        </member>
        <member name="T:Quartz.Job.SendMailJob">

            A Job which sends an e-mail with the configured content to the configured
            recipient.

            <author>James House</author>
            <author>Marko Lahma (.NET)</author>
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertySmtpHost">
             The host name of the smtp server. REQUIRED.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertySmtpPort">
             The port of the smtp server. Optional.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertyUsername">
             Username for authenticated session. Password must also be set if username is used. Optional.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertyPassword">
             Password for authenticated session. Optional.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertyRecipient">
             The e-mail address to send the mail to. REQUIRED.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertyCcRecipient">
             The e-mail address to cc the mail to. Optional.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertySender">
             The e-mail address to claim the mail is from. REQUIRED.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertyReplyTo">
             The e-mail address the message should say to reply to. Optional.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertySubject">
             The subject to place on the e-mail. REQUIRED.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertyMessage">
             The e-mail message body. REQUIRED.
        </member>
        <member name="F:Quartz.Job.SendMailJob.PropertyEncoding">
             The message subject and body content type. Optional.
        </member>
        <member name="M:Quartz.Job.SendMailJob.Execute(Quartz.IJobExecutionContext)">

            Executes the job.

            <param name="context">The job execution context.</param>
        </member>
        <member name="T:Quartz.Simpl.DefaultDirectoryProvider">

            Default directory provider that inspects and parses the merged JobDataMap <see cref="T:Quartz.JobDataMap"/>
            for the entries <see cref="F:Quartz.Job.DirectoryScanJob.DirectoryName"/> and <see cref="F:Quartz.Job.DirectoryScanJob.DirectoryNames"/>
            to supply the directory paths

        </member>
        <member name="T:Quartz.Spi.IDirectoryProvider">
            Interface for objects that wish to provide a list of directory paths to be
             monitored to <see cref="T:Quartz.Job.DirectoryScanJob"/>
            <remarks><para>Instances should be stored in the <see cref="T:Quartz.SchedulerContext"/> such that the
            <see cref="T:Quartz.Job.DirectoryScanJob"/> can find it.</para></remarks>
            <author>Chris Knight (.NET)</author>
        </member>
        <member name="M:Quartz.Spi.IDirectoryProvider.GetDirectoriesToScan(Quartz.JobDataMap)">

            Called by <see cref="T:Quartz.Job.DirectoryScanJob"/> to provide a list of directory paths
            to montitor - absolute paths are recommended.

            <returns></returns>
        </member>
    </members>
</doc>


text:
import { expect } from "chai";
import configureStore from "redux-mock-store";
import thunk from "redux-thunk";

import {
    createViewportActions,
    ZOOM, MOVE, MOVE_BY, RESET, RESIZE, FIT
} from "./viewportActions.js";
import { TreeNode } from "../../core/TreeNode.js";

const mockStore = configureStore([thunk]);

describe("life / viewport actions", () => {

    it("zooms viewport", () => {
        const { zoom } = createViewportActions();
        const factor = 1.5;
        const pivot = { x: 0, y: 0 };

        expect(zoom(factor, pivot)).to.eql({ type: ZOOM, factor, pivot });
    });

    it("moves viewport", () => {
        const { move } = createViewportActions();
        const from = { x: 0, y: 0 };
        const to = { x: 1, y: 10 };

        expect(move(from, to)).to.eql({ type: MOVE, from, to });
    });

    it("moves viewport by given offset", () => {
        const { moveBy } = createViewportActions();
        const dx = 2;
        const dy = 5;

        expect(moveBy(dx, dy)).to.eql({ type: MOVE_BY, dx, dy });
    });

    it("resets viewport", () => {
        const { reset } = createViewportActions();

        expect(reset()).to.eql({ type: RESET });
    });

    it("resizes viewport", () => {
        const { resize } = createViewportActions();
        const width = 1.5;
        const height = 1.2;

        expect(resize(width, height)).to.eql({ type: RESIZE, width, height });
    });

    it("fits viewport to content boundaries", () => {
        const { fit } = createViewportActions();
        const world = { root: TreeNode.alive() };
        const store = mockStore({ life: { world } });

        expect(store.dispatch(fit())).to.eql({ type: FIT, area: { bottom: 7.5, left: -7.5, right: 7.5, top: -7.5 } });
    });
});


text:
package org.apache.camel.component.aws2.sqs;

import org.apache.camel.BindToRegistry;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class SqsComponentTest extends CamelTestSupport {

    @EndpointInject("direct:start")
    private ProducerTemplate template;

    @EndpointInject("mock:result")
    private MockEndpoint result;

    @BindToRegistry("amazonSQSClient")
    private AmazonSQSClientMock client = new AmazonSQSClientMock();

    @Test
    public void sendInOnly() throws Exception {
        result.expectedMessageCount(1);

        Exchange exchange = template.send("direct:start", ExchangePattern.InOnly, new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody("This is my message text.");
            }
        });

        assertMockEndpointsSatisfied();

        Exchange resultExchange = result.getExchanges().get(0);
        assertEquals("This is my message text.", resultExchange.getIn().getBody());
        assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.MESSAGE_ID));
        assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.RECEIPT_HANDLE));
        assertEquals("6a1559560f67c5e7a7d5d838bf0272ee", resultExchange.getIn().getHeader(Sqs2Constants.MD5_OF_BODY));
        assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.ATTRIBUTES));
        assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.MESSAGE_ATTRIBUTES));

        assertEquals("This is my message text.", exchange.getIn().getBody());
        assertNotNull(exchange.getIn().getHeader(Sqs2Constants.MESSAGE_ID));
        assertEquals("6a1559560f67c5e7a7d5d838bf0272ee", exchange.getIn().getHeader(Sqs2Constants.MD5_OF_BODY));
    }

    @Test
    public void sendInOut() throws Exception {
        result.expectedMessageCount(1);

        Exchange exchange = template.send("direct:start", ExchangePattern.InOut, new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody("This is my message text.");
            }
        });

        assertMockEndpointsSatisfied();

        Exchange resultExchange = result.getExchanges().get(0);
        assertEquals("This is my message text.", resultExchange.getIn().getBody());
        assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.RECEIPT_HANDLE));
        assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.MESSAGE_ID));
        assertEquals("6a1559560f67c5e7a7d5d838bf0272ee", resultExchange.getIn().getHeader(Sqs2Constants.MD5_OF_BODY));
        assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.ATTRIBUTES));
        assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.MESSAGE_ATTRIBUTES));

        assertEquals("This is my message text.", exchange.getMessage().getBody());
        assertNotNull(exchange.getMessage().getHeader(Sqs2Constants.MESSAGE_ID));
        assertEquals("6a1559560f67c5e7a7d5d838bf0272ee", exchange.getMessage().getHeader(Sqs2Constants.MD5_OF_BODY));
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            final String sqsURI = String.format(
                    "aws2-sqs://MyQueue?amazonSQSClient=#amazonSQSClient&messageRetentionPeriod=%s&maximumMessageSize=%s&policy=%s",
                    "1209600", "65536",
                    "");

            @Override
            public void configure() throws Exception {
                from("direct:start").to(sqsURI);

                from(sqsURI).to("mock:result");
            }
        };
    }
}


text:
'use strict';

var express = require('express'),
    router  = express.Router(),
    authenticateOverseerToken = require('../middlewares/authenticateOverseerToken'),
    prepareUpdateObject = require('../middlewares/prepareUpdateObject'),
    getCreditTypeId = require('../middlewares/getCreditTypeId'),
    CreditType  = require('models').CreditType,
    Credit = require('models').Credit,
    Sequelize = require('models').Sequelize,
    HttpApiError = require('error').HttpApiError;

router.get('/', function(req, res, next) {
    var offset = +req.query.offset || 0,
        limit = +req.query.limit || 50;

    CreditType
        .findAll({ offset: offset, limit: limit })
        .then(function(creditTypes) {
            res.json({
                count: creditTypes.length,
                offset: offset,
                limit: limit,
                creditTypes: creditTypes
            });
        })
        .catch(function(error) {
            next(error);
        });
});

router.get('/:creditTypeId/credits', getCreditTypeId, function(req, res, next) {
    var offset = +req.query.offset || 0,
        limit = +req.query.limit || 50;

    Credit
        .findAll({
            offset: offset,
            limit: limit,
            where: { credit_type_id: req.creditTypeId }
        })
        .then(function(credits) {
            res.json({
                count: credits.length,
                offset: offset,
                limit: limit,
                credits: credits
            });
        })
        .catch(function(error) {
            next(error);
        });
});

router.get('/:creditTypeId', getCreditTypeId, function(req, res, next) {
    CreditType
        .findById(req.creditTypeId)
        .then(function(creditType) {
            if (!creditType) {
                return res.json({
                    message: 'No credit type has been found with given id'
                });
            }

            res.json(creditType);
        })
        .catch(function(error) {
            next(error);
        });
});

router.post('/', authenticateOverseerToken, function(req, res, next) {
    CreditType
        .create({
            title: req.body.title,
            description: req.body.description,
            minSum: req.body.minSum,
            maxSum: req.body.maxSum,
            minTerm: req.body.minTerm,
            maxTerm: req.body.maxTerm,
            interest: req.body.interest,
            credit_category_id: req.body.creditCategoryId
        })
        .then(function(creditType) {
            res.json({
                creditTypeId: creditType.id
            });
        })
        .catch(Sequelize.ValidationError, function(error) {
            next(new HttpApiError(400, error.message));
        })
        .catch(function(error) {
            next(error);
        });
});

router.patch('/:creditTypeId', authenticateOverseerToken,
                               getCreditTypeId,
                               prepareUpdateObject, function(req, res, next) {
    CreditType
        .update(req.updateObj, {
            where: {
                id: req.creditTypeId
            }
        })
        .then(function() {
            res.json({
                updated: req.creditTypeId
            });
        })
        .catch(Sequelize.ValidationError, function(error) {
            next(new HttpApiError(400, error.message));
        })
        .catch(function(error) {
            next(error);
        });
});

router.delete('/:creditTypeId', authenticateOverseerToken,
                                getCreditTypeId, function(req, res, next) {
    CreditType
        .destroy({
            where: { id: req.creditTypeId }
        })
        .then(function() {
            res.json({
                creditTypeId: req.creditTypeId
            });
        })
        .catch(function(error) {
            next(error);
        });
});

module.exports = router;


text:
<?php
namespace Resume\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Assetic\Filter;
use Michelf\MarkdownExtra;
use Michelf\SmartyPants;
use Sunra\PhpSimple\HtmlDomParser;

class HtmlCommand extends Command
{
    protected function configure()
    {
        // resume html source.md resume.html -template blockish -refresh
        $this
            ->setName('html')
            ->setDescription('Generate an HTML resume from a markdown file')
            ->addArgument(
                'source',
                InputArgument::REQUIRED,
                'Source markdown document'
            )
            ->addArgument(
                'destination',
                InputArgument::REQUIRED,
                'Output destination folder'
            )
            ->addOption(
                'template',
                't',
                InputOption::VALUE_REQUIRED,
                'Which of the templates to use. Use an absolute path for a custom template.'
            )
            ->addOption(
                'refresh',
                'r',
                InputOption::VALUE_REQUIRED,
                'Regenerate the html and include a meta command to refresh the ' .
                'document every periodically. Measured in seconds.'
            )
            ->addOption(
                'output',
                'o',
                InputOption::VALUE_REQUIRED,
                'The optional override of default filename to output to'
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->app    = $this->getApplication();
        $source       = $input->getArgument('source');
        $sourceName   = pathinfo($source, PATHINFO_FILENAME);
        $destination  = rtrim($input->getArgument('destination'), DIRECTORY_SEPARATOR);
        $template     = $input->getOption('template');
        $refresh      = $input->getOption('refresh');
        $optFilename  = $input->getOption('output');
        $destFilename = "";

        if ($optFilename) {
            $destFilename = $destination . DIRECTORY_SEPARATOR . $optFilename . '.html';
        } else {
            $destFilename = $destination . DIRECTORY_SEPARATOR . $sourceName . '.html';
        }

        $rendered = $this->generateHtml($source, $template, $refresh);
        file_put_contents($destFilename, $rendered);
        $output->writeln(
            sprintf(
                'Wrote resume to: <info>%s</info>',
                $destFilename
            ),
            $this->app->outputFormat
        );

        return true;
    }

    protected function generateContent($templatePath, $contentType)
    {
        // We build these into a single string so that we can deploy this resume as a
        // single file.
        $assetPath = join(DIRECTORY_SEPARATOR, array($templatePath, $contentType));

        if (!file_exists($assetPath)) {
            return '';
        }

        $assets = array();

        // Our PHAR deployment can't handle the GlobAsset typically used here
        foreach (new \DirectoryIterator($assetPath) as $fileInfo) {
            if ($fileInfo->isDot() || !$fileInfo->isFile()) {
                continue;
            }
            array_push($assets, new FileAsset($fileInfo->getPathname()));
        }

        usort($assets, function (FileAsset $a, FileAsset $b) {
            return strcmp($a->getSourcePath(), $b->getSourcePath());
        });

        $collection = new AssetCollection(
            $assets
        );

        switch ($contentType) {
            case 'css':
                $collection->ensureFilter(new Filter\LessphpFilter());
                break;
        }

        return $collection->dump();
    }

    protected function generateHtml($source, $template, $refresh)
    {
        // Check that the source file is sane
        if (!file_exists($source)) {
            throw new \Exception("Unable to open source file: $source");
        }

        // Check that our template is sane, or set to the default one
        if (!$template) {
            $template = $this->app->defaultTemplate;
        }

        if (strpos($template, DIRECTORY_SEPARATOR) !== false) {
            $templatePath = realpath($template);
        } else {
            $templatePath = join(DIRECTORY_SEPARATOR, array($this->app->templatePath, basename($template)));
        }

        $templateIndexPath = join(DIRECTORY_SEPARATOR, array($templatePath, 'index.html'));

        if (!file_exists($templateIndexPath)) {
            throw new \Exception("Unable to open template file: $templateIndexPath");
        }

        $style = $this->generateContent($templatePath, 'css');

        $links = $this->generateContent($templatePath, 'links');

        $templateContent = file_get_contents($templateIndexPath);
        $resumeContent   = file_get_contents($source);

        // Process with Markdown, and then use SmartyPants to clean up punctuation.
        $resumeHtml = MarkdownExtra::defaultTransform($resumeContent);
        $resumeHtml = SmartyPants::defaultTransform($resumeHtml);

        // Construct the title for the html document from the h1 and h2 tags
        $simpleDom = HtmlDomParser::str_get_html($resumeHtml);
        $title = sprintf(
            '%s | %s',
            $simpleDom->find('h1', 0)->innertext,
            $simpleDom->find('h2', 0)->innertext
        );

        // Render the Markdown into an html file with Mustache Templates
        $m = new \Mustache_Engine;
        $rendered = $m->render($templateContent, array(
            'title'        => $title,
            'style'        => $style,
            'links'        => $links,
            'resume'       => $resumeHtml,
            'reload'       => (bool) $refresh,
            'refresh_rate' => $refresh
        ));

        return $rendered;
    }

    protected function determineOutfile($outputFilename)
    {
        return join(DIRECTORY_SEPARATOR, array($destination, pathinfo($source, PATHINFO_FILENAME) . '.html'));
    }
}

/* End of file HtmlCommand.php */


text:
<?php

define('MBQ_PROTOCOL', 'json');   //define is using json protocol,if not defined(default) means is using xmlrpc protocol

require_once('mobiquoCommon.php');

MbqMain::init();  /* frame init */
MbqMain::input();     /* handle input data */
require_once(MBQ_PATH.'IncludeBeforeMbqAppEnv.php');
MbqMain::initAppEnv();    /* application environment init */
@ ob_start();
MbqMain::action();    /* main program handle */
MbqMain::beforeOutput();  /* do something before output */
MbqMain::output();    /* handle output data */

?>


text:
layout: drawing_page
number: 47
permalink: 47/
---


text:
/*
Package spannertest contains test helpers for working with Cloud Spanner.

This package is EXPERIMENTAL, and is lacking many features. See the README.md
file in this directory for more details.

In-memory fake

This package has an in-memory fake implementation of spanner. To use it,
create a Server, and then connect to it with no security:
	srv, err := spannertest.NewServer("localhost:0")
	...
	conn, err := grpc.DialContext(ctx, srv.Addr, grpc.WithInsecure())
	...
	client, err := spanner.NewClient(ctx, db, option.WithGRPCConn(conn))
	...

Alternatively, create a Server, then set the SPANNER_EMULATOR_HOST environment
variable and use the regular spanner.NewClient:
	srv, err := spannertest.NewServer("localhost:0")
	...
	os.Setenv("SPANNER_EMULATOR_HOST", srv.Addr)
	client, err := spanner.NewClient(ctx, db)
	...

The same server also supports database admin operations for use with
the cloud.google.com/go/spanner/admin/database/apiv1 package.
*/
package spannertest

import (
	"context"
	"encoding/base64"
	"fmt"
	"log"
	"math/rand"
	"net"
	"strconv"
	"sync"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	anypb "github.com/golang/protobuf/ptypes/any"
	emptypb "github.com/golang/protobuf/ptypes/empty"
	structpb "github.com/golang/protobuf/ptypes/struct"
	timestamppb "github.com/golang/protobuf/ptypes/timestamp"
	lropb "google.golang.org/genproto/googleapis/longrunning"
	adminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1"
	spannerpb "google.golang.org/genproto/googleapis/spanner/v1"

	"cloud.google.com/go/spanner/spansql"
)

// Server is an in-memory Cloud Spanner fake.
// It is unauthenticated, non-performant, and only a rough approximation.
type Server struct {
	Addr string

	l   net.Listener
	srv *grpc.Server
	s   *server
}

// server is the real implementation of the fake.
// It is a separate and unexported type so the API won't be cluttered with
// methods that are only relevant to the fake's implementation.
type server struct {
	logf Logger

	db database

	mu       sync.Mutex
	sessions map[string]*session
	lros     map[string]*lro

	// Any unimplemented methods will cause a panic.
	// TODO: Switch to Unimplemented at some point? spannerpb would need regenerating.
	adminpb.DatabaseAdminServer
	spannerpb.SpannerServer
	lropb.OperationsServer
}

type session struct {
	name     string
	creation time.Time

	// This context tracks the lifetime of this session.
	// It is canceled in DeleteSession.
	ctx    context.Context
	cancel func()

	mu           sync.Mutex
	lastUse      time.Time
	transactions map[string]*transaction
}

func (s *session) Proto() *spannerpb.Session {
	s.mu.Lock()
	defer s.mu.Unlock()
	m := &spannerpb.Session{
		Name:                   s.name,
		CreateTime:             timestampProto(s.creation),
		ApproximateLastUseTime: timestampProto(s.lastUse),
	}
	return m
}

// timestampProto returns a valid timestamp.Timestamp,
// or nil if the given time is zero or isn't representable.
func timestampProto(t time.Time) *timestamppb.Timestamp {
	if t.IsZero() {
		return nil
	}
	ts, err := ptypes.TimestampProto(t)
	if err != nil {
		return nil
	}
	return ts
}

type transaction struct {
	// TODO: connect this with db.go.
}

func (t *transaction) Commit() error {
	return nil
}

func (t *transaction) Rollback() error {
	return nil
}

func (t *transaction) finish() {
}

// lro represents a Long-Running Operation, generally a schema change.
type lro struct {
	mu    sync.Mutex
	state *lropb.Operation
}

func (l *lro) State() *lropb.Operation {
	l.mu.Lock()
	defer l.mu.Unlock()
	return proto.Clone(l.state).(*lropb.Operation)
}

// Logger is something that can be used for logging.
// It is matched by log.Printf and testing.T.Logf.
type Logger func(format string, args ...interface{})

// NewServer creates a new Server.
// The Server will be listening for gRPC connections, without TLS, on the provided TCP address.
// The resolved address is available in the Addr field.
func NewServer(laddr string) (*Server, error) {
	l, err := net.Listen("tcp", laddr)
	if err != nil {
		return nil, err
	}

	s := &Server{
		Addr: l.Addr().String(),
		l:    l,
		srv:  grpc.NewServer(),
		s: &server{
			logf: func(format string, args ...interface{}) {
				log.Printf("spannertest.inmem: "+format, args...)
			},
			sessions: make(map[string]*session),
			lros:     make(map[string]*lro),
		},
	}
	adminpb.RegisterDatabaseAdminServer(s.srv, s.s)
	spannerpb.RegisterSpannerServer(s.srv, s.s)
	lropb.RegisterOperationsServer(s.srv, s.s)

	go s.srv.Serve(s.l)

	return s, nil
}

// SetLogger sets a logger for the server.
// You can use a *testing.T as this argument to collate extra information
// from the execution of the server.
func (s *Server) SetLogger(l Logger) { s.s.logf = l }

// Close shuts down the server.
func (s *Server) Close() {
	s.srv.Stop()
	s.l.Close()
}

func genRandomSession() string {
	var b [4]byte
	rand.Read(b[:])
	return fmt.Sprintf("%x", b)
}

func genRandomTransaction() string {
	var b [6]byte
	rand.Read(b[:])
	return fmt.Sprintf("tx-%x", b)
}

func genRandomOperation() string {
	var b [3]byte
	rand.Read(b[:])
	return fmt.Sprintf("op-%x", b)
}

func (s *server) GetOperation(ctx context.Context, req *lropb.GetOperationRequest) (*lropb.Operation, error) {
	s.mu.Lock()
	lro, ok := s.lros[req.Name]
	s.mu.Unlock()
	if !ok {
		return nil, status.Errorf(codes.NotFound, "unknown LRO %q", req.Name)
	}
	return lro.State(), nil
}

// UpdateDDL applies the given DDL to the server.
//
// This is a convenience method for tests that may assume an existing schema.
// The more general approach is to dial this server using an admin client, and
// use the UpdateDatabaseDdl RPC method.
func (s *Server) UpdateDDL(ddl spansql.DDL) error {
	ctx := context.Background()
	for _, stmt := range ddl.List {
		if st := s.s.runOneDDL(ctx, stmt); st.Code() != codes.OK {
			return st.Err()
		}
	}
	return nil
}

func (s *server) UpdateDatabaseDdl(ctx context.Context, req *adminpb.UpdateDatabaseDdlRequest) (*lropb.Operation, error) {
	// Parse all the DDL statements first.
	var stmts []spansql.DDLStmt
	for _, s := range req.Statements {
		stmt, err := spansql.ParseDDLStmt(s)
		if err != nil {
			// TODO: check what code the real Spanner returns here.
			return nil, status.Errorf(codes.InvalidArgument, "bad DDL statement %q: %v", s, err)
		}
		stmts = append(stmts, stmt)
	}

	// Nothing should be depending on the exact structure of this,
	// but it is specified in google/spanner/admin/database/v1/spanner_database_admin.proto.
	id := "projects/fake-proj/instances/fake-instance/databases/fake-db/operations/" + genRandomOperation()
	lro := &lro{
		state: &lropb.Operation{
			Name: id,
		},
	}
	s.mu.Lock()
	s.lros[id] = lro
	s.mu.Unlock()

	go lro.Run(s, stmts)
	return lro.State(), nil
}

func (l *lro) Run(s *server, stmts []spansql.DDLStmt) {
	ctx := context.Background()

	for _, stmt := range stmts {
		time.Sleep(100 * time.Millisecond)
		if st := s.runOneDDL(ctx, stmt); st.Code() != codes.OK {
			l.mu.Lock()
			l.state.Done = true
			l.state.Result = &lropb.Operation_Error{st.Proto()}
			l.mu.Unlock()
			return
		}
	}

	l.mu.Lock()
	l.state.Done = true
	l.state.Result = &lropb.Operation_Response{&anypb.Any{}}
	l.mu.Unlock()
}

func (s *server) runOneDDL(ctx context.Context, stmt spansql.DDLStmt) *status.Status {
	return s.db.ApplyDDL(stmt)
}

func (s *server) CreateSession(ctx context.Context, req *spannerpb.CreateSessionRequest) (*spannerpb.Session, error) {
	s.logf("CreateSession(%q)", req.Database)

	id := genRandomSession()
	now := time.Now()
	sess := &session{
		name:         id,
		creation:     now,
		lastUse:      now,
		transactions: make(map[string]*transaction),
	}
	sess.ctx, sess.cancel = context.WithCancel(context.Background())

	s.mu.Lock()
	s.sessions[id] = sess
	s.mu.Unlock()

	return sess.Proto(), nil
}

func (s *server) GetSession(ctx context.Context, req *spannerpb.GetSessionRequest) (*spannerpb.Session, error) {
	s.mu.Lock()
	sess, ok := s.sessions[req.Name]
	s.mu.Unlock()

	if !ok {
		// TODO: what error does the real Spanner return?
		return nil, status.Errorf(codes.NotFound, "unknown session %q", req.Name)
	}

	return sess.Proto(), nil
}

// TODO: ListSessions

func (s *server) DeleteSession(ctx context.Context, req *spannerpb.DeleteSessionRequest) (*emptypb.Empty, error) {
	s.logf("DeleteSession(%q)", req.Name)

	s.mu.Lock()
	sess, ok := s.sessions[req.Name]
	delete(s.sessions, req.Name)
	s.mu.Unlock()

	if !ok {
		// TODO: what error does the real Spanner return?
		return nil, status.Errorf(codes.NotFound, "unknown session %q", req.Name)
	}

	// Terminate any operations in this session.
	sess.cancel()

	return &emptypb.Empty{}, nil
}

// popTx returns an existing transaction, removing it from the session.
// This is called when a transaction is finishing (Commit, Rollback).
func (s *server) popTx(sessionID, tid string) (tx *transaction, cleanup func(), err error) {
	s.mu.Lock()
	sess, ok := s.sessions[sessionID]
	s.mu.Unlock()
	if !ok {
		// TODO: what error does the real Spanner return?
		return nil, nil, status.Errorf(codes.NotFound, "unknown session %q", sessionID)
	}

	sess.mu.Lock()
	sess.lastUse = time.Now()
	tx, ok = sess.transactions[tid]
	if ok {
		delete(sess.transactions, tid)
	}
	sess.mu.Unlock()
	if !ok {
		// TODO: what error does the real Spanner return?
		return nil, nil, status.Errorf(codes.NotFound, "unknown transaction ID %q", tid)
	}
	return tx, tx.finish, nil
}

// readTx returns a transaction for the given session and transaction selector.
// It is used by read/query operations (ExecuteStreamingSql, StreamingRead).
func (s *server) readTx(ctx context.Context, session string, tsel *spannerpb.TransactionSelector) (tx *transaction, cleanup func(), err error) {
	s.mu.Lock()
	sess, ok := s.sessions[session]
	s.mu.Unlock()
	if !ok {
		// TODO: what error does the real Spanner return?
		return nil, nil, status.Errorf(codes.NotFound, "unknown session %q", session)
	}

	sess.mu.Lock()
	sess.lastUse = time.Now()
	sess.mu.Unlock()

	singleUse := func() (*transaction, func(), error) {
		tx := &transaction{}
		return tx, tx.finish, nil
	}
	singleUseReadOnly := func() (*transaction, func(), error) {
		// TODO: figure out a way to make this read-only.
		return singleUse()
	}

	if tsel.GetSelector() == nil {
		return singleUseReadOnly()
	}

	switch sel := tsel.Selector.(type) {
	default:
		return nil, nil, fmt.Errorf("TransactionSelector type %T not supported", sel)
	case *spannerpb.TransactionSelector_SingleUse:
		// Ignore options (e.g. timestamps).
		switch mode := sel.SingleUse.Mode.(type) {
		case *spannerpb.TransactionOptions_ReadOnly_:
			return singleUseReadOnly()
		case *spannerpb.TransactionOptions_ReadWrite_:
			return singleUse()
		default:
			return nil, nil, fmt.Errorf("single use transaction in mode %T not supported", mode)
		}
	case *spannerpb.TransactionSelector_Id:
		id := sel.Id // []byte
		_ = id       // TODO: lookup an existing transaction by ID.
		tx := &transaction{}
		return tx, tx.finish, nil
	}
}

func (s *server) ExecuteSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest) (*spannerpb.ResultSet, error) {
	return nil, status.Errorf(codes.Unimplemented, "ExecuteSql not implemented yet")
}

func (s *server) ExecuteStreamingSql(req *spannerpb.ExecuteSqlRequest, stream spannerpb.Spanner_ExecuteStreamingSqlServer) error {
	tx, cleanup, err := s.readTx(stream.Context(), req.Session, req.Transaction)
	if err != nil {
		return err
	}
	defer cleanup()

	q, err := spansql.ParseQuery(req.Sql)
	if err != nil {
		// TODO: check what code the real Spanner returns here.
		return status.Errorf(codes.InvalidArgument, "bad query: %v", err)
	}

	params := make(queryParams)
	for k, v := range req.GetParams().GetFields() {
		switch v := v.Kind.(type) {
		default:
			return fmt.Errorf("unsupported well-known type value kind %T", v)
		case *structpb.Value_NullValue:
			params[k] = nil
		case *structpb.Value_NumberValue:
			params[k] = v.NumberValue
		case *structpb.Value_StringValue:
			params[k] = v.StringValue
		}

	}

	s.logf("Querying: %s", q.SQL())
	if len(params) > 0 {
		s.logf("        ▹ %v", params)
	}

	ri, err := s.db.Query(q, params)
	if err != nil {
		return err
	}
	return s.readStream(stream.Context(), tx, stream.Send, ri)
}

// TODO: Read

func (s *server) StreamingRead(req *spannerpb.ReadRequest, stream spannerpb.Spanner_StreamingReadServer) error {
	tx, cleanup, err := s.readTx(stream.Context(), req.Session, req.Transaction)
	if err != nil {
		return err
	}
	defer cleanup()

	// Bail out if various advanced features are being used.
	if req.Index != "" {
		return fmt.Errorf("index reads (%q) not supported", req.Index)
	}
	if len(req.ResumeToken) > 0 {
		// This should only happen if we send resume_token ourselves.
		return fmt.Errorf("read resumption not supported")
	}
	if len(req.PartitionToken) > 0 {
		return fmt.Errorf("partition restrictions not supported")
	}

	// TODO: other KeySet types.
	if len(req.KeySet.Ranges) > 0 {
		return fmt.Errorf("reading with ranges not supported")
	}

	var ri *resultIter
	if req.KeySet.All {
		s.logf("Reading all from %s (cols: %v)", req.Table, req.Columns)
		ri, err = s.db.ReadAll(req.Table, req.Columns, req.Limit)
	} else {
		s.logf("Reading %d rows from from %s (cols: %v)", len(req.KeySet.Keys), req.Table, req.Columns)
		ri, err = s.db.Read(req.Table, req.Columns, req.KeySet.Keys, req.Limit)
	}
	if err != nil {
		return err
	}

	// TODO: Figure out the right contexts to use here. There's the session one (sess.ctx),
	// but also this specific RPC one (stream.Context()). Which takes precedence?
	// They appear to be independent.

	return s.readStream(stream.Context(), tx, stream.Send, ri)
}

func (s *server) readStream(ctx context.Context, tx *transaction, send func(*spannerpb.PartialResultSet) error, ri *resultIter) error {
	// Build the result set metadata.
	rsm := &spannerpb.ResultSetMetadata{
		RowType: &spannerpb.StructType{},
		// TODO: transaction info?
	}
	for _, ci := range ri.Cols {
		st, err := spannerTypeFromType(ci.Type)
		if err != nil {
			return err
		}
		rsm.RowType.Fields = append(rsm.RowType.Fields, &spannerpb.StructType_Field{
			Name: ci.Name,
			Type: st,
		})
	}

	for {
		row, ok := ri.Next()
		if !ok {
			break
		}

		values := make([]*structpb.Value, len(row))
		for i, x := range row {
			v, err := spannerValueFromValue(x)
			if err != nil {
				return err
			}
			values[i] = v
		}

		prs := &spannerpb.PartialResultSet{
			Metadata: rsm,
			Values:   values,
		}
		if err := send(prs); err != nil {
			return err
		}

		// ResultSetMetadata is only set for the first PartialResultSet.
		rsm = nil
	}

	return nil
}

func (s *server) BeginTransaction(ctx context.Context, req *spannerpb.BeginTransactionRequest) (*spannerpb.Transaction, error) {
	//s.logf("BeginTransaction(%v)", req)

	s.mu.Lock()
	sess, ok := s.sessions[req.Session]
	s.mu.Unlock()
	if !ok {
		// TODO: what error does the real Spanner return?
		return nil, status.Errorf(codes.NotFound, "unknown session %q", req.Session)
	}

	id := genRandomTransaction()
	tx := &transaction{}

	sess.mu.Lock()
	sess.lastUse = time.Now()
	sess.transactions[id] = tx
	sess.mu.Unlock()

	return &spannerpb.Transaction{Id: []byte(id)}, nil
}

func (s *server) Commit(ctx context.Context, req *spannerpb.CommitRequest) (*spannerpb.CommitResponse, error) {
	//s.logf("Commit(%q, %q)", req.Session, req.Transaction)

	obj, ok := req.Transaction.(*spannerpb.CommitRequest_TransactionId)
	if !ok {
		return nil, fmt.Errorf("unsupported transaction type %T", req.Transaction)
	}
	tid := string(obj.TransactionId)

	tx, cleanup, err := s.popTx(req.Session, tid)
	if err != nil {
		return nil, err
	}
	defer cleanup()

	for _, m := range req.Mutations {
		switch op := m.Operation.(type) {
		default:
			return nil, fmt.Errorf("unsupported mutation operation type %T", op)
		case *spannerpb.Mutation_Insert:
			ins := op.Insert
			err := s.db.Insert(ins.Table, ins.Columns, ins.Values)
			if err != nil {
				return nil, err
			}
		case *spannerpb.Mutation_Update:
			up := op.Update
			err := s.db.Update(up.Table, up.Columns, up.Values)
			if err != nil {
				return nil, err
			}
		case *spannerpb.Mutation_InsertOrUpdate:
			iou := op.InsertOrUpdate
			err := s.db.InsertOrUpdate(iou.Table, iou.Columns, iou.Values)
			if err != nil {
				return nil, err
			}
		case *spannerpb.Mutation_Delete_:
			del := op.Delete
			ks := del.KeySet

			err := s.db.Delete(del.Table, ks.Keys, makeKeyRangeList(ks.Ranges), ks.All)
			if err != nil {
				return nil, err
			}
		}

	}

	if err := tx.Commit(); err != nil {
		return nil, err
	}

	// TODO: return timestamp?
	return &spannerpb.CommitResponse{}, nil
}

func (s *server) Rollback(ctx context.Context, req *spannerpb.RollbackRequest) (*emptypb.Empty, error) {
	s.logf("Rollback(%v)", req)

	tx, cleanup, err := s.popTx(req.Session, string(req.TransactionId))
	if err != nil {
		return nil, err
	}
	defer cleanup()

	if err := tx.Rollback(); err != nil {
		return nil, err
	}

	return &emptypb.Empty{}, nil
}

// TODO: PartitionQuery, PartitionRead

func spannerTypeFromType(typ spansql.Type) (*spannerpb.Type, error) {
	var code spannerpb.TypeCode
	switch typ.Base {
	default:
		return nil, fmt.Errorf("unhandled base type %d", typ.Base)
	case spansql.Bool:
		code = spannerpb.TypeCode_BOOL
	case spansql.Int64:
		code = spannerpb.TypeCode_INT64
	case spansql.Float64:
		code = spannerpb.TypeCode_FLOAT64
	case spansql.String:
		code = spannerpb.TypeCode_STRING
	case spansql.Bytes:
		code = spannerpb.TypeCode_BYTES
	case spansql.Date:
		code = spannerpb.TypeCode_DATE
	}
	st := &spannerpb.Type{Code: code}
	if typ.Array {
		st = &spannerpb.Type{
			Code:             spannerpb.TypeCode_ARRAY,
			ArrayElementType: st,
		}
	}
	return st, nil
}

func spannerValueFromValue(x interface{}) (*structpb.Value, error) {
	switch x := x.(type) {
	default:
		return nil, fmt.Errorf("unhandled database value type %T", x)
	case bool:
		return &structpb.Value{Kind: &structpb.Value_BoolValue{x}}, nil
	case int64:
		// The Spanner int64 is actually a decimal string.
		s := strconv.FormatInt(x, 10)
		return &structpb.Value{Kind: &structpb.Value_StringValue{s}}, nil
	case float64:
		return &structpb.Value{Kind: &structpb.Value_NumberValue{x}}, nil
	case string:
		return &structpb.Value{Kind: &structpb.Value_StringValue{x}}, nil
	case []byte:
		return &structpb.Value{Kind: &structpb.Value_StringValue{base64.StdEncoding.EncodeToString(x)}}, nil
	case nil:
		return &structpb.Value{Kind: &structpb.Value_NullValue{}}, nil
	case []interface{}:
		var vs []*structpb.Value
		for _, elem := range x {
			v, err := spannerValueFromValue(elem)
			if err != nil {
				return nil, err
			}
			vs = append(vs, v)
		}
		return &structpb.Value{Kind: &structpb.Value_ListValue{
			&structpb.ListValue{Values: vs},
		}}, nil
	}
}

func makeKeyRangeList(ranges []*spannerpb.KeyRange) keyRangeList {
	var krl keyRangeList
	for _, r := range ranges {
		krl = append(krl, makeKeyRange(r))
	}
	return krl
}

func makeKeyRange(r *spannerpb.KeyRange) *keyRange {
	var kr keyRange
	switch s := r.StartKeyType.(type) {
	case *spannerpb.KeyRange_StartClosed:
		kr.start = s.StartClosed
		kr.startClosed = true
	case *spannerpb.KeyRange_StartOpen:
		kr.start = s.StartOpen
	}
	switch e := r.EndKeyType.(type) {
	case *spannerpb.KeyRange_EndClosed:
		kr.end = e.EndClosed
		kr.endClosed = true
	case *spannerpb.KeyRange_EndOpen:
		kr.end = e.EndOpen
	}
	return &kr
}


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>E stvarno super, vratili smo se na domaću hranu GRAH S KOBASICOM+LEPINJA.. Odlično! Sutra ćemo ponovo klopati grah!</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/meduza-catering-savica</Source>
</CrawlItem>


text:
namespace Quants.Units
{
    /// <summary>
    /// Class that enables creating combined units in a fluent manner.
    /// <example>
    /// <code>
    /// // kg*m/ (s*s).
    /// IUnit newton = new UnitCreator(kg).Multiply(m).Divide(s, s).Create().
    /// </code>
    /// </example>
    /// </summary>
    public class UnitCreator
    {
        private CompoundUnit _unit;

        /// <summary>
        /// Initialize the creator with the unit given.
        /// </summary>
        /// <param name="baseUnit"></param>
        public UnitCreator(IUnit baseUnit)
        {
            UpdateUnit(baseUnit);
        }

        /// <summary>
        /// Initialize the creator to be dimensionless.
        /// </summary>
        public UnitCreator()
        {
            UpdateUnit(new CompoundUnit(Unitless.Instance));
        }

        /// <summary>
        /// Multiply the current unit with the units(s) given.
        /// </summary>
        /// <param name="units">One or more units.</param>
        public UnitCreator Multiply(params IUnit[] units)
        {
            UpdateUnit(_unit.Multiply(units));
            return this;
        }

        /// <summary>
        /// Divide the current unit with the unit(s) given.
        /// </summary>
        /// <param name="units">One or more units.</param>
        public UnitCreator Divide(params IUnit[] units)
        {
            UpdateUnit(_unit.Divide(units));
            return this;
        }

        /// <summary>
        /// Determine the resulting unit and return.
        /// </summary>
        /// <returns></returns>
        public IUnit Create()
        {
            return _unit.Multiply(Unitless.Instance);
        }

        private void UpdateUnit(IUnit unit)
        {
            if (unit is CompoundUnit)
            {
                _unit = (CompoundUnit) unit;
            }
            else
            {
                _unit = new CompoundUnit(unit);
            }
        }
    }
}


text:
package com.themodernway.server.core.security;

import java.io.Closeable;

public interface IAuthorizationProvider extends IAuthorizer, Closeable
{
}


text:
cd /opt
sudo yum install -y git gcc libffi-devel python-devel openssl-devel gmp-devel libxml2-devel libxslt-devel postgresql-devel
sudo git clone https://git.openstack.org/openstack/rally
sudo chown -R vagrant:vagrant rally
sudo ./rally/install_rally.sh
sudo chown -R vagrant:vagrant /etc/rally /var/lib/rally
rally-manage db recreate
source /home/vagrant/openrc
rally deployment create --fromenv --name=packstack
rally deployment check

cat <<EOT | sudo tee /etc/httpd/conf.d/rally.conf
Alias /rally "/opt/rally"
<Directory "/opt/rally">
  Options +Indexes
  AllowOverride None
  Require all granted
</Directory>
EOT

sudo sed -i "s#</VirtualHost>#  Include /etc/httpd/conf.d/rally.conf\n</VirtualHost>#" /etc/httpd/conf.d/15-horizon_vhost.conf
sudo systemctl restart httpd


text:
package org.jivesoftware.smackx.pep;

import org.jivesoftware.smack.packet.Message;

import org.jivesoftware.smackx.pubsub.EventElement;

import org.jxmpp.jid.EntityBareJid;

/**
 *
 * A listener that is fired anytime a PEP event message is received.
 *
 * @author Jeff Williams
 * @author Florian Schmaus
 */
public interface PepListener {

    /**
     * Called when PEP events are received as part of a presence subscribe or message filter.
     *
     * @param from the user that sent the entries.
     * @param event the event contained in the message.
     * @param message the message stanza containing the PEP event.
     */
    void eventReceived(EntityBareJid from, EventElement event, Message message);

}


text:
// Copyright (c) 2014, 2015 Adobe Systems Incorporated. All rights reserved.
//
// 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.

/* Help write the SVG */

(function () {
    "use strict";

    var svgWriterUtils = require("./svgWriterUtils.js"),
        svgWriterGradient = require("./svgWriterGradient.js"),
        svgWriterPattern = require("./svgWriterPattern.js"),
        writeGradient = svgWriterGradient.writeGradient,
        writePattern = svgWriterPattern.writePattern;

    module.exports = {
        externalizeStyles: function (ctx) {
            var omIn = ctx.currentOMNode,
                fill,
                styleBlock = ctx.omStylesheet.getStyleBlock(omIn);

            if (!omIn.style || !omIn.style.fill) {
                if (omIn.type == "shape" || "from" in omIn && "to" in omIn) {
                    styleBlock.addRule("fill", "none");
                }
                return;
            }
            fill = omIn.style.fill;

            if (fill.type === "gradient") {
                writeGradient(ctx, styleBlock, fill.gradient, "fill");
            } else if (fill.type == "pattern") {
                writePattern(ctx, fill.pattern, "fill");
            } else if (fill.type == "none") {
                styleBlock.addRule("fill", "none");
            } else {
                styleBlock.addRule("fill", svgWriterUtils.writeColor(fill.color, ctx));
            }

            if (isFinite(omIn.style.fill.opacity)) {
                styleBlock.addRule("fill-opacity", omIn.style.fill.opacity);
            }
        }
    };
}());


text:
namespace Bull
{
    enum DateMonth
    {
        DateMonth_January = 1,
        DateMonth_Febuary = 2,
        DateMonth_March = 3,
        DateMonth_April = 4,
        DateMonth_May = 5,
        DateMonth_June = 6,
        DateMonth_Juily = 7,
        DateMonth_August = 8,
        DateMonth_September = 9,
        DateMonth_October = 10,
        DateMonth_November = 11,
        DateMonth_December = 12
    };
}

#endif // BULL_CORE_TIME_DATEMONTH_HPP


text:
module Azure::DataMigration::Mgmt::V2018_04_19
  module Models
    #
    # OData page of quota objects
    #
    class QuotaList

      include MsRestAzure

      include MsRest::JSONable
      # @return [Array<Quota>] List of quotas
      attr_accessor :value

      # @return [String] URL to load the next page of quotas, or null or
      # missing if this is the last page
      attr_accessor :next_link

      # return [Proc] with next page method call.
      attr_accessor :next_method

      #
      # Gets the rest of the items for the request, enabling auto-pagination.
      #
      # @return [Array<Quota>] operation results.
      #
      def get_all_items
        items = @value
        page = self
        while page.next_link != nil && !page.next_link.strip.empty? do
          page = page.get_next_page
          items.concat(page.value)
        end
        items
      end

      #
      # Gets the next page of results.
      #
      # @return [QuotaList] with next page content.
      #
      def get_next_page
        response = @next_method.call(@next_link).value! unless @next_method.nil?
        unless response.nil?
          @next_link = response.body.next_link
          @value = response.body.value
          self
        end
      end

      #
      # Mapper for QuotaList class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'QuotaList',
          type: {
            name: 'Composite',
            class_name: 'QuotaList',
            model_properties: {
              value: {
                client_side_validation: true,
                required: false,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'QuotaElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'Quota'
                      }
                  }
                }
              },
              next_link: {
                client_side_validation: true,
                required: false,
                serialized_name: 'nextLink',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
import * as utils from '../src/utils';
import { parse as parseUrl } from '../src/url';
import { config } from '../src/config';
import { registerBidder } from '../src/adapters/bidderFactory';
import { Renderer } from '../src/Renderer';
import { VIDEO, BANNER } from '../src/mediaTypes';
import find from 'core-js/library/fn/array/find';
import includes from 'core-js/library/fn/array/includes';

const ADAPTER_VERSION = '1.5';
const ADAPTER_NAME = 'BFIO_PREBID';
const OUTSTREAM = 'outstream';

export const VIDEO_ENDPOINT = '//reachms.bfmio.com/bid.json?exchange_id=';
export const BANNER_ENDPOINT = '//display.bfmio.com/prebid_display';
export const OUTSTREAM_SRC = '//player-cdn.beachfrontmedia.com/playerapi/loader/outstream.js';

export const VIDEO_TARGETING = ['mimes', 'playbackmethod', 'maxduration'];
export const DEFAULT_MIMES = ['video/mp4', 'application/javascript'];

let appId = '';

export const spec = {
  code: 'beachfront',
  supportedMediaTypes: [ VIDEO, BANNER ],

  isBidRequestValid(bid) {
    return !!(isVideoBidValid(bid) || isBannerBidValid(bid));
  },

  buildRequests(bids, bidderRequest) {
    let requests = [];
    let videoBids = bids.filter(bid => isVideoBidValid(bid));
    let bannerBids = bids.filter(bid => isBannerBidValid(bid));
    videoBids.forEach(bid => {
      appId = getVideoBidParam(bid, 'appId');
      requests.push({
        method: 'POST',
        url: VIDEO_ENDPOINT + appId,
        data: createVideoRequestData(bid, bidderRequest),
        bidRequest: bid
      });
    });
    if (bannerBids.length) {
      appId = getBannerBidParam(bannerBids[0], 'appId');
      requests.push({
        method: 'POST',
        url: BANNER_ENDPOINT,
        data: createBannerRequestData(bannerBids, bidderRequest),
        bidRequest: bannerBids
      });
    }
    return requests;
  },

  interpretResponse(response, { bidRequest }) {
    response = response.body;

    if (isVideoBid(bidRequest)) {
      if (!response || !response.url || !response.bidPrice) {
        utils.logWarn(`No valid video bids from ${spec.code} bidder`);
        return [];
      }
      let sizes = getVideoSizes(bidRequest);
      let firstSize = getFirstSize(sizes);
      let context = utils.deepAccess(bidRequest, 'mediaTypes.video.context');
      return {
        requestId: bidRequest.bidId,
        bidderCode: spec.code,
        vastUrl: response.url,
        cpm: response.bidPrice,
        width: firstSize.w,
        height: firstSize.h,
        creativeId: response.cmpId,
        renderer: context === OUTSTREAM ? createRenderer(bidRequest) : null,
        mediaType: VIDEO,
        currency: 'USD',
        netRevenue: true,
        ttl: 300
      };
    } else {
      if (!response || !response.length) {
        utils.logWarn(`No valid banner bids from ${spec.code} bidder`);
        return [];
      }
      return response
        .filter(bid => bid.adm)
        .map((bid) => {
          let request = find(bidRequest, req => req.adUnitCode === bid.slot);
          return {
            requestId: request.bidId,
            bidderCode: spec.code,
            ad: bid.adm,
            creativeId: bid.crid,
            cpm: bid.price,
            width: bid.w,
            height: bid.h,
            mediaType: BANNER,
            currency: 'USD',
            netRevenue: true,
            ttl: 300
          };
        });
    }
  },

  getUserSyncs(syncOptions, serverResponses = [], gdprConsent = {}) {
    let syncs = [];
    let { gdprApplies, consentString } = gdprConsent;
    let bannerResponse = find(serverResponses, (res) => utils.isArray(res.body));

    if (bannerResponse) {
      if (syncOptions.iframeEnabled) {
        bannerResponse.body
          .filter(bid => bid.sync)
          .forEach(bid => {
            syncs.push({
              type: 'iframe',
              url: bid.sync
            });
          });
      }
    } else if (syncOptions.iframeEnabled) {
      syncs.push({
        type: 'iframe',
        url: `//sync.bfmio.com/sync_iframe?ifg=1&id=${appId}&gdpr=${gdprApplies ? 1 : 0}&gc=${consentString || ''}&gce=1`
      });
    } else if (syncOptions.pixelEnabled) {
      syncs.push({
        type: 'image',
        url: `//sync.bfmio.com/syncb?pid=144&id=${appId}&gdpr=${gdprApplies ? 1 : 0}&gc=${consentString || ''}&gce=1`
      });
    }

    return syncs;
  }
};

function createRenderer(bidRequest) {
  const renderer = Renderer.install({
    id: bidRequest.bidId,
    url: OUTSTREAM_SRC,
    loaded: false
  });

  renderer.setRender(bid => {
    bid.renderer.push(() => {
      window.Beachfront.Player(bid.adUnitCode, {
        adTagUrl: bid.vastUrl,
        width: bid.width,
        height: bid.height,
        expandInView: getPlayerBidParam(bidRequest, 'expandInView', false),
        collapseOnComplete: getPlayerBidParam(bidRequest, 'collapseOnComplete', true),
        progressColor: getPlayerBidParam(bidRequest, 'progressColor')
      });
    });
  });

  return renderer;
}

function getFirstSize(sizes) {
  return (sizes && sizes.length) ? sizes[0] : { w: undefined, h: undefined };
}

function parseSizes(sizes) {
  return utils.parseSizesInput(sizes).map(size => {
    let [ width, height ] = size.split('x');
    return {
      w: parseInt(width, 10) || undefined,
      h: parseInt(height, 10) || undefined
    };
  });
}

function getVideoSizes(bid) {
  return parseSizes(utils.deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes);
}

function getBannerSizes(bid) {
  return parseSizes(utils.deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes);
}

function getOsVersion() {
  let clientStrings = [
    { s: 'Android', r: /Android/ },
    { s: 'iOS', r: /(iPhone|iPad|iPod)/ },
    { s: 'Mac OS X', r: /Mac OS X/ },
    { s: 'Mac OS', r: /(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/ },
    { s: 'Linux', r: /(Linux|X11)/ },
    { s: 'Windows 10', r: /(Windows 10.0|Windows NT 10.0)/ },
    { s: 'Windows 8.1', r: /(Windows 8.1|Windows NT 6.3)/ },
    { s: 'Windows 8', r: /(Windows 8|Windows NT 6.2)/ },
    { s: 'Windows 7', r: /(Windows 7|Windows NT 6.1)/ },
    { s: 'Windows Vista', r: /Windows NT 6.0/ },
    { s: 'Windows Server 2003', r: /Windows NT 5.2/ },
    { s: 'Windows XP', r: /(Windows NT 5.1|Windows XP)/ },
    { s: 'UNIX', r: /UNIX/ },
    { s: 'Search Bot', r: /(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/ }
  ];
  let cs = find(clientStrings, cs => cs.r.test(navigator.userAgent));
  return cs ? cs.s : 'unknown';
}

function isMobile() {
  return (/(ios|ipod|ipad|iphone|android)/i).test(navigator.userAgent);
}

function isConnectedTV() {
  return (/(smart[-]?tv|hbbtv|appletv|googletv|hdmi|netcast\.tv|viera|nettv|roku|\bdtv\b|sonydtv|inettvbrowser|\btv\b)/i).test(navigator.userAgent);
}

function getDoNotTrack() {
  return navigator.doNotTrack === '1' || window.doNotTrack === '1' || navigator.msDoNoTrack === '1' || navigator.doNotTrack === 'yes';
}

function isVideoBid(bid) {
  return utils.deepAccess(bid, 'mediaTypes.video');
}

function isBannerBid(bid) {
  return utils.deepAccess(bid, 'mediaTypes.banner') || !isVideoBid(bid);
}

function getVideoBidParam(bid, key) {
  return utils.deepAccess(bid, 'params.video.' + key) || utils.deepAccess(bid, 'params.' + key);
}

function getBannerBidParam(bid, key) {
  return utils.deepAccess(bid, 'params.banner.' + key) || utils.deepAccess(bid, 'params.' + key);
}

function getPlayerBidParam(bid, key, defaultValue) {
  let param = utils.deepAccess(bid, 'params.player.' + key);
  return param === undefined ? defaultValue : param;
}

function isVideoBidValid(bid) {
  return isVideoBid(bid) && getVideoBidParam(bid, 'appId') && getVideoBidParam(bid, 'bidfloor');
}

function isBannerBidValid(bid) {
  return isBannerBid(bid) && getBannerBidParam(bid, 'appId') && getBannerBidParam(bid, 'bidfloor');
}

function getTopWindowLocation(bidderRequest) {
  let url = bidderRequest && bidderRequest.refererInfo && bidderRequest.refererInfo.referer;
  return parseUrl(config.getConfig('pageUrl') || url, { decodeSearchAsString: true });
}

function getTopWindowReferrer() {
  try {
    return window.top.document.referrer;
  } catch (e) {
    return '';
  }
}

function getVideoTargetingParams(bid) {
  return Object.keys(Object(bid.params.video))
    .filter(param => includes(VIDEO_TARGETING, param))
    .reduce((obj, param) => {
      obj[ param ] = bid.params.video[ param ];
      return obj;
    }, {});
}

function createVideoRequestData(bid, bidderRequest) {
  let sizes = getVideoSizes(bid);
  let firstSize = getFirstSize(sizes);
  let video = getVideoTargetingParams(bid);
  let appId = getVideoBidParam(bid, 'appId');
  let bidfloor = getVideoBidParam(bid, 'bidfloor');
  let topLocation = getTopWindowLocation(bidderRequest);
  let payload = {
    isPrebid: true,
    appId: appId,
    domain: document.location.hostname,
    id: utils.getUniqueIdentifierStr(),
    imp: [{
      video: Object.assign({
        w: firstSize.w,
        h: firstSize.h,
        mimes: DEFAULT_MIMES
      }, video),
      bidfloor: bidfloor,
      secure: topLocation.protocol === 'https:' ? 1 : 0
    }],
    site: {
      page: topLocation.href,
      domain: topLocation.hostname
    },
    device: {
      ua: navigator.userAgent,
      language: navigator.language,
      devicetype: isMobile() ? 1 : isConnectedTV() ? 3 : 2,
      dnt: getDoNotTrack() ? 1 : 0,
      js: 1,
      geo: {}
    },
    regs: {
      ext: {}
    },
    user: {
      ext: {}
    },
    cur: ['USD']
  };

  if (bidderRequest && bidderRequest.gdprConsent) {
    let { gdprApplies, consentString } = bidderRequest.gdprConsent;
    payload.regs.ext.gdpr = gdprApplies ? 1 : 0;
    payload.user.ext.consent = consentString;
  }

  if (bid.userId && bid.userId.tdid) {
    payload.user.ext.eids = [{
      source: 'adserver.org',
      uids: [{
        id: bid.userId.tdid,
        ext: {
          rtiPartner: 'TDID'
        }
      }]
    }];
  }

  return payload;
}

function createBannerRequestData(bids, bidderRequest) {
  let topLocation = getTopWindowLocation(bidderRequest);
  let topReferrer = getTopWindowReferrer();
  let slots = bids.map(bid => {
    return {
      slot: bid.adUnitCode,
      id: getBannerBidParam(bid, 'appId'),
      bidfloor: getBannerBidParam(bid, 'bidfloor'),
      sizes: getBannerSizes(bid)
    };
  });
  let payload = {
    slots: slots,
    page: topLocation.href,
    domain: topLocation.hostname,
    search: topLocation.search,
    secure: topLocation.protocol.indexOf('https') === 0 ? 1 : 0,
    referrer: topReferrer,
    ua: navigator.userAgent,
    deviceOs: getOsVersion(),
    isMobile: isMobile() ? 1 : 0,
    dnt: getDoNotTrack() ? 1 : 0,
    adapterVersion: ADAPTER_VERSION,
    adapterName: ADAPTER_NAME
  };

  if (bidderRequest && bidderRequest.gdprConsent) {
    let { gdprApplies, consentString } = bidderRequest.gdprConsent;
    payload.gdpr = gdprApplies ? 1 : 0;
    payload.gdprConsent = consentString;
  }

  if (bids[0] && bids[0].userId && bids[0].userId.tdid) {
    payload.tdid = bids[0].userId.tdid;
  }

  return payload;
}

registerBidder(spec);


text:
title: Bookshelf Project, Week Seventeen(ish)*
date: 2017-04-27 00:00:00 Z
layout: post
---

## Dickens-Fforde

**Books read:** 3

**Title:** _Oliver Twist_

**Author:** Charles Dickens

**Status:** This book has been on my shelf since I was 10 or so, and I'm not convinced I've ever read it all the way through before now. For many a year, Oliver! was my absolute favorite musical. (It was the first one I saw in the West End) I think I appropriated the book from my mother with the intent to read it to compliment the musical, but didn't complete the task. ...There's a lot more to the story than you see in the musical, btw. I'm not a huge fan of Dickens' prose style (reading _A Tale of Two Cities_ was one of the most academically trying parts of high school), but I was surprised by the amount of sardonic asides about England's treatment of the poor.

**Result:** I'm sending this one back to my mom, since I originally stole it from her.

---
**Title:** _Star Trek: Voyage to Adventure_

**Author:** Michael J. Dodge

**Status:** A knock off 'Choose Your Own Adventure' book set in the world of the original Star Trek. You are a new ensign assigned to the USS Enterprise who immediately gets to hang out with Kirk, Spock and co.. Whether you are sucked in to the icy vacuum of space or shot by Klingons or sent to the Mirror Universe all depends on the choices you make. It's good fun, but each of the stories I created were all extremely short, and it was pretty easy to determine which choice is going to killed and which will get a chuckle with one of the senior staff.

**Result:** This book was given to me many years ago by my best friend at the time, but I think it will be better of moving on to another generation of Trekkie.

---
**Title:** _The Eyre Affair_

**Author:** Jasper Fforde

**Status:** This book consistently places on my favorites list. When I first read it, it was unlike anything else I had read. I'm not even sure of how to describe it. Manic and zany and very, very clever. There is satire on modern England, literary criticism (and loads of literary jokes), a bit of time travel, vampire slaying and dodos. I've read it many times (and gone through a number of copies of the book because I keep loaning it out to people) and every time I get something new out of it.

**Result:** While I could certainly get it on my Kindle, I think it's important to keep a paper edition on my shelf.

---

* Apparently, I can't count and this is actually the seventeenth week of the year.


text:
{% load i18n %}

{% blocktrans with filter_title=title %}By {{ filter_title }}{% endblocktrans %}

    <form action="{{ choices.0.query_string|iriencode }}" method="get">
      <input type="text" name="{{ choices.0.field_path }}" value="{% if choices.0.value %}{{ choices.0.value }}{% endif %}">
    </form>


text:
const merge = require('webpack-merge');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const analyzeConfig = {
    plugins: [
        new BundleAnalyzerPlugin({
            analyzerHost: "0.0.0.0"
        })
    ]
};

const prodConfig = require('./webpack.prod.js');

module.exports = merge(prodConfig, analyzeConfig);