text:
package org.opencb.opencga.server.rest;

import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.junit.*;
import org.opencb.commons.datastore.mongodb.MongoDataStoreManager;
import org.opencb.opencga.core.models.user.User;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import java.io.IOException;

import static org.junit.Assert.assertEquals;

public class OpenCGAWSServerTest {

    public static final String TEST_SERVER_USER = "test_server_user";
    private static WSServerTestUtils serverTestUtils;
    private WebTarget webTarget;

    @BeforeClass
    static public void initServer() throws Exception {
        serverTestUtils = new WSServerTestUtils();
        serverTestUtils.setUp();
        serverTestUtils.initServer();
    }

    @AfterClass
    static public void shutdownServer() throws Exception {
        serverTestUtils.shutdownServer();
    }

    @Before
    public void init() throws Exception {

        //Drop default user mongoDB database.
        String databaseName = WSServerTestUtils.DATABASE_PREFIX + TEST_SERVER_USER + "_" + ProjectWSServerTest.PROJECT_ALIAS;
        MongoDataStoreManager dataStoreManager = new MongoDataStoreManager("localhost", 27017);
        dataStoreManager.get(databaseName);
        dataStoreManager.drop(databaseName);

//        serverTestUtils.setUp();
        webTarget = serverTestUtils.getWebTarget();

    }

    @After
    public void after() throws Exception {
        // It is here to avoid restarting the server again and again
        serverTestUtils.setUp();
    }

    /** First echo message to test Server connectivity **/
    @Test
    public void testConnectivity() throws InterruptedException, IOException {
        String message = "Test";
        WebTarget testPath = webTarget.path("test").path("echo").path(message);
        System.out.println("testPath = " + testPath);
        String s = testPath.request().get(String.class);
        assertEquals("Expected [" + message + "], actual [" + s + "]", message, s);

        testPath = webTarget.path("test").path("echo");
        System.out.println("testPath = " + testPath);
        MultiPart multiPart = new MultiPart();
        multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
        FormDataBodyPart bodyPart = new FormDataBodyPart("message", message);
        multiPart.bodyPart(bodyPart);

        s = testPath.request().post(Entity.entity(multiPart, multiPart.getMediaType()), String.class);
        assertEquals("Expected [" + message + "], actual [" + s + "]", message, s);
    }

    /** User tests **/
    @Test
    public void userTests() throws IOException {
        UserWSServerTest userTest = new UserWSServerTest(webTarget);
        User user = userTest.createUser(TEST_SERVER_USER);
        String sessionId = userTest.loginUser(user.getId());
        userTest.updateUser(user.getId(), sessionId);
    }

    @Test
    public void workflowCreation() throws Exception {
//        UserWSServerTest userTest = new UserWSServerTest(webTarget);
//        User user = userTest.createUser(TEST_SERVER_USER);
//        String sessionId = userTest.loginUser(user.getId());
//        user = userTest.info(user.getId(), sessionId);
//
//        ProjectWSServerTest prTest = new ProjectWSServerTest(webTarget);
//        Project project = prTest.createProject(user.getId(), sessionId);
//        prTest.modifyProject(project.getId(), sessionId);
//        project = prTest.info(project.getId(), sessionId);
//        userTest.getAllProjects(user.getId(), sessionId);
//
//        StudyWSServerTest stTest = new StudyWSServerTest(webTarget);
//        Study study = stTest.createStudy(project.getId(), sessionId);
//        stTest.modifyStudy(study.getId(), sessionId);
//        study = stTest.info(study.getId(), sessionId);
//        prTest.getAllStudies(project.getId(), sessionId);
//
//        FileWSServerTest fileTest = new FileWSServerTest();
//        fileTest.setWebTarget(webTarget);
//        File fileVcf = fileTest.uploadVcf(study.getId(), sessionId);
//        assertEquals(File.FileStatus.READY, fileVcf.getStatus().getName());
//        assertEquals(File.Bioformat.VARIANT, fileVcf.getBioformat());
//        Job indexJobVcf = fileTest.index(fileVcf.getId(), sessionId);
//
//        /* Emulate DAEMON working */
//        indexJobVcf = runStorageJob(sessionId, indexJobVcf);
//        assertEquals(Job.JobStatus.READY, indexJobVcf.getStatus().getName());
//
//        QueryOptions queryOptions = new QueryOptions(QueryOptions.LIMIT, 10);
//        queryOptions.put("region", "1");
//        List<Sample> samples = OpenCGAWSServer.catalogManager.getAllSamples(study.getId(),
//                new Query(CatalogSampleDBAdaptor.QueryParams.ID.key(), fileVcf.getSampleIds()), new QueryOptions(), sessionId).getResult();
//        List<String> sampleNames = samples.stream().map(Sample::getName).collect(Collectors.toList());
//        List<Variant> variants = fileTest.fetchVariants(fileVcf.getId(), sessionId, queryOptions);
//        assertEquals(10, variants.size());
//        for (Variant variant : variants) {
//            for (StudyEntry sourceEntry : variant.getStudies()) {
//                assertEquals(sampleNames.size(), sourceEntry.getSamplesData().size());
//                assertNotNull("Stats must be calculated", sourceEntry.stats(StudyEntry.DEFAULT_COHORT));
//            }
//            assertNotNull("Must be annotated", variant.getAnnotation());
//        }
//
//        //Create a new user with permissions just over 2 samples.
//        String userTest2 = OpenCGAWSServer.catalogManager.createUser("userTest2", "userTest2", "my@email.com", "1234", "ACME", null, new QueryOptions()).first().getId();
//        String sessionId2 = OpenCGAWSServer.catalogManager.login(userTest2, "1234", "127.0.0.1").first().getString("sessionId");
//        OpenCGAWSServer.catalogManager.addUsersToGroup(study.getId(), AuthorizationManager.MEMBERS_ROLE, userTest2, sessionId);
//
//        QueryResult<Sample> allSamples = OpenCGAWSServer.catalogManager.getAllSamples(study.getId(),
//                new Query(CatalogSampleDBAdaptor.QueryParams.NAME.key(), "NA19685,NA19661"), new QueryOptions(), sessionId);
//        OpenCGAWSServer.catalogManager.shareSample(allSamples.getResult().get(0).getId() + "", "@" + AuthorizationManager.MEMBERS_ROLE,
//                new AclEntry("@" + AuthorizationManager.MEMBERS_ROLE, true, false, false, false), sessionId);
//        OpenCGAWSServer.catalogManager.shareSample(allSamples.getResult().get(1).getId() + "", userTest2,
//                new AclEntry(userTest2, true, false, false, false), sessionId);
//
//        variants = stTest.fetchVariants(study.getId(), sessionId2, queryOptions);
//        assertEquals(10, variants.size());
//        for (Variant variant : variants) {
//            for (StudyEntry sourceEntry : variant.getStudies()) {
//                assertEquals(2, sourceEntry.getSamplesData().size());
//                assertNotNull("Stats must be calculated", sourceEntry.stats(StudyEntry.DEFAULT_COHORT));
//            }
//            assertNotNull("Must be annotated", variant.getAnnotation());
//        }
//
//
//        Cohort myCohort = OpenCGAWSServer.catalogManager.createCohort(study.getId(), "MyCohort", Study.Type.FAMILY, "", samples.stream().map(Sample::getId).collect(Collectors.toList()), null, sessionId).first();
//        assertEquals(Cohort.CohortStatus.NONE, OpenCGAWSServer.catalogManager.getCohort(myCohort.getId(), null, sessionId).first().getStatus().getName());
//
//        long outputId = OpenCGAWSServer.catalogManager.getFileParent(fileVcf.getId(), null, sessionId).first().getId();
//        Job calculateVariantStatsJob = fileTest.calculateVariantStats(myCohort.getId(), outputId, sessionId);
//
//        /* Emulate DAEMON working */
//        calculateVariantStatsJob = runStorageJob(sessionId, calculateVariantStatsJob);
//        assertEquals(Job.JobStatus.READY, calculateVariantStatsJob.getStatus().getName());
//        assertEquals(Cohort.CohortStatus.READY, OpenCGAWSServer.catalogManager.getCohort(myCohort.getId(), null, sessionId).first().getStatus().getName());
//
//
//
//        File fileBam = fileTest.uploadBam(study.getId(), sessionId);
//        assertEquals(File.FileStatus.READY, fileBam.getStatus().getName());
//        assertEquals(File.Bioformat.ALIGNMENT, fileBam.getBioformat());
//        Job indexJobBam = fileTest.index(fileBam.getId(), sessionId);
//
//        /* Emulate DAEMON working */
//        indexJobBam = runStorageJob(sessionId, indexJobBam);
//        assertEquals(Job.JobStatus.READY, indexJobBam.getStatus().getName());
//
//        queryOptions = new QueryOptions(QueryOptions.LIMIT, 10);
//        queryOptions.put("region", "20:60000-60200");
//        queryOptions.put(AlignmentDBAdaptor.QO_INCLUDE_COVERAGE, false);
//        fileTest.fetchAlignments(fileBam.getId(), sessionId, queryOptions);
//        assertEquals(10, alignments.size());

    }

}


text:
package org.apache.spark.sql.execution.ui

import javax.servlet.http.HttpServletRequest

import scala.collection.mutable
import scala.xml.{Node, NodeSeq}

import org.apache.commons.lang3.StringEscapeUtils

import org.apache.spark.JobExecutionStatus
import org.apache.spark.internal.Logging
import org.apache.spark.ui.{UIUtils, WebUIPage}

private[ui] class AllExecutionsPage(parent: SQLTab) extends WebUIPage("") with Logging {

  private val sqlStore = parent.sqlStore

  override def render(request: HttpServletRequest): Seq[Node] = {
    val currentTime = System.currentTimeMillis()
    val running = new mutable.ArrayBuffer[SQLExecutionUIData]()
    val completed = new mutable.ArrayBuffer[SQLExecutionUIData]()
    val failed = new mutable.ArrayBuffer[SQLExecutionUIData]()

    sqlStore.executionsList().foreach { e =>
      val isRunning = e.completionTime.isEmpty ||
        e.jobs.exists { case (_, status) => status == JobExecutionStatus.RUNNING }
      val isFailed = e.jobs.exists { case (_, status) => status == JobExecutionStatus.FAILED }
      if (isRunning) {
        running += e
      } else if (isFailed) {
        failed += e
      } else {
        completed += e
      }
    }

    val content = {
      val _content = mutable.ListBuffer[Node]()

      if (running.nonEmpty) {
        _content ++=
          new RunningExecutionTable(
            parent, s"Running Queries (${running.size})", currentTime,
            running.sortBy(_.submissionTime).reverse).toNodeSeq(request)
      }

      if (completed.nonEmpty) {
        _content ++=
          new CompletedExecutionTable(
            parent, s"Completed Queries (${completed.size})", currentTime,
            completed.sortBy(_.submissionTime).reverse).toNodeSeq(request)
      }

      if (failed.nonEmpty) {
        _content ++=
          new FailedExecutionTable(
            parent, s"Failed Queries (${failed.size})", currentTime,
            failed.sortBy(_.submissionTime).reverse).toNodeSeq(request)
      }
      _content
    }
    content ++=

    val summary: NodeSeq =

          {
            if (running.nonEmpty) {

                Running Queries:
                {running.size}

            }
          }
          {
            if (completed.nonEmpty) {

                Completed Queries:
                {completed.size}

            }
          }
          {
            if (failed.nonEmpty) {

                Failed Queries:
                {failed.size}

            }
          }

    UIUtils.headerSparkPage(request, "SQL", summary ++ content, parent, Some(5000))
  }
}

private[ui] abstract class ExecutionTable(
    parent: SQLTab,
    tableId: String,
    tableName: String,
    currentTime: Long,
    executionUIDatas: Seq[SQLExecutionUIData],
    showRunningJobs: Boolean,
    showSucceededJobs: Boolean,
    showFailedJobs: Boolean) {

  protected def baseHeader: Seq[String] = Seq(
    "ID",
    "Description",
    "Submitted",
    "Duration")

  protected def header: Seq[String]

  protected def row(
      request: HttpServletRequest,
      currentTime: Long,
      executionUIData: SQLExecutionUIData): Seq[Node] = {
    val submissionTime = executionUIData.submissionTime
    val duration = executionUIData.completionTime.map(_.getTime()).getOrElse(currentTime) -
      submissionTime

    def jobLinks(status: JobExecutionStatus): Seq[Node] = {
      executionUIData.jobs.flatMap { case (jobId, jobStatus) =>
        if (jobStatus == status) {
          [{jobId.toString}]
        } else {
          None
        }
      }.toSeq
    }

        {executionUIData.executionId.toString}

        {descriptionCell(request, executionUIData)}

        {UIUtils.formatDate(submissionTime)}

        {UIUtils.formatDuration(duration)}

      {if (showRunningJobs) {

          {jobLinks(JobExecutionStatus.RUNNING)}

      }}
      {if (showSucceededJobs) {

          {jobLinks(JobExecutionStatus.SUCCEEDED)}

      }}
      {if (showFailedJobs) {

          {jobLinks(JobExecutionStatus.FAILED)}

      }}

  }

  private def descriptionCell(
      request: HttpServletRequest,
      execution: SQLExecutionUIData): Seq[Node] = {
    val details = if (execution.details != null && execution.details.nonEmpty) {

        +details
       ++

{execution.details}

    } else {
      Nil
    }

    val desc = if (execution.description != null && execution.description.nonEmpty) {
      {execution.description}
    } else {
      {execution.executionId}
    }

{desc} {details}

  }

  def toNodeSeq(request: HttpServletRequest): Seq[Node] = {

{tableName}

      {UIUtils.listingTable[SQLExecutionUIData](
        header, row(request, currentTime, _), executionUIDatas, id = Some(tableId))}

  }

  private def jobURL(request: HttpServletRequest, jobId: Long): String =
    "%s/jobs/job?id=%s".format(UIUtils.prependBaseUri(request, parent.basePath), jobId)

  private def executionURL(request: HttpServletRequest, executionID: Long): String =
    s"${UIUtils.prependBaseUri(
      request, parent.basePath)}/${parent.prefix}/execution?id=$executionID"
}

private[ui] class RunningExecutionTable(
    parent: SQLTab,
    tableName: String,
    currentTime: Long,
    executionUIDatas: Seq[SQLExecutionUIData])
  extends ExecutionTable(
    parent,
    "running-execution-table",
    tableName,
    currentTime,
    executionUIDatas,
    showRunningJobs = true,
    showSucceededJobs = true,
    showFailedJobs = true) {

  override protected def header: Seq[String] =
    baseHeader ++ Seq("Running Job IDs", "Succeeded Job IDs", "Failed Job IDs")
}

private[ui] class CompletedExecutionTable(
    parent: SQLTab,
    tableName: String,
    currentTime: Long,
    executionUIDatas: Seq[SQLExecutionUIData])
  extends ExecutionTable(
    parent,
    "completed-execution-table",
    tableName,
    currentTime,
    executionUIDatas,
    showRunningJobs = false,
    showSucceededJobs = true,
    showFailedJobs = false) {

  override protected def header: Seq[String] = baseHeader ++ Seq("Job IDs")
}

private[ui] class FailedExecutionTable(
    parent: SQLTab,
    tableName: String,
    currentTime: Long,
    executionUIDatas: Seq[SQLExecutionUIData])
  extends ExecutionTable(
    parent,
    "failed-execution-table",
    tableName,
    currentTime,
    executionUIDatas,
    showRunningJobs = false,
    showSucceededJobs = true,
    showFailedJobs = true) {

  override protected def header: Seq[String] =
    baseHeader ++ Seq("Succeeded Job IDs", "Failed Job IDs")
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.data.schemaregistry.implementation.models;

import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpRequest;
import com.azure.core.http.rest.ResponseBase;

/** Contains all response data for the queryIdByContent operation. */
public final class SchemasQueryIdByContentResponse extends ResponseBase<SchemasQueryIdByContentHeaders, Void> {
    /**
     * Creates an instance of SchemasQueryIdByContentResponse.
     *
     * @param request the request which resulted in this SchemasQueryIdByContentResponse.
     * @param statusCode the status code of the HTTP response.
     * @param rawHeaders the raw headers of the HTTP response.
     * @param value the deserialized value of the HTTP response.
     * @param headers the deserialized headers of the HTTP response.
     */
    public SchemasQueryIdByContentResponse(
            HttpRequest request,
            int statusCode,
            HttpHeaders rawHeaders,
            Void value,
            SchemasQueryIdByContentHeaders headers) {
        super(request, statusCode, rawHeaders, value, headers);
    }
}


text:
"""
Helper functions which constructs blaze functions from dynd kernels.
"""

from __future__ import absolute_import, division, print_function

from dynd import _lowlevel
import datashape

from .. import function

def _make_sig(kern):
    dslist = [datashape.dshape("A..., " + str(x)) for x in kern.types]
    return datashape.Function(*(dslist[1:] + [dslist[0]]))

def _make_pyfunc(nargs, modname, name):
    if nargs == 1:
        def pyfunc(arg1):
            raise NotImplementedError('pyfunc for blaze func %s should not be called' % name)
    elif nargs == 2:
        def pyfunc(arg1, arg2):
            raise NotImplementedError('pyfunc for blaze func %s should not be called' % name)
    elif nargs == 3:
        def pyfunc(arg1, arg2, arg3):
            raise NotImplementedError('pyfunc for blaze func %s should not be called' % name)
    elif nargs == 4:
        def pyfunc(arg1, arg2, arg3, arg4):
            raise NotImplementedError('pyfunc for blaze func %s should not be called' % name)
    else:
        raise ValueError('unsupported number of args %s' % nargs)
    pyfunc.__module__ = modname
    pyfunc.__name__ = modname + '.' + name if modname else name
    return pyfunc

def blazefunc_from_dynd_property(tplist, propname, modname, name):
    """Converts a dynd property access into a Blaze ufunc.

    Parameters
    ----------
    tplist : list of dynd types
        A list of the types to use.
    propname : str
        The name of the property to access on the type.
    modname : str
        The module name to report in the ufunc's name
    name : str
        The ufunc's name.
    """
    # Get the list of type signatures
    kernlist = [_lowlevel.make_ckernel_deferred_from_property(tp, propname,
                                                              'expr', 'default')
                for tp in tplist]
    siglist = [_make_sig(kern) for kern in kernlist]
    # Create the empty blaze function to start
    blaze_func = function.BlazeFunc()
    blaze_func.add_metadata({'elementwise': True})
    # Add default dummy dispatching for 'python' mode
    pydispatcher = blaze_func.get_dispatcher('python')
    # Add dispatching to the kernel for each signature
    ckdispatcher = blaze_func.get_dispatcher('ckernel')
    for (sig, kern) in zip(siglist, kernlist):
        # The blaze function currently requires matching (do-nothing)
        # python functions
        pyfunc = _make_pyfunc(len(kern.types) - 1, modname, name)
        datashape.overloading.overload(sig, dispatcher=pydispatcher)(pyfunc)
        datashape.overloading.overload(sig, dispatcher=ckdispatcher)(kern)
    return blaze_func


text:
package de.djuelg.neuronizer.presentation.ui.custom.view;

import android.view.View;

import de.djuelg.neuronizer.R;
import jp.wasabeef.richeditor.RichEditor;

import static de.djuelg.neuronizer.presentation.ui.Constants.EDITOR_DETAILS_CSS;
import static de.djuelg.neuronizer.presentation.ui.Constants.EDITOR_FONT_SIZE;
import static de.djuelg.neuronizer.presentation.ui.Constants.EDITOR_HEIGHT;
import static de.djuelg.neuronizer.presentation.ui.Constants.EDITOR_PADDING;

/**
 * Created by Domi on 18.08.2017.
 */

public class RichEditorNavigation {

    private final View mView;
    private final RichEditor mEditor;

    public RichEditorNavigation(View view, RichEditor mEditor) {
        this.mView = view;
        this.mEditor = mEditor;
    }

    public static void setupRichEditor(RichEditor richEditor) {
        richEditor.setEditorHeight(EDITOR_HEIGHT);
        richEditor.setPadding(EDITOR_PADDING, EDITOR_PADDING, EDITOR_PADDING, EDITOR_PADDING);
        richEditor.setEditorFontSize(EDITOR_FONT_SIZE);
        richEditor.loadCSS(EDITOR_DETAILS_CSS);
    }

    public void setupRichEditor() {
        setupRichEditor(mEditor);
    }

    public void setupOnClickListeners() {
        final View richTextNavigation = mView.findViewById(R.id.richtext_navigation);

        mEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    richTextNavigation.setVisibility(View.VISIBLE);
                } else {
                    richTextNavigation.setVisibility(View.GONE);
                }
            }
        });

        mView.findViewById(R.id.action_undo).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.undo();
            }
        });

        mView.findViewById(R.id.action_bold).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                v.setSelected(!v.isSelected());
                mEditor.setBold();
            }
        });

        mView.findViewById(R.id.action_italic).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                v.setSelected(!v.isSelected());
                mEditor.setItalic();
            }
        });

        mView.findViewById(R.id.action_underline).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                v.setSelected(!v.isSelected());
                mEditor.setUnderline();
            }
        });

        mView.findViewById(R.id.action_heading1).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setHeading(2);
            }
        });

        mView.findViewById(R.id.action_heading2).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setHeading(3);
            }
        });

        mView.findViewById(R.id.action_heading3).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setHeading(4);
            }
        });

        mView.findViewById(R.id.action_indent).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setIndent();
            }
        });

        mView.findViewById(R.id.action_outdent).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setOutdent();
            }
        });

        mView.findViewById(R.id.action_align_left).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setAlignLeft();
            }
        });

        mView.findViewById(R.id.action_align_center).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setAlignCenter();
            }
        });

        mView.findViewById(R.id.action_align_right).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setAlignRight();
            }
        });

        mView.findViewById(R.id.action_insert_bullets).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setBullets();
            }
        });

        mView.findViewById(R.id.action_insert_numbers).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                mEditor.setNumbers();
            }
        });
    }
}


text:
package graph

// Defines one of the base iterators, the HasA iterator. The HasA takes a
// subiterator of links, and acts as an iterator of nodes in the given
// direction. The name comes from the idea that a "link HasA subject" or a "link
// HasA predicate".
//
// HasA is weird in that it may return the same value twice if on the Next()
// path. That's okay -- in reality, it can be viewed as returning the value for
// a new quad, but to make logic much simpler, here we have the HasA.
//
// Likewise, it's important to think about Contains()ing a HasA. When given a
// value to check, it means "Check all predicates that have this value for your
// direction against the subiterator." This would imply that there's more than
// one possibility for the same Contains()ed value. While we could return the
// number of options, it's simpler to return one, and then call NextPath()
// enough times to enumerate the options. (In fact, one could argue that the
// raison d'etre for NextPath() is this iterator).
//
// Alternatively, can be seen as the dual of the LinksTo iterator.

import (
	"context"
	"fmt"

	"github.com/cayleygraph/cayley/clog"
	"github.com/cayleygraph/cayley/graph/iterator"
	"github.com/cayleygraph/cayley/graph/refs"
	"github.com/cayleygraph/quad"
)

// A HasA consists of a reference back to the graph.QuadStore that it references,
// a primary subiterator, a direction in which the quads for that subiterator point,
// and a temporary holder for the iterator generated on Contains().
type HasA struct {
	qs      QuadIndexer
	primary iterator.Shape
	dir     quad.Direction
}

// NewHasA construct a new HasA iterator, given the quad subiterator, and the quad
// direction for which it stands.
func NewHasA(qs QuadIndexer, subIt iterator.Shape, d quad.Direction) *HasA {
	return &HasA{
		qs:      qs,
		primary: subIt,
		dir:     d,
	}
}

func (it *HasA) Iterate() iterator.Scanner {
	return newHasANext(it.qs, it.primary.Iterate(), it.dir)
}

func (it *HasA) Lookup() iterator.Index {
	return newHasAContains(it.qs, it.primary.Lookup(), it.dir)
}

// SubIterators returns our sole subiterator.
func (it *HasA) SubIterators() []iterator.Shape {
	return []iterator.Shape{it.primary}
}

// Direction accessor.
func (it *HasA) Direction() quad.Direction { return it.dir }

// Optimize pass the Optimize() call along to the subiterator. If it becomes Null,
// then the HasA becomes Null (there are no quads that have any directions).
func (it *HasA) Optimize(ctx context.Context) (iterator.Shape, bool) {
	newPrimary, changed := it.primary.Optimize(ctx)
	if changed {
		it.primary = newPrimary
		if iterator.IsNull(it.primary) {
			return it.primary, true
		}
	}
	return it, false
}

func (it *HasA) String() string {
	return fmt.Sprintf("HasA(%v)", it.dir)
}

// Stats returns the statistics on the HasA iterator. This is curious. Next
// cost is easy, it's an extra call or so on top of the subiterator Next cost.
// ContainsCost involves going to the graph.QuadStore, iterating out values, and hoping
// one sticks -- potentially expensive, depending on fanout. Size, however, is
// potentially smaller. we know at worst it's the size of the subiterator, but
// if there are many repeated values, it could be much smaller in totality.
func (it *HasA) Stats(ctx context.Context) (iterator.Costs, error) {
	subitStats, err := it.primary.Stats(ctx)
	// TODO(barakmich): These should really come from the quadstore itself
	// and be optimized.
	faninFactor := int64(1)
	fanoutFactor := int64(30)
	nextConstant := int64(2)
	quadConstant := int64(1)
	return iterator.Costs{
		NextCost:     quadConstant + subitStats.NextCost,
		ContainsCost: (fanoutFactor * nextConstant) * subitStats.ContainsCost,
		Size: refs.Size{
			Value: faninFactor * subitStats.Size.Value,
			Exact: false,
		},
	}, err
}

// A HasA consists of a reference back to the graph.QuadStore that it references,
// a primary subiterator, a direction in which the quads for that subiterator point,
// and a temporary holder for the iterator generated on Contains().
type hasANext struct {
	qs      QuadIndexer
	primary iterator.Scanner
	dir     quad.Direction
	result  refs.Ref
	err     error
}

// Construct a new HasA iterator, given the quad subiterator, and the quad
// direction for which it stands.
func newHasANext(qs QuadIndexer, subIt iterator.Scanner, d quad.Direction) *hasANext {
	return &hasANext{
		qs:      qs,
		primary: subIt,
		dir:     d,
	}
}

// Direction accessor.
func (it *hasANext) Direction() quad.Direction { return it.dir }

// Pass the TagResults down the chain.
func (it *hasANext) TagResults(dst map[string]refs.Ref) {
	it.primary.TagResults(dst)
}

func (it *hasANext) String() string {
	return fmt.Sprintf("HasANext(%v)", it.dir)
}

// Get the next result that matches this branch.
func (it *hasANext) NextPath(ctx context.Context) bool {
	return it.primary.NextPath(ctx)
}

// Next advances the iterator. This is simpler than Contains. We have a
// subiterator we can get a value from, and we can take that resultant quad,
// pull our direction out of it, and return that.
func (it *hasANext) Next(ctx context.Context) bool {
	if !it.primary.Next(ctx) {
		return false
	}
	var err error
	it.result, err = it.qs.QuadDirection(it.primary.Result(), it.dir)
	if err != nil {
		it.err = err
		return false
	}
	return true
}

func (it *hasANext) Err() error {
	if it.err != nil {
		return it.err
	}
	return it.primary.Err()
}

func (it *hasANext) Result() refs.Ref {
	return it.result
}

// Close the subiterator, the result iterator (if any) and the HasA. It closes
// all subiterators it can, but returns the first error it encounters.
func (it *hasANext) Close() error {
	return it.primary.Close()
}

// A HasA consists of a reference back to the graph.QuadStore that it references,
// a primary subiterator, a direction in which the quads for that subiterator point,
// and a temporary holder for the iterator generated on Contains().
type hasAContains struct {
	qs      QuadIndexer
	primary iterator.Index
	dir     quad.Direction
	results iterator.Scanner
	result  refs.Ref
	err     error
}

// Construct a new HasA iterator, given the quad subiterator, and the quad
// direction for which it stands.
func newHasAContains(qs QuadIndexer, subIt iterator.Index, d quad.Direction) iterator.Index {
	return &hasAContains{
		qs:      qs,
		primary: subIt,
		dir:     d,
	}
}

// Direction accessor.
func (it *hasAContains) Direction() quad.Direction { return it.dir }

// Pass the TagResults down the chain.
func (it *hasAContains) TagResults(dst map[string]refs.Ref) {
	it.primary.TagResults(dst)
}

func (it *hasAContains) String() string {
	return fmt.Sprintf("HasAContains(%v)", it.dir)
}

// Check a value against our internal iterator. In order to do this, we must first open a new
// iterator of "quads that have `val` in our direction", given to us by the quad store,
// and then Next() values out of that iterator and Contains() them against our subiterator.
func (it *hasAContains) Contains(ctx context.Context, val refs.Ref) bool {
	if clog.V(4) {
		clog.Infof("Id is %v", val)
	}
	// TODO(barakmich): Optimize this
	if it.results != nil {
		it.results.Close()
	}
	it.results = it.qs.QuadIterator(it.dir, val).Iterate()
	ok := it.nextContains(ctx)
	if it.err != nil {
		return false
	}
	return ok
}

// nextContains() is shared code between Contains() and GetNextResult() -- calls next on the
// result iterator (a quad iterator based on the last checked value) and returns true if
// another match is made.
func (it *hasAContains) nextContains(ctx context.Context) bool {
	if it.results == nil {
		return false
	}
	for it.results.Next(ctx) {
		link := it.results.Result()
		if clog.V(4) {
			qlv, err := it.qs.Quad(link)
			if err == nil {
				clog.Infof("Quad is %v", qlv)
			} else {
				clog.Warningf("Error looking up result quad: %v", err)
			}
		}
		if it.primary.Contains(ctx, link) {
			var err error
			it.result, err = it.qs.QuadDirection(link, it.dir)
			if err != nil {
				it.err = err
				return false
			}
			return true
		}
	}
	it.err = it.results.Err()
	return false
}

// Get the next result that matches this branch.
func (it *hasAContains) NextPath(ctx context.Context) bool {
	// Order here is important. If the subiterator has a NextPath, then we
	// need do nothing -- there is a next result, and we shouldn't move forward.
	// However, we then need to get the next result from our last Contains().
	//
	// The upshot is, the end of NextPath() bubbles up from the bottom of the
	// iterator tree up, and we need to respect that.
	if clog.V(4) {
		clog.Infof("HASA %p NextPath", it)
	}
	if it.primary.NextPath(ctx) {
		return true
	}
	it.err = it.primary.Err()
	if it.err != nil {
		return false
	}

	result := it.nextContains(ctx) // Sets it.err if there's an error
	if it.err != nil {
		return false
	}
	if clog.V(4) {
		clog.Infof("HASA %p NextPath Returns %v", it, result)
	}
	return result
}

func (it *hasAContains) Err() error {
	return it.err
}

func (it *hasAContains) Result() refs.Ref {
	return it.result
}

// Close the subiterator, the result iterator (if any) and the HasA. It closes
// all subiterators it can, but returns the first error it encounters.
func (it *hasAContains) Close() error {
	err := it.primary.Close()
	if it.results != nil {
		if err2 := it.results.Close(); err2 != nil && err == nil {
			err = err2
		}
	}
	return err
}


text:
It's a clock, for #sudoroom

# requirements
This requires the ESP8266 IoT SDK, after following it's build directions you
should have the paths needed for the next build step.

# wiring

| ESP | MATRIX |
|-----|--------|
| 13  |   DIN  |
| 12  |   CS   |
| 14  |   CLK  |

# build
```
  SDK_DIR=/path/to/esp_iot_sdk_v1.x/ ESPTOOL2=/path/to/esptool/esptool2 make
```

You can also edit the Makefile setting the paths to the SDK and esptool2.

# flash
  esptool.py --port COM2 write_flash -fs 8m 0x00000 firmware/0x00000.bin 0x40000 firmware/0x40000.bin

Tested with SDK v1.4 on an ESP12 (if using a board with less than 1mb of flash
a change to the second linker script will be required).

```
  miniterm.py /dev/ttyUSB0 115200 --rts=0 --dtr=0
```

NOTE: `--rts/--dtr` are only needed if you have these lines connected from your USB-Serial to
the ESP8266 for buttonless flashing.

# ITS A CLOCK!!!
![It's a clock!](https://github.com/morganrallen/sudo-clock/raw/master/extra/clock_v2.jpg)


text:
import { AuthenticatedTwitterCallHandler } from '../../twitter-call-handler';

export function configuration(callHandler: AuthenticatedTwitterCallHandler): Promise<any> {
  return callHandler.callTwitterApi('help/configuration');
}


text:
<?php

namespace Tests\Feature\Games;

use App\Games\Config;
use App\Models\Lobby;
use App\Models\Match;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ConfigTest extends TestCase
{
	use RefreshDatabase;

	public function test_it_returns_the_config()
	{
		$match = Match::factory()->create(['game' => 'tictactoe', 'config' => Lobby::DEFAULT_CONFIG['tictactoe']]);

		$this->assertInstanceOf(Config::class, $match->config());
		$this->assertSame($match->config(), $match->instance('config'));
		$this->assertSame($match->config(), $match->instance->get('config'));
	}

	public function test_it_returns_all()
	{
		$match = Match::factory()->create(['game' => 'tictactoe', 'config' => Lobby::DEFAULT_CONFIG['tictactoe']]);

		$this->assertEquals(Lobby::DEFAULT_CONFIG['tictactoe'], $match->config()->all());

		$match->config()->set('turn', 'lorem');

		$this->assertEquals(array_merge(Lobby::DEFAULT_CONFIG['tictactoe'], [
			'turn' => 'lorem',
		]), $match->config()->all());
	}

	public function test_it_can_be_initialized()
	{
		$match = Match::factory()->create(['game' => 'tictactoe', 'config' => Lobby::DEFAULT_CONFIG['tictactoe']]);

		$this->assertEquals(Lobby::DEFAULT_CONFIG['tictactoe'], $match->config()->all());

		$this->assertSame($match->config(), $match->config()->initialize([
			'lorem' => 'ipsum', 'nested' => ['key' => 'value'],
		]));

		$this->assertNotEquals(Lobby::DEFAULT_CONFIG['tictactoe'], $match->config()->all());

		$this->assertEquals([
			'lorem' => 'ipsum', 'nested' => ['key' => 'value'],
		], $match->config()->all());

		$this->assertDatabaseHas('matches', [
			'id' => $match->id,
			'config' => json_encode(['lorem' => 'ipsum', 'nested' => ['key' => 'value']]),
		]);
	}

	public function test_it_gets_values()
	{
		$match = Match::factory()->create(['game' => 'tictactoe', 'config' => Lobby::DEFAULT_CONFIG['tictactoe']]);

		$this->assertEquals(['min' => 2, 'max' => 2], $match->config('playerCount'));
		$this->assertEquals(2, $match->config('playerCount.min'));
		$this->assertEquals(2, $match->config('playerCount.max'));

		$this->assertEquals(['min' => 2, 'max' => 2], $match->config()->get('playerCount'));
		$this->assertEquals(2, $match->config()->get('playerCount.min'));
		$this->assertEquals(2, $match->config()->get('playerCount.max'));

		$this->assertNull($match->config('invalid'));
		$this->assertNull($match->config()->get('invalid'));
	}

	public function test_it_sets_values()
	{
		$match = Match::factory()->create(['game' => 'tictactoe', 'config' => Lobby::DEFAULT_CONFIG['tictactoe']]);

		$this->assertEquals($match->config(), $match->config()->set('playerCount.min', 3));
		$this->assertEquals(3, $match->config('playerCount.min'));

		$this->assertDatabaseHas('matches', [
			'id' => $match->id,
			'config' => json_encode(array_merge(Lobby::DEFAULT_CONFIG['tictactoe'], [
				'playerCount' => ['min' => 3, 'max' => 2],
			])),
		]);

		$this->assertEquals($match->config(), $match->config()->set('playerCount', ['min' => 1, 'max' => 1]));
		$this->assertEquals(['min' => 1, 'max' => 1], $match->config('playerCount'));
		$this->assertEquals(1, $match->config('playerCount.min'));
		$this->assertEquals(1, $match->config('playerCount.max'));

		$this->assertDatabaseHas('matches', [
			'id' => $match->id,
			'config' => json_encode(array_merge(Lobby::DEFAULT_CONFIG['tictactoe'], [
				'playerCount' => ['min' => 1, 'max' => 1],
			])),
		]);

		$this->assertEquals($match->config(), $match->config()->set('new_key', 'some value'));
		$this->assertEquals('some value', $match->config('new_key'));

		$this->assertDatabaseHas('matches', [
			'id' => $match->id,
			'config' => json_encode(array_merge(Lobby::DEFAULT_CONFIG['tictactoe'], [
				'playerCount' => ['min' => 1, 'max' => 1],
				'new_key' => 'some value',
			])),
		]);
	}

	public function test_it_removes_values()
	{
		$match = Match::factory()->create(['game' => 'tictactoe', 'config' => Lobby::DEFAULT_CONFIG['tictactoe']]);

		$this->assertTrue($match->config()->has('playerCount'));
		$this->assertTrue($match->config()->has('playerCount.min'));
		$this->assertTrue($match->config()->has('playerCount.max'));

		$this->assertEquals($match->config(), $match->config()->remove('playerCount.min'));

		$this->assertFalse($match->config()->has('playerCount.min'));
		$this->assertNull($match->config('playerCount.min'));

		$this->assertDatabaseHas('matches', [
			'id' => $match->id,
			'config' => json_encode(array_merge(Lobby::DEFAULT_CONFIG['tictactoe'], ['playerCount' => ['max' => 2]])),
		]);

		$this->assertEquals($match->config(), $match->config()->remove('playerCount'));

		$this->assertFalse($match->config()->has('playerCount'));
		$this->assertFalse($match->config()->has('playerCount.min'));
		$this->assertFalse($match->config()->has('playerCount.max'));

		$this->assertNull($match->config('playerCount'));
		$this->assertNull($match->config('playerCount.min'));
		$this->assertNull($match->config('playerCount.max'));

		$this->assertDatabaseHas('matches', [
			'id' => $match->id,
			'config' => json_encode([]),
		]);
	}
}


text:
require 'helper'

class TestNominetDomainCheckRequest < Test::Unit::TestCase
  context 'NominetEPP::Domain::Check' do
    setup do
      @request = NominetEPP::Domain::Check.new('example.co.uk', 'example.me.uk')
      @xml     = prepare_request.to_xml

      namespaces_from_request
    end

    should 'validate against schema' do
      assert @xml.validate_schema(schema)
    end

    should 'include names' do
      names = []
      xpath_each('//domain:name') do |node|
        names << node.content.strip
      end

      assert_equal %w(example.co.uk example.me.uk), names
    end
  end

  context 'NominetEPP::Domain::Check Direct Rights' do
    context 'registrant' do
      setup do
        @request = NominetEPP::Domain::Check.new('example.uk', :registrant => '239r79343')
        @xml     = prepare_request.to_xml

        namespaces_from_request
      end

      should 'validate against schema' do
        assert @xml.validate_schema(schema)
      end

      should 'include name' do
        names = []
        xpath_each('//domain:name') do |node|
          names << node.content.strip
        end

        assert_equal %w(example.uk), names
      end

      should 'include direct-rights extension' do
        assert xpath_exists?('//nom-direct-rights:check'), "should have extension create element"
      end

      should 'have registrant element' do
        assert_equal '239r79343', xpath_find('//nom-direct-rights:registrant')
      end
    end

    context 'postal info & email' do
      setup do
        @request = NominetEPP::Domain::Check.new('example.uk',
          :email       => "enoch.root@test.host",
          :postal_info => {
            :org       => "Epiphyte",
            :name      => "Enoch Root",
            :addr      => {
              :street  => "1 Test Avenue",
              :city    => "Testington",
              :sp      => "Testshire",
              :pc      => "TE57 1NG",
              :cc      => "GB" } })
        @xml     = prepare_request.to_xml

        namespaces_from_request
      end

      should 'validate against schema' do
        assert @xml.validate_schema(schema)
      end

      should 'include name' do
        names = []
        xpath_each('//domain:name') do |node|
          names << node.content.strip
        end

        assert_equal %w(example.uk), names
      end

      should 'include direct-rights extension' do
        assert xpath_exists?('//nom-direct-rights:check'), "should have extension create element"
      end

      should 'set email' do
        assert_equal "enoch.root@test.host", xpath_find('//nom-direct-rights:email')
      end
      should 'set organisation' do
        assert_equal "Epiphyte", xpath_find('//nom-direct-rights:postalInfo/contact:org')
      end
      should 'set name' do
        assert_equal "Enoch Root", xpath_find('//nom-direct-rights:postalInfo/contact:name')
      end
      should 'set address' do
        assert_equal "1 Test Avenue", xpath_find('//nom-direct-rights:postalInfo/contact:addr/contact:street')
        assert_equal "Testington", xpath_find('//nom-direct-rights:postalInfo/contact:addr/contact:city')
        assert_equal "Testshire", xpath_find('//nom-direct-rights:postalInfo/contact:addr/contact:sp')
        assert_equal "TE57 1NG", xpath_find('//nom-direct-rights:postalInfo/contact:addr/contact:pc')
        assert_equal "GB", xpath_find('//nom-direct-rights:postalInfo/contact:addr/contact:cc')
      end
    end

    context 'argument errors' do
      should 'raise argument error if rights requested with multiple names' do
        assert_raises ArgumentError do
          NominetEPP::Domain::Check.new('example.uk', 'example2.uk',
            :registrant => '239r79343')
        end
      end

      should 'raise argument error if registrant given with other keys' do
        assert_raises ArgumentError do
          NominetEPP::Domain::Check.new('example.uk',
            :registrant => '239r79343', :email => 'example@example.co.uk')
        end
      end

      should 'raise argument error if postal info given without email' do
        assert_raises ArgumentError do
          NominetEPP::Domain::Check.new('example.uk',
            :postal_info => { :name => "Joe Bloggs" })
        end
      end

      should 'raise argument error if email given without postal info' do
        assert_raises ArgumentError do
          NominetEPP::Domain::Check.new('example.uk',
            :email => 'example@example.co.uk')
        end
      end
    end
  end
end


text:
=head1 NAME

Mail::SpamAssassin::Conf::LDAP - load SpamAssassin scores from LDAP database

=head1 SYNOPSIS

  (see Mail::SpamAssassin)

=head1 DESCRIPTION

Mail::SpamAssassin is a module to identify spam using text analysis and
several internet-based realtime blacklists.

This class is used internally by SpamAssassin to load scores from an LDAP
database.  Please refer to the C<Mail::SpamAssassin> documentation for public
interfaces.

=head1 METHODS

=over 4

=cut

package Mail::SpamAssassin::Conf::LDAP;

use Mail::SpamAssassin::Logger;

use strict;
use warnings;
use bytes;

use vars qw{
  @ISA
};

@ISA = qw();

###########################################################################

sub new {
  my $class = shift;
  $class = ref($class) || $class;
  my ($main) = @_;

  my $self = {
    'main'              => $main
  };

  bless ($self, $class);
  $self;
}

###########################################################################

sub load_modules {		# static
  dbg("ldap: loading Net::LDAP and URI");
  eval {
    require Net::LDAP; # actual server connection
    require URI;       # parse server connection dsn
  };

  # do any other preloading that will speed up operation
}

###########################################################################

=item $f->load ($username)

Read configuration paramaters from LDAP server and parse scores from it.

=cut

sub load {
   my ($self, $username) = @_;

   my $url = $self->{main}->{conf}->{user_scores_dsn}; # an ldap URI
   dbg("ldap: URL is $url");
   if(!defined($url) || $url eq '') {
     dbg("ldap: No URL defined; skipping LDAP");
     return;
   }

   eval {
     # make sure we can see croak messages from DBI
     local $SIG{'__DIE__'} = sub { warn "$_[0]"; };
     require Net::LDAP;
     require URI;
     load_with_ldap($self, $username, $url);
   };

   if ($@) {
     warn "ldap: failed to load user scores from LDAP server, ignored ($@)\n";
   }
}

sub load_with_ldap {
  my ($self, $username, $url) = @_;

#       ldapurl    = scheme "://" [hostport] ["/"
#                    [dn ["?" [attributes] ["?" [scope]
#                    ["?" [filter] ["?" extensions]]]]]]

  my $uri = URI->new("$url");

  my $host   = $uri->host;
  if (!defined($host) || $host eq '') {
    dbg("ldap: No server specified, assuming localhost");
    $host = "localhost";
  }
  my $port   = $uri->port;
  my $base   = $uri->dn;
  my @attr   = $uri->attributes;
  my $scope  = $uri->scope;
  my $filter = $uri->filter;
  my $scheme = $uri->scheme;
  my %extn   = $uri->extensions; # unused

  $filter =~ s/__USERNAME__/$username/g;
  dbg("ldap: host=$host, port=$port, base='$base', attr=${attr[0]}, scope=$scope, filter='$filter'");

  my $main = $self->{main};
  my $ldapuser = $main->{conf}->{user_scores_ldap_username};
  my $ldappass = $main->{conf}->{user_scores_ldap_password};

  if(!$ldapuser) {
      undef($ldapuser);
  } else {
      dbg("ldap: user='$ldapuser'");
  }

  if(!$ldappass) {
      undef($ldappass);
  } else {
      # don't log this to avoid leaking sensitive info
      # dbg("ldap: pass='$ldappass'");
  }

  my $f_attribute = $attr[0];

  my $ldap = Net::LDAP->new ("$host:$port",
                onerror => "warn",
                scheme => $scheme);

  if (!defined($ldapuser) && !defined($ldappass)) {
    $ldap->bind;
  } else {
    $ldap->bind($ldapuser, password => $ldappass);
  }

  my $result = $ldap->search( base => $base,
			      filter => $filter,
			      scope => $scope,
			      attrs => \@attr
                            );

  my $conf = '';
  foreach my $entry ($result->all_entries) {
    my @v = $entry->get_value($f_attribute);
    foreach my $v (@v) {
      dbg("ldap: retrieving prefs for $username: $v");
      $conf .= $v."\n";
    }
  }
  $main->{conf}->{main} = $main;
  $main->{conf}->parse_scores_only($conf);
  delete $main->{conf}->{main};
  return;
}

###########################################################################

sub sa_die { Mail::SpamAssassin::sa_die(@_); }

###########################################################################

1;


text:
/// <reference path="class-info.js" />

classInfo.setup({
    name: "AtomFrameView",
    value: "atom-frame-view",
    properties: [
        {
            label: "url",
            value: "url",
            readonly: false,
            def: "",
            description: "View will navigate to specified url that should exist as scope template",
            url: ""
        }
    ]
});

classInfo.load("atom-view-stack");


text:
<?php
namespace Eagle\Content\Forms;

use Eagle\Core\Services\Debug;
use Phalcon\Annotations\Exception;
use Phalcon\Forms\Element\Hidden;
use Phalcon\Forms\Element\Submit;
use Phalcon\Forms\Form as PhalconForm;
use Phalcon\Filter;
use Phalcon\Validation\Message;

class Form extends PhalconForm
{
    protected $_method = 'POST';
    protected $_view = null;

    protected $_attribs = array();

    protected $_render_submit = false;

    protected $_entity_messages = array();

    public function getMethod()
    {
        return $this->_method;
    }

    public function setMethod($value)
    {
        $value = trim(strtolower($value));
        if ($value === 'get') {
            $this->_method = 'GET';
        } else {
            $this->_method = 'POST';
        }
    }

    public function getAllMessagesFor($element)
    {
        $messages = [];
        foreach ($this->getMessagesFor($element) as $message) {
            $messages[] = $message;
        }
        /* @var $model \Phalcon\Mvc\Model */
        $model = $this->getEntity();
        foreach ($model->getMessages() as $message) {
            if ($message->getField() == $element) {
                $messages[] = $message;
            }
        }
        return $messages;
    }

    public function setView($path)
    {
        if (!is_file($path)) {

            // $build_path = CORE_PATH . '/views/forms/'

            throw new \Exception("Invalid form view path");
        }
        $this->_view = $path;
    }

    public function renderForm()
    {
        $this->_attribs['action'] = $this->getAction();
        $this->_attribs['method'] = $this->getMethod();
        $attribs = array();

        foreach ($this->_attribs as $key => $value) {
            if (is_array($value)) {
                $attribs[] = "{$key}='" . implode(' ', $value) . "'";
            } else {
                $attribs[] = "{$key}='{$value}'";
            }
        }

        return '<form ' . implode(' ', $attribs) . '>';
    }

    public function renderEndForm()
    {

        $string_to_render = array();

        if($this->_render_submit === false) {
            //no submit was rendered we presume a submit button does not exist and add one
            //check if a submit element exists

            $submit = new Submit('save');
            $submit->setDefault('Save');
            $this->add($submit);
            $string_to_render[] = $this->renderDecorated('save');
            $this->_render_submit = 'save';

        }

        $string_to_render[] = '</form>';
        return implode(' ', $string_to_render);
    }

    public function renderErrors(\Phalcon\Forms\ElementInterface $element)
    {

        $messages = $this->getMessagesFor($element->getName());

        $this->getEntityMessages();

        if (isset($this->_entity_messages[$element->getName()])) {

            foreach ($this->_entity_messages[$element->getName()] as $key => $message) {
                if ($key === 'has_element') {
                    continue;
                }
                $messages->appendMessage(new Message($message->getMessage()));

            }

            $this->_entity_messages[$element->getName()]['has_element'] = true;

        } elseif ($element instanceof Submit && count($this->_entity_messages) > 0) {

            /**
             * Attach all the errors to submit, must be sure Submit is always last
             */

            foreach ($this->_entity_messages as $k => $model_messages) {
                if (isset($model_messages['has_element']) && $model_messages['has_element'] === true) {
                    continue;
                }
                foreach ($model_messages as $message) {
                    $messages->appendMessage(new Message($message->getMessage()));
                }

            }

        }

        $element_string = array();

        // Get any generated messages for the current element
        if ($messages->count()) {

            // Print each element
            $element_string[] = '

';

            foreach ($messages as $message) {
                $element_string[] = '
' . $message->getMessage() . '
';
            }
            $element_string[] = '

';
        }

        return implode(' ', $element_string);
    }

    public function __toString()
    {
        if ($this->request->isAjax()) {
            $this->_attribs['class'][] = 'ajaxSubmit';
        }

        try {
            if (!is_null($this->_view) && is_file($this->_view)) {
                include $this->_view;
                return '';
            }

            $string_to_return = array();

            $string_to_return[] = $this->renderForm();

            foreach ($this->getElements() as $element_key => $element) {
                if($element instanceof Submit) {
                    $this->_render_submit = $element_key;
                }
                $string_to_return[] = $this->renderDecorated($element_key);

            }

            $string_to_return[] = $this->renderEndForm();
            return implode(' ', $string_to_return);
        } catch (\Exception $e) {
            Debug::exception($e, true);

        }
        return '';

    }

    public function getEntityMessages()
    {

        if (empty($this->_entity_messages)) {

            if ($this->getEntity() && $this->getEntity()->getMessages()) {

                foreach ($this->getEntity()->getMessages() as $message) {

                    $this->_entity_messages[$message->getField()][] = new Message($message->getMessage());

                }
            }

        }

        return $this->_entity_messages;
    }

    public function renderDecorated($name)
    {

        $element_string = array();

        $element = $this->get($name);

        $element_string[] = '
';

        if (!($element instanceof Hidden)) {
            $element_string[] = 'getName() . '">' . $element->getLabel() . '';
        }

        $element_string[] = $element->render();

        $element_string[] = $this->renderErrors($element);

        $element_string[] = '
';

        return implode(' ', $element_string);

    }

    public function getValues()
    {

        $filter = new Filter();

        $elements = array();

        foreach ($this->getElements() as $element_name => $element) {
            $element_value = $element->getValue();

            if ($element->getFilters()) {
                foreach ($element->getFilters() as $filter_name) {
                    $element_value = $filter->sanitize($element_value, $filter_name);
                }
            }
            $elements[$element_name] = $element_value;
        }
        return $elements;
    }

}


text:
package com.ocdsoft.bacta.swg.shared.collision.extent;

import bacta.iff.Iff;
import com.ocdsoft.bacta.swg.shared.collision.ExtentType;
import com.ocdsoft.bacta.swg.shared.math.*;

/**
 * Created by crush on 4/22/2016.
 */
public abstract class BaseExtent {
    private final ExtentType extentType;

    public BaseExtent() {
        extentType = ExtentType.NULL;
    }

    public BaseExtent(final ExtentType extentType) {
        this.extentType = extentType;
    }

    public final ExtentType getType() {
        return extentType;
    }

    public abstract void load(final Iff iff);

    public abstract void write(final Iff iff);

    public abstract boolean contains(final Vector vector);

    public abstract boolean contains(final Vector begin, final Vector end);

    public abstract Range rangedIntersect(final Line3d line);

    public abstract Range rangedInsersect(final Ray3d ray);

    public abstract Range rangedIntersect(final Segment3d segment);

    public abstract BaseExtent clone();

    public abstract void copy(final BaseExtent source);

    public abstract void transform(final BaseExtent parent, final Transform transform, final float scale);

    public abstract AxialBox getBoundingBox();

    public abstract Sphere getBoundingSphere();

    public boolean intersect(final Vector begin, final Vector end, final Vector surfaceNormal, float time) {
        return realIntersect(begin, end, surfaceNormal, time);
    }

    public boolean intersect(final Vector begin, final Vector end, float time) {
        final Vector surfaceNormal = null;
        return realIntersect(begin, end, surfaceNormal, time);
    }

    public boolean interset(final Vector begin, final Vector end) {
        final Vector surfaceNormal = null;
        float time = 0;
        return realIntersect(begin, end, surfaceNormal, time);
    }

    public Vector getCenter() {
        return getBoundingSphere().getCenter();
    }

    public float getRadius() {
        return getBoundingSphere().getRadius();
    }

    public boolean validate() {
        return true;
    }

    protected abstract boolean realIntersect(final Vector begin, final Vector end, Vector surfaceNormal, float time);
}


text:
import React, { PropTypes } from 'react';
import './Card.css';
import back from './images/back.png';

// I really hope there's a better way to do this:
const cards = [
  require('./images/1.png'),
  require('./images/2.png'),
  require('./images/3.png'),
  require('./images/4.png'),
  require('./images/5.png'),
  require('./images/6.png'),
  require('./images/7.png'),
  require('./images/8.png'),
  require('./images/9.png'),
  require('./images/10.png'),
  require('./images/11.png'),
  require('./images/12.png'),
  require('./images/13.png'),
  require('./images/14.png'),
  require('./images/15.png'),
  require('./images/16.png'),
  require('./images/17.png'),
  require('./images/18.png'),
  require('./images/19.png'),
  require('./images/20.png'),
  require('./images/21.png'),
  require('./images/22.png'),
  require('./images/23.png'),
  require('./images/24.png'),
  require('./images/25.png'),
  require('./images/26.png'),
  require('./images/27.png'),
  require('./images/28.png'),
  require('./images/29.png'),
  require('./images/30.png'),
  require('./images/31.png'),
  require('./images/32.png'),
  require('./images/33.png'),
  require('./images/34.png'),
  require('./images/35.png'),
  require('./images/36.png')
];

function get_card_img(value, suit) {
  if (value === 0 || suit === 0) {
    return back;
  }

  const base = (14 - value) * 4;

  // The protocol uses Pass-C-D-S-H, the cards use C-S-H-D.
  const suit_offset = [0, 3, 1, 2][suit - 1];
  const card_num = base + suit_offset;
  return cards[card_num];
}

const Card = ({value, suit, direction}) => (
  // TODO: set alts to the value??
  <img src={get_card_img(value, suit)} className={"Card-" + direction} alt="card"/>
);

Card.propTypes = {
  value: PropTypes.number,
  suit: PropTypes.number,
  direction: PropTypes.string
};

Card.defaultProps = {
  value: 0,
  suit: 0
};

export default Card;


text:
/**
 * @module ol/renderer/Map
 */
import {getUid} from '../util.js';
import Disposable from '../Disposable.js';
import {listen, unlistenByKey} from '../events.js';
import EventType from '../events/EventType.js';
import {getWidth} from '../extent.js';
import {TRUE, UNDEFINED} from '../functions.js';
import {visibleAtResolution} from '../layer/Layer.js';
import {shared as iconImageCache} from '../style/IconImageCache.js';
import {compose as composeTransform, invert as invertTransform, setFromArray as transformSetFromArray} from '../transform.js';

var MapRenderer = (function (Disposable) {
  function MapRenderer(map) {
    Disposable.call(this);

    /**
     * @private
     * @type {module:ol/PluggableMap}
     */
    this.map_ = map;

    /**
     * @private
     * @type {!Object.<string, module:ol/renderer/Layer>}
     */
    this.layerRenderers_ = {};

    /**
     * @private
     * @type {Object.<string, module:ol/events~EventsKey>}
     */
    this.layerRendererListeners_ = {};

    /**
     * @private
     * @type {Array.<module:ol/renderer/Layer>}
     */
    this.layerRendererConstructors_ = [];

  }

  if ( Disposable ) MapRenderer.__proto__ = Disposable;
  MapRenderer.prototype = Object.create( Disposable && Disposable.prototype );
  MapRenderer.prototype.constructor = MapRenderer;

  /**
   * Register layer renderer constructors.
   * @param {Array.<module:ol/renderer/Layer>} constructors Layer renderers.
   */
  MapRenderer.prototype.registerLayerRenderers = function registerLayerRenderers (constructors) {
    this.layerRendererConstructors_.push.apply(this.layerRendererConstructors_, constructors);
  };

  /**
   * Get the registered layer renderer constructors.
   * @return {Array.<module:ol/renderer/Layer>} Registered layer renderers.
   */
  MapRenderer.prototype.getLayerRendererConstructors = function getLayerRendererConstructors () {
    return this.layerRendererConstructors_;
  };

  /**
   * @param {module:ol/PluggableMap~FrameState} frameState FrameState.
   * @protected
   */
  MapRenderer.prototype.calculateMatrices2D = function calculateMatrices2D (frameState) {
    var viewState = frameState.viewState;
    var coordinateToPixelTransform = frameState.coordinateToPixelTransform;
    var pixelToCoordinateTransform = frameState.pixelToCoordinateTransform;

    composeTransform(coordinateToPixelTransform,
      frameState.size[0] / 2, frameState.size[1] / 2,
      1 / viewState.resolution, -1 / viewState.resolution,
      -viewState.rotation,
      -viewState.center[0], -viewState.center[1]);

    invertTransform(
      transformSetFromArray(pixelToCoordinateTransform, coordinateToPixelTransform));
  };

  /**
   * Removes all layer renderers.
   */
  MapRenderer.prototype.removeLayerRenderers = function removeLayerRenderers () {
    var this$1 = this;

    for (var key in this$1.layerRenderers_) {
      this$1.removeLayerRendererByKey_(key).dispose();
    }
  };

  /**
   * @param {module:ol/coordinate~Coordinate} coordinate Coordinate.
   * @param {module:ol/PluggableMap~FrameState} frameState FrameState.
   * @param {number} hitTolerance Hit tolerance in pixels.
   * @param {function(this: S, (module:ol/Feature|module:ol/render/Feature),
   *     module:ol/layer/Layer): T} callback Feature callback.
   * @param {S} thisArg Value to use as `this` when executing `callback`.
   * @param {function(this: U, module:ol/layer/Layer): boolean} layerFilter Layer filter
   *     function, only layers which are visible and for which this function
   *     returns `true` will be tested for features.  By default, all visible
   *     layers will be tested.
   * @param {U} thisArg2 Value to use as `this` when executing `layerFilter`.
   * @return {T|undefined} Callback result.
   * @template S,T,U
   */
  MapRenderer.prototype.forEachFeatureAtCoordinate = function forEachFeatureAtCoordinate (
    coordinate,
    frameState,
    hitTolerance,
    callback,
    thisArg,
    layerFilter,
    thisArg2
  ) {
    var this$1 = this;

    var result;
    var viewState = frameState.viewState;
    var viewResolution = viewState.resolution;

    /**
     * @param {module:ol/Feature|module:ol/render/Feature} feature Feature.
     * @param {module:ol/layer/Layer} layer Layer.
     * @return {?} Callback result.
     */
    function forEachFeatureAtCoordinate(feature, layer) {
      var key = getUid(feature).toString();
      var managed = frameState.layerStates[getUid(layer)].managed;
      if (!(key in frameState.skippedFeatureUids && !managed)) {
        return callback.call(thisArg, feature, managed ? layer : null);
      }
    }

    var projection = viewState.projection;

    var translatedCoordinate = coordinate;
    if (projection.canWrapX()) {
      var projectionExtent = projection.getExtent();
      var worldWidth = getWidth(projectionExtent);
      var x = coordinate[0];
      if (x < projectionExtent[0] || x > projectionExtent[2]) {
        var worldsAway = Math.ceil((projectionExtent[0] - x) / worldWidth);
        translatedCoordinate = [x + worldWidth * worldsAway, coordinate[1]];
      }
    }

    var layerStates = frameState.layerStatesArray;
    var numLayers = layerStates.length;
    var i;
    for (i = numLayers - 1; i >= 0; --i) {
      var layerState = layerStates[i];
      var layer = layerState.layer;
      if (visibleAtResolution(layerState, viewResolution) && layerFilter.call(thisArg2, layer)) {
        var layerRenderer = this$1.getLayerRenderer(layer);
        if (layer.getSource()) {
          result = layerRenderer.forEachFeatureAtCoordinate(
            layer.getSource().getWrapX() ? translatedCoordinate : coordinate,
            frameState, hitTolerance, forEachFeatureAtCoordinate, thisArg);
        }
        if (result) {
          return result;
        }
      }
    }
    return undefined;
  };

  /**
   * @abstract
   * @param {module:ol/pixel~Pixel} pixel Pixel.
   * @param {module:ol/PluggableMap~FrameState} frameState FrameState.
   * @param {number} hitTolerance Hit tolerance in pixels.
   * @param {function(this: S, module:ol/layer/Layer, (Uint8ClampedArray|Uint8Array)): T} callback Layer
   *     callback.
   * @param {S} thisArg Value to use as `this` when executing `callback`.
   * @param {function(this: U, module:ol/layer/Layer): boolean} layerFilter Layer filter
   *     function, only layers which are visible and for which this function
   *     returns `true` will be tested for features.  By default, all visible
   *     layers will be tested.
   * @param {U} thisArg2 Value to use as `this` when executing `layerFilter`.
   * @return {T|undefined} Callback result.
   * @template S,T,U
   */
  MapRenderer.prototype.forEachLayerAtPixel = function forEachLayerAtPixel (pixel, frameState, hitTolerance, callback, thisArg, layerFilter, thisArg2) {};

  /**
   * @param {module:ol/coordinate~Coordinate} coordinate Coordinate.
   * @param {module:ol/PluggableMap~FrameState} frameState FrameState.
   * @param {number} hitTolerance Hit tolerance in pixels.
   * @param {function(this: U, module:ol/layer/Layer): boolean} layerFilter Layer filter
   *     function, only layers which are visible and for which this function
   *     returns `true` will be tested for features.  By default, all visible
   *     layers will be tested.
   * @param {U} thisArg Value to use as `this` when executing `layerFilter`.
   * @return {boolean} Is there a feature at the given coordinate?
   * @template U
   */
  MapRenderer.prototype.hasFeatureAtCoordinate = function hasFeatureAtCoordinate (coordinate, frameState, hitTolerance, layerFilter, thisArg) {
    var hasFeature = this.forEachFeatureAtCoordinate(
      coordinate, frameState, hitTolerance, TRUE, this, layerFilter, thisArg);

    return hasFeature !== undefined;
  };

  /**
   * @param {module:ol/layer/Layer} layer Layer.
   * @protected
   * @return {module:ol/renderer/Layer} Layer renderer.
   */
  MapRenderer.prototype.getLayerRenderer = function getLayerRenderer (layer) {
    var this$1 = this;

    var layerKey = getUid(layer).toString();
    if (layerKey in this.layerRenderers_) {
      return this.layerRenderers_[layerKey];
    } else {
      var renderer;
      for (var i = 0, ii = this.layerRendererConstructors_.length; i < ii; ++i) {
        var candidate = this$1.layerRendererConstructors_[i];
        if (candidate['handles'](layer)) {
          renderer = candidate['create'](this$1, layer);
          break;
        }
      }
      if (renderer) {
        this.layerRenderers_[layerKey] = renderer;
        this.layerRendererListeners_[layerKey] = listen(renderer,
          EventType.CHANGE, this.handleLayerRendererChange_, this);
      } else {
        throw new Error('Unable to create renderer for layer: ' + layer.getType());
      }
      return renderer;
    }
  };

  /**
   * @param {string} layerKey Layer key.
   * @protected
   * @return {module:ol/renderer/Layer} Layer renderer.
   */
  MapRenderer.prototype.getLayerRendererByKey = function getLayerRendererByKey (layerKey) {
    return this.layerRenderers_[layerKey];
  };

  /**
   * @protected
   * @return {Object.<string, module:ol/renderer/Layer>} Layer renderers.
   */
  MapRenderer.prototype.getLayerRenderers = function getLayerRenderers () {
    return this.layerRenderers_;
  };

  /**
   * @return {module:ol/PluggableMap} Map.
   */
  MapRenderer.prototype.getMap = function getMap () {
    return this.map_;
  };

  /**
   * Handle changes in a layer renderer.
   * @private
   */
  MapRenderer.prototype.handleLayerRendererChange_ = function handleLayerRendererChange_ () {
    this.map_.render();
  };

  /**
   * @param {string} layerKey Layer key.
   * @return {module:ol/renderer/Layer} Layer renderer.
   * @private
   */
  MapRenderer.prototype.removeLayerRendererByKey_ = function removeLayerRendererByKey_ (layerKey) {
    var layerRenderer = this.layerRenderers_[layerKey];
    delete this.layerRenderers_[layerKey];

    unlistenByKey(this.layerRendererListeners_[layerKey]);
    delete this.layerRendererListeners_[layerKey];

    return layerRenderer;
  };

  /**
   * @param {module:ol/PluggableMap} map Map.
   * @param {module:ol/PluggableMap~FrameState} frameState Frame state.
   * @private
   */
  MapRenderer.prototype.removeUnusedLayerRenderers_ = function removeUnusedLayerRenderers_ (map, frameState) {
    var this$1 = this;

    for (var layerKey in this$1.layerRenderers_) {
      if (!frameState || !(layerKey in frameState.layerStates)) {
        this$1.removeLayerRendererByKey_(layerKey).dispose();
      }
    }
  };

  /**
   * @param {module:ol/PluggableMap~FrameState} frameState Frame state.
   * @protected
   */
  MapRenderer.prototype.scheduleExpireIconCache = function scheduleExpireIconCache (frameState) {
    frameState.postRenderFunctions.push(/** @type {module:ol/PluggableMap~PostRenderFunction} */ (expireIconCache));
  };

  /**
   * @param {!module:ol/PluggableMap~FrameState} frameState Frame state.
   * @protected
   */
  MapRenderer.prototype.scheduleRemoveUnusedLayerRenderers = function scheduleRemoveUnusedLayerRenderers (frameState) {
    var this$1 = this;

    for (var layerKey in this$1.layerRenderers_) {
      if (!(layerKey in frameState.layerStates)) {
        frameState.postRenderFunctions.push(
          /** @type {module:ol/PluggableMap~PostRenderFunction} */ (this$1.removeUnusedLayerRenderers_.bind(this$1))
        );
        return;
      }
    }
  };

  return MapRenderer;
}(Disposable));

/**
 * @param {module:ol/PluggableMap} map Map.
 * @param {module:ol/PluggableMap~FrameState} frameState Frame state.
 */
function expireIconCache(map, frameState) {
  iconImageCache.expire();
}

/**
 * Render.
 * @param {?module:ol/PluggableMap~FrameState} frameState Frame state.
 */
MapRenderer.prototype.renderFrame = UNDEFINED;

/**
 * @param {module:ol/layer/Layer~State} state1 First layer state.
 * @param {module:ol/layer/Layer~State} state2 Second layer state.
 * @return {number} The zIndex difference.
 */
export function sortByZIndex(state1, state2) {
  return state1.zIndex - state2.zIndex;
}
export default MapRenderer;

//# sourceMappingURL=Map.js.map


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30796_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans758.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">WHITING OIL & GAS CORPORATION BARTLESON 34-30-2TFH
420' FSL 8c 1421' FEL
SE 7A; Section 30, T153N, R92W - 5th Principal Meridian 4298 89th Ave NW, New Town, Mountrail County, North Dakota 58763
' DENNIS DILWORTH 81 r V \ LAUREL JOHNSON
HIGHLANDS NO OCCUPIED DWELLINGS WITHIN A ENG'NEER'NGa' 1/4-MILE RADIUS OF THE WELL LOCATION
SURVEYING, PLLC 253 24th Street East m
Dickinson ND 58601 ' PROPOSED ROAD 701.483.2444 office [MSW/V6 ROAD
701.483.2610 fax ENEINEERINE & SURVEYING. PLLI:
WWW-highlandseng-Com SHEET NAME: DATE: SCALE: _, , PROJ, No. SHEET No. DWELLING MAP 09/29/14 1 =2000 146265 9


text:
from pandac.PandaModules import *
from direct.directnotify import DirectNotifyGlobal
from otp.launcher.LauncherBase import LauncherBase
import os
import sys
import time

class LogAndOutput:
    def __init__(self, orig, log):
        self.orig = orig
        self.log = log

    def write(self, str):
        self.log.write(str)
        self.log.flush()
        self.orig.write(str)
        self.orig.flush()

    def flush(self):
        self.log.flush()
        self.orig.flush()

class TTILauncher(LauncherBase):
    notify = DirectNotifyGlobal.directNotify.newCategory('ToontownDummyLauncher')

    def __init__(self):
        self.http = HTTPClient()

        self.logPrefix = 'fellowship-'

        ltime = 1 and time.localtime()
        logSuffix = '%02d%02d%02d_%02d%02d%02d' % (ltime[0] - 2000,  ltime[1], ltime[2],
                                                   ltime[3], ltime[4], ltime[5])

        if not os.path.exists('logs/'):
            os.mkdir('logs/')
            self.notify.info('Made new directory to save logs.')

        logfile = os.path.join('logs', self.logPrefix + logSuffix + '.log')

        log = open(logfile, 'a')
        logOut = LogAndOutput(sys.stdout, log)
        logErr = LogAndOutput(sys.stderr, log)
        sys.stdout = logOut
        sys.stderr = logErr

    def getPlayToken(self):
        return self.getValue('TTI_PLAYCOOKIE')

    def getGameServer(self):
        return self.getValue('TTI_GAMESERVER')

    def setPandaErrorCode(self, code):
        pass

    def getGame2Done(self):
        return True

    def getLogFileName(self):
        return 'toontown'

    def getValue(self, key, default = None):
        return os.environ.get(key, default)

    def setValue(self, key, value):
        os.environ[key] = str(value)

    def getVerifyFiles(self):
        return config.GetInt('launcher-verify', 0)

    def getTestServerFlag(self):
        return self.getValue('IS_TEST_SERVER', 0)

    def isDownloadComplete(self):
        return 1

    def isTestServer(self):
        return 0

    def getPhaseComplete(self, phase):
        return 1

    def startGame(self):
        self.newTaskManager()
        eventMgr.restart()
        from toontown.toonbase import ToontownStart


text:
#include <config.h>

#include "closein.h"

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>

#include "gettext.h"
#define _(msgid) gettext (msgid)

#include "close-stream.h"
#include "closeout.h"
#include "error.h"
#include "exitfail.h"
#include "freadahead.h"
#include "quotearg.h"

static const char *file_name;

/* Set the file name to be reported in the event an error is detected
   on stdin by close_stdin.  See also close_stdout_set_file_name, if
   an error is detected when closing stdout.  */
void
close_stdin_set_file_name (const char *file)
{
  file_name = file;
}

/* Close standard input, rewinding any unused input if stdin is
   seekable.  On error, issue a diagnostic and _exit with status
   'exit_failure'.  Then call close_stdout.

   Most programs can get by with close_stdout.  close_stdin is only
   needed when a program wants to guarantee that partially read input
   from seekable stdin is not consumed, for any subsequent clients.
   For example, POSIX requires that these two commands behave alike:

     (sed -ne 1q; cat) < file
     tail -n +2 file

   Since close_stdin is commonly registered via 'atexit', POSIX
   and the C standard both say that it should not call 'exit',
   because the behavior is undefined if 'exit' is called more than
   once.  So it calls '_exit' instead of 'exit'.  If close_stdin
   is registered via atexit before other functions are registered,
   the other functions can act before this _exit is invoked.

   Applications that use close_stdout should flush any streams other
   than stdin, stdout, and stderr before exiting, since the call to
   _exit will bypass other buffer flushing.  Applications should be
   flushing and closing other streams anyway, to check for I/O errors.
   Also, applications should not use tmpfile, since _exit can bypass
   the removal of these files.

   It's important to detect such failures and exit nonzero because many
   tools (most notably 'make' and other build-management systems) depend
   on being able to detect failure in other tools via their exit status.  */

void
close_stdin (void)
{
  bool fail = false;

  /* There is no need to flush stdin if we can determine quickly that stdin's
     input buffer is empty; in this case we know that if stdin is seekable,
     (fseeko (stdin, 0, SEEK_CUR), ftello (stdin))
     == lseek (0, 0, SEEK_CUR).  */
  if (freadahead (stdin) > 0)
    {
      /* Only attempt flush if stdin is seekable, as fflush is entitled to
         fail on non-seekable streams.  */
      if (fseeko (stdin, 0, SEEK_CUR) == 0 && fflush (stdin) != 0)
        fail = true;
    }
  if (close_stream (stdin) != 0)
    fail = true;
  if (fail)
    {
      /* Report failure, but defer exit until after closing stdout,
         since the failure report should still be flushed.  */
      char const *close_error = _("error closing file");
      if (file_name)
        error (0, errno, "%s: %s", quotearg_colon (file_name),
               close_error);
      else
        error (0, errno, "%s", close_error);
    }

  close_stdout ();

  if (fail)
    _exit (exit_failure);
}


text:
<%- if namespace_name -%>
module <%= module_name %>
<%- end -%>
class <%= plural_class %>Controller < ApplicationController

  layout 'admin'
  respond_to :html, :json

  def index
    @<%= plural_name %> = <%= class_name %>.paginate(page: params[:page], per_page: 10).order('created_at DESC')

    respond_with @<%= plural_name %>
  end

  def show
    @<%= singular_name %> = get_register(params[:id])
    respond_with @<%= singular_name %>
  end

  def new
    @<%= singular_name %> = <%= class_name %>.new

    respond_with @<%= singular_name %>
  end

  def edit
    @<%= singular_name %> = get_register(params[:id])
    respond_with @<%= singular_name %>
  end

  def create
    @<%= singular_name %> = <%= class_name %>.new params[:<%= singular_name %>]

    flash[:notice] = t :<%= singular_name %>_created if @<%= singular_name %>.save
    respond_with @<%= singular_name %>
  end

  def update
    @<%= singular_name %> = get_register(params[:id])

    flash[:notice] = t :<%= singular_name %>_updated if @<%= singular_name %>.update_attributes params[:<%= singular_name %>]
    respond_with @<%= singular_name %>
  end

  def destroy
    @<%= singular_name %> = get_register(params[:id])
    @<%= singular_name %>.destroy

    respond_with @<%= singular_name %>
  end

  private
  def get_register(id)
    <%= class_name %>.find(id)
  end

end
<%- if namespace_name -%>
end
<%- end -%>


text:
import React from 'react';
import PropTypes from 'prop-types';
import { Form, Select, Input, Button, Card } from 'antd';
import PageHeaderLayout from '../PageHeaderLayout';

const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;

class Add extends React.Component {
  static propTypes = {
    form: PropTypes.object.isRequired,
    match: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired,
    add: PropTypes.func.isRequired,
    addResult: PropTypes.object,
    project: PropTypes.object,
    groups: PropTypes.array,
  }

  componentWillReceiveProps(nextProps) {
    const { addResult } = nextProps;
    if (addResult !== this.props.addResult) {
      if (addResult.code === 0) {
        this.props.history.push(`${this.props.match.url}/${addResult.data._id}`);
      }
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { id } = this.props.match.params;
        this.props.add({ ...values, project: id });
      }
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { groups } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 4,
        },
      },
    };
    const prefixSelector = getFieldDecorator('method', {
      initialValue: 'GET',
    })(<Select style={{ width: 70 }}>
      <Option value="GET">GET</Option>
      <Option value="POST">POST</Option>
      <Option value="PUT">PUT</Option>
      <Option value="PATCH">PATCH</Option>
      <Option value="DELETE">DELETE</Option>
    </Select>);
    const { project } = this.props;
    return (
      <PageHeaderLayout
        title={project.name}
      >
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit}>
            <FormItem
              {...formItemLayout}
              label="名称"
            >
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入名称!' }],
              })(<Input placeholder="请输入名称" />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="请求"
            >
              {getFieldDecorator('url', {
                rules: [{ required: true, message: '请输入相对路径,支持路径参数,例如:/api/get/:id' }],
              })(<Input addonBefore={prefixSelector} placeholder="请输入相对路径,支持路径参数,例如:/api/get/:id" />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="分组"
            >
              {getFieldDecorator('group', {
                initialValue: ''
              })(
                <Select
                  placeholder="选择分组"
                >
                  <Option value="" >未分组</Option>
                  {groups.map(item => <Option key={item._id} value={item._id}>{item.name}</Option>)}
                </Select>)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="备注"
            >
              {getFieldDecorator('remark', {
              })(<TextArea placeholder="请输入备注" />)}
            </FormItem>
            <FormItem
              {...tailFormItemLayout}
            >
              <Button type="primary" htmlType="submit">保存</Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}

export default Form.create()(Add);


text:
If you just want to use it then you don't need to do all this; this is just for setting up a complete development environment (on Ubuntu, mostly).

There is also a [docker build file](../docker/mediahubdev/Dockerfile) for a container which covers the same ground.

## Install

You'll need npm, node, coffescript, zurb foundation tool(s), e.g. (ubuntu). N.B. you will need a relatively recent version of node and npm (certainly >0.6) so if you are using an older OS version you may need to download/build node and npm directly from their website(s).
```
sudo apt-get install npm
sudo apt-get install nodejs-legacy
sudo apt-get install couchdb

sudo npm install -g coffee-script

sudo apt-get install ruby1.9.1

sudo gem install compass

sudo npm install -g bower
```
Get dependencies (see package.json):
```
npm install
cd public
bower install
```
Re-generate the CSS from SCSS (if changed, only):
```
cd public
compass compile
```
Export the assembled `public/js/app.js`:
```
coffee build.coffee
```
Set up couchdb CORS: edit (as root) `/etc/couchdb/local.ini` and after `[httpd]` add
```
enable_cors = true
```
and add a section (change origins according to app serving arrangements):
```
[cors]
credentials = true
origins = http://127.0.0.1:9294
methods = GET, PUT, POST, HEAD, DELETE
headers = accept, authorization, content-type, origin
```
Set up some basic authentication - first an administrator:
Edit (as root) `/etc/couchdb/local.ini` and after `[couch_httpd_auth]` add
```
require_valid_user = true
```
and after `[httpd]` add/uncomment
```
WWW-Authenticate = Basic realm="administrator"
```
and at the end of the file add (use your own password :-)
```
[admins]
admin = ADMINPASSWORD
```

Then kick the server:
```
sudo service couchdb restart
```
Now we'll two more generic users, a reader and a writer (although the difference in the latter two will have to be defined by us).
```
curl -HContent-Type:application/json -X PUT http://admin:ADMINPASSWORD@127.0.0.1:5984/_users/org.couchdb.user:hubreader --data-binary '{"_id":"org.couchdb.user:hubreader","type":"user","name":"hubreader","password":"HUBREADERPASSWORD","roles":["hubreader"]}'
curl -HContent-Type:application/json -X PUT http://admin:ADMINPASSWORD@127.0.0.1:5984/_users/org.couchdb.user:hubwriter --data-binary '{"_id":"org.couchdb.user:hubwriter","type":"user","name":"hubwriter","password":"HUBWRITERPASSWORD","roles":["hubwriter"]}'
```
Create the database and add the `hubreader` and `hubwriter` as admins (!! doesn't work as members, failing with 401 on `_temp_view?include_docs=true`):
```
curl -X PUT http://admin:ADMINPASSWORD@127.0.0.1:5984/mediahub
curl -X PUT http://admin:ADMINPASSWORD@127.0.0.1:5984/mediahub/_security --data-binary '{"admins":{"names":["admin"],"roles":["hubwriter"]},"members":{"names":[],"roles":["hubreader"]}}'
```
You can check out how things are going with futon, [http://127.0.0.1:5984/_utils](http://127.0.0.1:5984/_utils)

Also create some accounts for local database access - the static passwords are fine as front-end security will be done in nginx:
```
wget -O- --method=PUT --header=Accept:application/json --header=Content-Type:application/json '--body-data={"_id":"org.couchdb.user:serverreader","type":"user","name":"serverreader","password":"serverreader","roles":["serverreader"]}' http://admin:ADMINPASSWORD@127.0.0.1:5984/_users/org.couchdb.user:serverreader
wget -O- --method=PUT --header=Accept:application/json --header=Content-Type:application/json '--body-data={"_id":"org.couchdb.user:serverwriter","type":"user","name":"serverwriter","password":"serverwriter","roles":["serverwriter"]}' http://admin:ADMINPASSWORD@127.0.0.1:5984/_users/org.couchdb.user:serverwriter
```

Some function presume a web server is also running, e.g. for development try `docker/nginxdev` (see [notes](../docker/deployment.md)).

Background tasks require `tools/taskrunner.coffee` to be running. This can be configured as a couchdb external process, or run directly:
```
cd tools; echo "{}" | coffee taskrunner.coffee
```


text:
'
'  CmdMessenger - library that provides command based messaging
'
'  Permission is hereby granted, free of charge, to any person obtaining
'  a copy of this software and associated documentation files (the
'  "Software"), to deal in the Software without restriction, including
'  without limitation the rights to use, copy, modify, merge, publish,
'  distribute, sublicense, and/or sell copies of the Software, and to
'  permit persons to whom the Software is furnished to do so, subject to
'  the following conditions:
'
'  The above copyright notice and this permission notice shall be
'  included in all copies or substantial portions of the Software.
'
'  Copyright 2013 - Thijs Elenbaas
'
#End Region

Imports Microsoft.VisualBasic
Imports System
Namespace CommandMessenger
	''' <summary> Base command strategy.  </summary>
	Public Class CommandStrategy
		''' <summary> Base command strategy. </summary>
		''' <param name="command"> The command to be wrapped in a strategy. </param>
		Public Sub New(ByVal command As Command)
			Command = command
		End Sub

		''' <summary> Gets or sets the command queue. </summary>
		''' <value> A Queue of commands. </value>
		Private privateCommandQueue As ListQueue
		Public Property CommandQueue() As ListQueue(Of CommandStrategy)
			Get
				Return privateCommandQueue
			End Get
			Set(ByVal value As ListQueue)
				privateCommandQueue = value
			End Set
		End Property

		''' <summary> Gets or sets the run state of the thread. </summary>
		''' <value> The thread run state. </value>
		Private privateThreadRunState As CommandQueue.ThreadRunStates
		Public Property ThreadRunState() As CommandQueue.ThreadRunStates
			Get
				Return privateThreadRunState
			End Get
			Set(ByVal value As CommandQueue.ThreadRunStates)
				privateThreadRunState = value
			End Set
		End Property

		''' <summary> Gets or sets the command. </summary>
		''' <value> The command wrapped in the strategy. </value>
		Private privateCommand As Command
		Public Property Command() As Command
			Get
				Return privateCommand
			End Get
			Private Set(ByVal value As Command)
				privateCommand = value
			End Set
		End Property

		''' <summary> Add command (strategy) to command queue. </summary>
		Public Overridable Sub Enqueue()
			CommandQueue.Enqueue(Me)
		End Sub

		''' <summary> Remove this command (strategy) from command queue. </summary>
		Public Overridable Sub DeQueue()
			CommandQueue.Remove(Me)
		End Sub
	End Class
End Namespace


text:
package net.chwthewke.passman
package engine

import cats.syntax.either._
import java.util.UUID
import org.scalatest.WordSpec
import org.scalatest.Matchers

class PasswordGeneratorSpec extends WordSpec with Matchers with CatsTripleEquals {

  val derivationAlgorithm = Pbkdf2KeyDerivationAlgorithm(0)

  val symbols = "0123456789ABCDEF"

  def testMaterializer(symbols: String, bits: Int): Materializer = {
    Materializer(CharSpace("test", symbols.to[Vector]), Strength("strong", bits, 0, legacy = true))
      .getOrElse(sys.error("Misconfigured materializer"))
  }

  def testPasswordGenerator(symbols: String, bits: Int): PasswordGenerator = {
    val hash = new HashAlgorithm(Pbkdf2KeyDerivationAlgorithm(100000, 64), Pbkdf2KeyDerivationAlgorithm(1000, 64))

    val materializer = testMaterializer(symbols, bits)

    val config = PasswordGenerator.Config(new PasswordGeneratorId(UUID.randomUUID),
                                          PasswordGenerator.Family.Pbkdf2G,
                                          Strength.Strong2017.copy(bits = bits),
                                          new CharSpace("test", symbols))

    new PasswordGenerator(config, derivationAlgorithm, materializer, hash)
  }

  "A PasswordGenerator" when {
    "deriving password" should {
      "create a derived password according to derived key and symbols" in {

        val generator = testPasswordGenerator(symbols, 32)

        val Right(derivedKey)              = derivationAlgorithm.apply("key".toUtf8Bytes, "password", 2, 4)
        val Right(expectedDerivedPassword) = testMaterializer(symbols, 32).apply(derivedKey)

        generator.derivePassword("key", "password", 2) should ===(Either.right(expectedDerivedPassword))
      }
    }

    "bits is 32 and symbols are 16" should {
      val generator = testPasswordGenerator(fakeSymbols(16), 32)

      "create passwords 8 long" in {
        val Right(derivedPassword) = generator.derivePassword("key", "password", 1)
        derivedPassword should have length 8
      }
    }

    "bits is 60 and symbols are 64" should {

      val generator = testPasswordGenerator(fakeSymbols(64), 60)

      "create passwords 10 long" in {
        val Right(derivedPassword) = generator.derivePassword("key", "password", 1)
        derivedPassword should have length 10
      }

    }

    "bits is 55 and symbols are 64" should {

      val generator = testPasswordGenerator(fakeSymbols(64), 55)

      "create passwords 10 long" in {
        val Right(derivedPassword) = generator.derivePassword("key", "password", 1)
        derivedPassword should have length 10
      }

    }

    "bits is 128 and symbols are 91" should {

      val generator = testPasswordGenerator(fakeSymbols(91), 128)

      "create passwords 20 long" in {
        val Right(derivedPassword) = generator.derivePassword("key", "password", 1)
        derivedPassword should have length 20
      }

    }
  }

  private def fakeSymbols(length: Int): String = " " * length

}


text:
Rswag::Ui.configure do |c|

  # List the Swagger endpoints that you want to be documented through the swagger-ui
  # The first parameter is the path (absolute or relative to the UI host) to the corresponding
  # JSON endpoint and the second is a title that will be displayed in the document selector
  # NOTE: If you're using rspec-api to expose Swagger files (under swagger_root) as JSON endpoints,
  # then the list below should correspond to the relative paths for those endpoints

  c.swagger_endpoint '/api-docs/v1/swagger.json', 'API V1 Docs'
end


text:
package io.machinecode.chainlink.core.execution.artifact.listener;

import io.machinecode.chainlink.core.execution.artifact.exception.FailListenException;

import javax.batch.api.chunk.listener.ChunkListener;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Brent Douglas
 * @since 1.0
 */
public class FailAfterChunkListener implements ChunkListener {

    public static final AtomicInteger count = new AtomicInteger(0);

    public static void reset() {
        count.set(0);
    }

    public static int get() {
        return count.get();
    }

    @Override
    public void beforeChunk() throws Exception {
        //
    }

    @Override
    public void onError(final Exception exception) throws Exception {
        //
    }

    @Override
    public void afterChunk() throws Exception {
        count.incrementAndGet();
        throw new FailListenException();
    }
}


text:
MP4Box.prototype.writeBPG = function(pixel_format, bit_depth_luma_minus8, bit_depth_chroma_minus8, width, height, data) {
	if (bit_depth_luma_minus8 !== bit_depth_chroma_minus8) {
		throw "Luma and chroma depths should be the same";
	}
	var stream = new DataStream();
	stream.endianness = DataStream.BIG_ENDIAN;

	stream.writeUint32(0x425047fb); /* file magic */

	var alpha1_flag = 0;
	stream.writeUint8(pixel_format<<5 | alpha1_flag << 4 | bit_depth);

	var color_space = 0;
	var extension_present_flag = 0;
	var alpha2_flag = 0;
	var limited_range_flag = 0;
	var animation_flag = 0;
	stream.writeUint8(color_space<<4 | extension_present_flag << 3 | alpha2_flag << 2 | limited_range_flag << 1 | animation_flag);

	stream.writeUint32(width);
	stream.writeUint32(height);

	stream.writeUint32(data.byteLength);
	if (extension_present_flag !== 0) {
		/* TODO: write extension_data_length and extension_data */
	}

	if (alpha1_flag || alpha2_flag) {
		/* write extra header */
	}
	stream.writeUint32(hevc_header_length);

	return stream.buffer;
}


text:
cask "font-yinmar" do
  version :latest
  sha256 :no_check

  url "https://github.com/google/fonts/raw/main/ofl/yinmar/Yinmar-Regular.ttf",
      verified: "github.com/google/fonts/"
  name "Yinmar"
  homepage "https://fonts.google.com/specimen/Yinmar"

  font "Yinmar-Regular.ttf"
end


text:
import React from 'react';
import {connect} from 'react-redux';
import Home from './Home';
import {staticFiles} from '../../../config';

class HomeContainer extends React.Component {
    render() {
        return <Home/>;
    }

    componentDidMount() {
        // Set src of all img's to it's data-src value (deferred images)
        $('img[data-src]').each(function() {
            this.src = staticFiles + $(this).data("src");
        });

        $('section#about-image div.fill-screen').css("background-image", `url(${staticFiles}/images/beach.jpg)`);

        // Add smooth scrolling animation to the anchors
        $('.nav-anchor, .down-button a').bind('click', function() {
            $('html, body').stop().animate({
                scrollTop: $($(this).attr('href')).offset().top - 100
            }, 1500, 'easeInOutExpo');
            event.preventDefault();
        });

        // Resize header on scroll
        $('body').scrollspy({
            target: '.navbar',
            offset: 160
        });
    }
};

export default connect()(HomeContainer);


text:
Template.jsonView.onRendered(function () {
    this.autorun(() => {
        var json = this.view.lookup('json')();
        var options = this.view.lookup('options')();
        this.$('.json-view').JSONView(json || {}, options || {});
});
});


text:
layout: post
published: true
title: Daemonizing a Python script
---
It's pretty straightforward to daemonize and communicate with a Python script using the PYRO (Python Remoting Objects) library. I found this example on StackOverflow recently and it worked for my purposes.

If you haven't already, setup pip. Then use it to install Pyro.

{% highlight shell %}
$ sudo apt-get install python-pip
$ sudo pip install pyro
{% endhighlight %}

To test the daemon, you'll need two scripts–a client and server. The server acts as the daemon and the client communicates with it.

Server.py:

{% highlight python %}
#!/usr/bin/python
import Pyro.core

class JokeGen(Pyro.core.ObjBase):
        def __init__(self):
                Pyro.core.ObjBase.__init__(self)
        def joke(self, name):
                return "Sorry "+name+", I don't know any jokes."

Pyro.core.initServer()
daemon=Pyro.core.Daemon()
uri=daemon.connect(JokeGen(),"jokegen")

print "The daemon runs on port:",daemon.port
print "The object's uri is:",uri

daemon.requestLoop()
{% endhighlight %}

Client.py:

{% highlight python %}
#!/usr/bin/python

import Pyro.core

# you have to change the URI below to match your own host/port.
jokes = Pyro.core.getProxyForURI("PYROLOC://localhost:7766/jokegen")

print jokes.joke("Irmen")
{% endhighlight %}

[via [http://stackoverflow.com/questions/656933/communicating-with-a-running-python-daemon](http://stackoverflow.com/questions/656933/communicating-with-a-running-python-daemon)]


text:
layout: page
title: "Cameron Wobus"
comments: true
description: "blanks"
keywords: "Cameron Wobus,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: GEOL 3050

#### GEOL 3050: GIS FOR GEOLOGISTS

**Terms taught**: Fall 2008, Spring 2010

**Instructor rating**: 5.54

**Standard deviation in instructor rating**: 0.04

**Average grade** (4.0 scale): 3.37

**Standard deviation in grades** (4.0 scale): 0.02

**Average workload** (raw): 2.64

**Standard deviation in workload** (raw): 0.09


text:
{% load static %}

            © 2016 Knnect.com
            Home