text:
package org.glite.data.common.helpers;

import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.sql.DataSource;

/**
 * Class to manage database connection for the given pool.
 */
public class DBManager {
    /* Log4j logger for class  */
    private final static Logger m_log = Logger.getLogger(DBManager.class);
    protected final String m_db_pool_name;

    // The datasource from which to fetch the connections
    protected final DataSource m_dataSource;

    /**
     * Create a manager for the given poolname. Multiple managers can be active on any one pool. Just like the real
     * thing.
     *
     * @param pool
     * @throws DBException
     */
    public DBManager(String pool) throws DBException {
        m_log.debug("Created new DBManager");

        try {
            m_db_pool_name = pool;

            Context initCtx = new InitialContext();
            m_log.debug("Fetched initial context");

            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            m_log.debug("Fetched envirnoment context");

            // Look up our data source
            m_log.debug("Looking up JNDI datasource: " + m_db_pool_name);

            m_dataSource = (DataSource) envCtx.lookup(m_db_pool_name);
        } catch (NamingException e) {
            m_log.error("Got naming error trying to fetch pool: " + pool, e);
            throw new DBException();
        }
    }

    /**
     * Fetch a cvonnection from the pool.
     *
     * @param autocommit Boolean flag for autocommit
     * @return the connection.
     * @throws org.glite.data.common.helpers.DBException
     *          if a connection cannot be fetched.
     */
    public Connection getConnection(boolean autocommit)
        throws DBException {
        Connection conn;

        try {
            m_log.debug("Trying to get connection wo sync");
            conn = m_dataSource.getConnection();
            m_log.debug("Setting AutoCommit " + (autocommit ? "true" : "false"));

            conn.setAutoCommit(autocommit);
        } catch (SQLException e) {
            m_log.error("Could not get connection to the database from pool: " + m_db_pool_name, e);
            throw new DBException();
        }

        return conn;
    }

    /**
     * Create a basic statement object from the connection.
     *
     * @param conn
     * @return
     * @throws DBException
     */
    public Statement createStatement(Connection conn)
        throws DBException {
        if (conn == null) {
            m_log.error("Trying to create statement on closed connection from pool: " + m_db_pool_name);
            throw new DBException();
        }

        Statement statement;

        try {
            statement = conn.createStatement();
        } catch (SQLException e) {
            m_log.error("Failed to get a statement object from db connection on pool: " + m_db_pool_name, e);
            throw new DBException();
        }

        return statement;
    }

    /**
     * Create a basic statement object from the connection.
     *
     * @param conn
     * @return
     * @throws DBException
     */
    public PreparedStatement prepareStatement(Connection conn, String sqlQuery)
        throws DBException {
        if (conn == null) {
            m_log.error("Trying to create statement on closed connection from pool: " + m_db_pool_name);
            throw new DBException();
        }

        m_log.debug("PrepareStatement SQL query: " + sqlQuery);

        PreparedStatement statement;

        try {
            statement = conn.prepareStatement(sqlQuery);
        } catch (SQLException e) {
            m_log.error("Failed to get a statement object from db connection on pool: " + m_db_pool_name, e);
            throw new DBException();
        }

        return statement;
    }

    /**
     * Rollback a connectiopn and throw an excpetion if it fails.
     *
     * @param conn
     * @throws DBException
     */
    public  void rollback(Connection conn)
        throws DBException {
        try {
            conn.rollback();
        } catch (SQLException e) {
            m_log.error("Error rolling back connection from pool: " + m_db_pool_name, e);
            throw new DBException();
        }
    }

    /**
     * Rollback a connection, returning true on success, false on failure.
     *
     * @param conn
     * @return
     */
    public  boolean rollbackWithResult(Connection conn) {
        try {
            conn.rollback();
        } catch (SQLException e) {
            m_log.error("Error rolling back connection from pool: " + m_db_pool_name, e);

            return false;
        }

        return true;
    }

    /**
     * Rollback, but do not throw any exceptions if the rollback fails. This method should be used sparingly in only
     * cases where you don't care or can't actually do anything if the rollback failed...
     *
     * @param conn
     */
    public  void rollbackRegardless(Connection conn) {
        try {
            conn.rollback();
        } catch (SQLException e) {
            m_log.error("Error reolling back connection from pool: " + m_db_pool_name, e);
        }
    }

    /**
     * Commit a connection, throwing an exception if it fails.
     *
     * @param conn
     * @throws DBException
     */
    public  void commit(Connection conn) throws DBException {
        try {
            conn.commit();
        } catch (SQLException e) {
            m_log.error("Error comitting connection from pool: " + m_db_pool_name, e);
            throw new DBException();
        }
    }

    /**
     * Commit a connection, returning true if it suceeded and false if it failed.
     *
     * @param conn
     * @return
     */
    public  boolean commitWithResult(Connection conn) {
        try {
            conn.commit();
        } catch (SQLException e) {
            m_log.error("Error comitting connection from pool: " + m_db_pool_name, e);

            return false;
        }

        return true;
    }

    /**
     * Commit a connection, but do not throw any exceptions if the commit fails. This method should be used sparingly in
     * only cases where you don't care or can't actually do anything if the commit failed...
     *
     * @param conn
     */
    public  void commitRegardless(Connection conn) {
        try {
            conn.commit();
        } catch (SQLException e) {
            m_log.error("Error comitting connection from pool: " + m_db_pool_name, e);
        }
    }

    /**
     * Cleanup a connection and return to pool. You should cleanup ResultSets and Statements belonging to the Connection
     * first.
     *
     * @param conn
     */
    public  void cleanupResources(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException e) {
            m_log.warn("Error closing Connection on pool: " + m_db_pool_name, e);
        }
    }

    /**
     * Cleanup a Statement. You should cleanup ResultSets belonging to the Statement first.
     *
     * @param st
     */
    public  void cleanupResources(Statement st) {
        try {
            if (st != null) {
                st.close();
                st = null;
            }
        } catch (SQLException e) {
            m_log.warn("Error closing Statement on pool: " + m_db_pool_name, e);
        }
    }

    /**
     * Cleanup ResultSet.
     *
     * @param rs
     */
    public  void cleanupResources(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
        } catch (SQLException e) {
            m_log.warn("Error closing ResultSet on pool: " + m_db_pool_name, e);
        }
    }
}


text:
package com.b2international.snowowl.snomed.validation;

import static com.b2international.snowowl.test.commons.snomed.DocumentBuilders.concept;
import static com.b2international.snowowl.test.commons.snomed.DocumentBuilders.description;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.Collection;
import java.util.Map;
import java.util.UUID;

import org.eclipse.xtext.parser.IParser;
import org.eclipse.xtext.serializer.ISerializer;
import org.eclipse.xtext.validation.IResourceValidator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.b2international.collections.PrimitiveCollectionModule;
import com.b2international.commons.options.Options;
import com.b2international.index.Index;
import com.b2international.index.Indexes;
import com.b2international.index.mapping.Mappings;
import com.b2international.index.query.Expressions.ExpressionBuilder;
import com.b2international.index.revision.BaseRevisionIndexTest;
import com.b2international.index.revision.RevisionIndex;
import com.b2international.snowowl.core.ComponentIdentifier;
import com.b2international.snowowl.core.domain.BranchContext;
import com.b2international.snowowl.core.internal.validation.ValidationRepository;
import com.b2international.snowowl.core.internal.validation.ValidationThreadPool;
import com.b2international.snowowl.core.validation.ValidationRequests;
import com.b2international.snowowl.core.validation.eval.ValidationRuleEvaluator;
import com.b2international.snowowl.core.validation.issue.ValidationIssue;
import com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtension;
import com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtensionProvider;
import com.b2international.snowowl.core.validation.issue.ValidationIssues;
import com.b2international.snowowl.core.validation.rule.ValidationRule;
import com.b2international.snowowl.core.validation.rule.ValidationRule.Severity;
import com.b2international.snowowl.core.validation.whitelist.ValidationWhiteList;
import com.b2international.snowowl.datastore.request.RevisionIndexReadRequest;
import com.b2international.snowowl.snomed.SnomedConstants.Concepts;
import com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants;
import com.b2international.snowowl.snomed.core.ecl.DefaultEclParser;
import com.b2international.snowowl.snomed.core.ecl.DefaultEclSerializer;
import com.b2international.snowowl.snomed.core.ecl.EclParser;
import com.b2international.snowowl.snomed.core.ecl.EclSerializer;
import com.b2international.snowowl.snomed.datastore.id.RandomSnomedIdentiferGenerator;
import com.b2international.snowowl.snomed.datastore.index.entry.SnomedConceptDocument;
import com.b2international.snowowl.snomed.datastore.index.entry.SnomedDescriptionIndexEntry;
import com.b2international.snowowl.snomed.ecl.EclStandaloneSetup;
import com.b2international.snowowl.test.commons.snomed.TestBranchContext;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Injector;

/**
 * @since 6.0
 */
public class SnomedQueryValidationRuleEvaluatorTest extends BaseRevisionIndexTest {

	private static final Injector INJECTOR = new EclStandaloneSetup().createInjectorAndDoEMFRegistration();

	/**
	 * Usage of this class intended for testing purposes only
	 */
	private static final class TestValidationDetailExtension implements ValidationIssueDetailExtension {

		@Override
		public void prepareQuery(ExpressionBuilder queryBuilder, Options options) {}

		@Override
		public void extendIssues(BranchContext context, Collection<ValidationIssue> issue) {}

		@Override
		public String getToolingId() {
			return SnomedQueryValidationRuleEvaluatorTest.TOOLING_ID;
		}

	}

	private BranchContext context;
	private SnomedQueryValidationRuleEvaluator evaluator;
	private ValidationRepository repository;

	private static final String TOOLING_ID = "toolingId";

	@Override
	protected Collection<Class<?>> getTypes() {
		return ImmutableList.of(SnomedConceptDocument.class, SnomedDescriptionIndexEntry.class);
	}

	@Override
	protected void configureMapper(ObjectMapper mapper) {
		super.configureMapper(mapper);
		mapper.setSerializationInclusion(Include.NON_NULL);
		mapper.registerModule(new PrimitiveCollectionModule());
	}

	@Before
	public void setup() {
		super.setup();
		final Index index = Indexes.createIndex(UUID.randomUUID().toString(), getMapper(), new Mappings(ValidationRule.class, ValidationIssue.class, ValidationWhiteList.class));
		repository = new ValidationRepository(index);
		context = TestBranchContext.on(MAIN)
				.with(ObjectMapper.class, getMapper())
				.with(EclParser.class, new DefaultEclParser(INJECTOR.getInstance(IParser.class), INJECTOR.getInstance(IResourceValidator.class)))
				.with(EclSerializer.class, new DefaultEclSerializer(INJECTOR.getInstance(ISerializer.class)))
				.with(Index.class, rawIndex())
				.with(RevisionIndex.class, index())
				.with(ValidationThreadPool.class, new ValidationThreadPool(1, 1, 1))
				.with(ValidationRepository.class, repository)
				.build();
		evaluator = new SnomedQueryValidationRuleEvaluator();
		if (!ValidationRuleEvaluator.Registry.types().contains(evaluator.type())) {
			ValidationRuleEvaluator.Registry.register(evaluator);
		}

		ValidationIssueDetailExtensionProvider extensionProvider = ValidationIssueDetailExtensionProvider.INSTANCE;
		extensionProvider.addExtension(new TestValidationDetailExtension());

	}

	@After
	public void teardown() {
		super.teardown();
		repository.dispose();
	}

	@Test
	public void conceptRuleEclSingleConcept() throws Exception {
		final String concept1 = RandomSnomedIdentiferGenerator.generateConceptId();
		final String concept2 = RandomSnomedIdentiferGenerator.generateConceptId();
		indexRevision(MAIN, STORAGE_KEY1, concept(concept1).build());
		indexRevision(MAIN, STORAGE_KEY2, concept(concept2).build());

		final Map<String, Object> ruleQuery = ImmutableMap.<String, Object>builder()
				.put("componentType", "concept")
				.put("ecl", concept1)
				.build();

		final String ruleId = createSnomedQueryRule(ruleQuery);

		final ValidationIssues issues = validate(ruleId);

		assertThat(issues.getTotal()).isEqualTo(1);
		assertThat(issues.getItems().get(0).getAffectedComponent()).isEqualTo(ComponentIdentifier.of(SnomedTerminologyComponentConstants.CONCEPT_NUMBER, concept1));
	}

	@Test
	public void conceptRuleActiveAndModuleFilter() throws Exception {
		final String concept1 = RandomSnomedIdentiferGenerator.generateConceptId();
		final String concept2 = RandomSnomedIdentiferGenerator.generateConceptId();
		final String concept3 = RandomSnomedIdentiferGenerator.generateConceptId();
		indexRevision(MAIN, STORAGE_KEY1, concept(concept1).moduleId(Concepts.MODULE_B2I_EXTENSION).build());
		indexRevision(MAIN, STORAGE_KEY2, concept(concept2).active(false).moduleId(Concepts.MODULE_B2I_EXTENSION).build());
		indexRevision(MAIN, nextStorageKey(), concept(concept3).active(false).moduleId(Concepts.MODULE_SCT_CORE).build());

		final Map<String, Object> ruleQuery = ImmutableMap.<String, Object>builder()
				.put("componentType", "concept")
				.put("active", true)
				.put("module", Concepts.MODULE_B2I_EXTENSION)
				.build();

		final String ruleId = createSnomedQueryRule(ruleQuery);
		final ValidationIssues issues = validate(ruleId);

		assertThat(issues.getTotal()).isEqualTo(1);
		assertThat(issues.getItems().get(0).getAffectedComponent()).isEqualTo(ComponentIdentifier.of(SnomedTerminologyComponentConstants.CONCEPT_NUMBER, concept1));

	}

	@Test
	public void descriptionRuleRegex() throws Exception {
		final String description1 = RandomSnomedIdentiferGenerator.generateDescriptionId();
		final String description2 = RandomSnomedIdentiferGenerator.generateDescriptionId();

		indexRevision(MAIN, STORAGE_KEY1, description(description1, Concepts.SYNONYM, "Minor heart attack").build());
		indexRevision(MAIN, STORAGE_KEY2, description(description2, Concepts.SYNONYM, "Clinical finding").build());

		final Map<String, Object> ruleQuery = ImmutableMap.<String, Object>builder()
				.put("componentType", "description")
				.put("term", "regex(.*heart.*)")
				.build();

		final String ruleId = createSnomedQueryRule(ruleQuery);
		final ValidationIssues issues = validate(ruleId);

		assertThat(issues.getTotal()).isEqualTo(1);
		assertThat(issues.getItems().get(0).getAffectedComponent()).isEqualTo(ComponentIdentifier.of(SnomedTerminologyComponentConstants.DESCRIPTION_NUMBER, description1));
	}

	@Test
	public void descriptionRuleEmptySemanticTag() throws Exception {
		final String description1 = RandomSnomedIdentiferGenerator.generateDescriptionId();
		final String description2 = RandomSnomedIdentiferGenerator.generateDescriptionId();

		indexRevision(MAIN, STORAGE_KEY1, description(description1, Concepts.SYNONYM, "Minor heart attack").build());
		indexRevision(MAIN, STORAGE_KEY2, description(description2, Concepts.SYNONYM, "Clinical finding (finding)").build());

		final Map<String, Object> ruleQuery = ImmutableMap.<String, Object>builder()
				.put("componentType", "description")
				.put("semanticTag", "")
				.build();

		final String ruleId = createSnomedQueryRule(ruleQuery);
		final ValidationIssues issues = validate(ruleId);

		assertThat(issues.getTotal()).isEqualTo(1);
		assertThat(issues.getItems().get(0).getAffectedComponent()).isEqualTo(ComponentIdentifier.of(SnomedTerminologyComponentConstants.DESCRIPTION_NUMBER, description1));
	}

	@Test
	public void descriptionAcceptableInAndPreferredIn() throws Exception {
		final String description1 = RandomSnomedIdentiferGenerator.generateDescriptionId();
		final String description2 = RandomSnomedIdentiferGenerator.generateDescriptionId();
		final String langRefSet1 = RandomSnomedIdentiferGenerator.generateConceptId();
		final String langRefSet2 = RandomSnomedIdentiferGenerator.generateConceptId();

		indexRevision(MAIN, STORAGE_KEY1, description(description1, Concepts.SYNONYM, "Minor heart attack")
				.acceptableIn(ImmutableSet.of(langRefSet1))
				.preferredIn(ImmutableSet.of(langRefSet2))
				.build());
		indexRevision(MAIN, STORAGE_KEY2, description(description2, Concepts.SYNONYM, "Clinical finding (finding)")
				.acceptableIn(ImmutableSet.of(langRefSet1))
				.build());

		final Map<String, Object> ruleQuery = ImmutableMap.<String, Object>builder()
				.put("componentType", "description")
				.put("acceptableIn", ImmutableList.of(langRefSet1))
				.put("preferredIn", ImmutableList.of(langRefSet2))
				.build();

		final String ruleId = createSnomedQueryRule(ruleQuery);
		final ValidationIssues issues = validate(ruleId);

		assertThat(issues.getTotal()).isEqualTo(1);
		assertThat(issues.getItems().get(0).getAffectedComponent()).isEqualTo(ComponentIdentifier.of(SnomedTerminologyComponentConstants.DESCRIPTION_NUMBER, description1));
	}

	private ValidationIssues validate(final String ruleId) {
		new RevisionIndexReadRequest<>(ValidationRequests.prepareValidate().build()).execute(context);
		return ValidationRequests.issues().prepareSearch()
			.all()
			.filterByRule(ruleId)
			.build()
			.execute(context);
	}

	private String createSnomedQueryRule(final Map<String, Object> ruleQuery) throws JsonProcessingException {
		return ValidationRequests.rules().prepareCreate()
			.setType(evaluator.type())
			.setMessageTemplate("Error")
			.setSeverity(Severity.ERROR)
			.setImplementation(context.service(ObjectMapper.class).writeValueAsString(ruleQuery))
			.setToolingId(TOOLING_ID)
			.build()
			.execute(context);
	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.jbpm.simulation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.drools.core.time.SessionPseudoClock;
import org.jbpm.simulation.impl.SimulationPath;
import org.jbpm.simulation.impl.ht.StaffPoolManager;

public class SimulationContext {

    protected static InheritableThreadLocal<SimulationContext> simulationContextThreadLocal = new InheritableThreadLocal<SimulationContext>();

    private SimulationRegistry registry;
    private SimulationRepository repository;
    private SimulationDataProvider dataProvider;
    private SimulationPath currentPath;
    private long startTime;
    private SessionPseudoClock clock;
    private StaffPoolManager staffPoolManager;
    private long maxEndTime;
    private List<String> executedNodes = new ArrayList<String>();
    private int loopLimit = 2;
    private long processInstanceId;

    public static SimulationContext getContext() {
        return simulationContextThreadLocal.get();
    }

    public static void setContext(SimulationContext context) {
        simulationContextThreadLocal.set(context);
    }

    public SimulationRepository getRepository() {
        return repository;
    }

    public SimulationRegistry getRegistry() {
        return registry;
    }

    protected void setRepository(SimulationRepository repository) {
        this.repository = repository;
    }

    protected void setRegistry(SimulationRegistry registry) {
        this.registry = registry;
    }

    public SimulationPath getCurrentPath() {
        return currentPath;
    }

    public void setCurrentPath(SimulationPath currentPath) {
        this.currentPath = currentPath;
    }

    public long getStartTime() {
        return startTime;
    }

    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    public SimulationDataProvider getDataProvider() {
        return dataProvider;
    }

    public void setDataProvider(SimulationDataProvider dataProvider) {
        this.dataProvider = dataProvider;
    }

    public SessionPseudoClock getClock() {
        return clock;
    }

    public void setClock(SessionPseudoClock clock) {
        this.clock = clock;
    }

    public StaffPoolManager getStaffPoolManager() {
        return staffPoolManager;
    }

    public void setStaffPoolManager(StaffPoolManager staffPoolManager) {
        this.staffPoolManager = staffPoolManager;
    }

    public long getMaxEndTime() {
        return maxEndTime;
    }

    public void setMaxEndTime(long maxEndTime) {
        if (maxEndTime > this.maxEndTime) {
            this.maxEndTime = maxEndTime;
        }
    }

    public void resetMaxEndTime() {
        this.maxEndTime = -1;
    }

    public List<String> getExecutedNodes() {
        return executedNodes;
    }

    public void setExecutedNodes(List<String> executedNodes) {
        this.executedNodes = executedNodes;
    }

    public void addExecutedNode(String node) {

        this.executedNodes.add(node);
    }

    public boolean isLoopLimitExceeded(String node) {
        int currentCount = Collections.frequency(executedNodes, node);
        return currentCount >= loopLimit;
    }

    public long getProcessInstanceId() {
        return processInstanceId;
    }

    public void setProcessInstanceId(long processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    public void incrementProcessInstanceId() {
        this.processInstanceId++;
    }
}


text:
package com.shzisg.generator.processor;

import com.shzisg.generator.config.ColumnConfig;
import com.shzisg.generator.output.DomainDefine;
import com.shzisg.generator.output.EntityDefine;
import com.shzisg.generator.output.PropertyDefine;

public class JsonProcessor implements Processor {

    @Override
    public DomainDefine process(DomainDefine domainDefine) {
        if (!domainDefine.isJackson()) {
            return domainDefine;
        }
        for (EntityDefine define : domainDefine.getEntities()) {
            for (PropertyDefine prop : define.getProperties()) {
                ColumnConfig config = prop.getColumnConfig();
                if (config.isIgnore()) {
                    define.addImport("com.fasterxml.jackson.annotation.JsonIgnore");
                    prop.addDecorator("@JsonIgnore");
                }
            }
        }
        return domainDefine;
    }
}


text:
<?php

declare(strict_types=1);

namespace Sphp\Foundation\Sites\Grids;

use Sphp\Html\AbstractComponent;
use Sphp\Html\PlainContainer;
use Traversable;

/**
 * Implements an XY Grid Row
 *
 * @author  Sami Holck <sami.holck@gmail.com>
 * @link    https://foundation.zurb.com/ Foundation
 * @link    https://foundation.zurb.com/sites/docs/xy-grid.html XY Grid
 * @license https://opensource.org/licenses/MIT The MIT License
 * @filesource
 */
abstract class AbstractRow extends AbstractComponent implements \IteratorAggregate, Row {

  /**
   * @var PlainContainer
   */
  private $columns;

  /**
   * Constructor
   *
   * @param string $tagname
   */
  public function __construct(string $tagname = 'div') {
    parent::__construct($tagname);
    $this->columns = new PlainContainer();
    $this->cssClasses()->protectValue('grid-x');
  }

  public function setLayouts(...$layout) {
    foreach (is_array($layout) ? $layout : [$layout] as $width) {
      $parts = explode('-', $width);
    }
    return $this;
  }

  /**
   * Unsets all layout settings
   *
   * @return $this for a fluent interface
   */
  public function unsetLayouts() {
    foreach (Foundation::sizes() as $screenSize) {
      $this->reset($screenSize);
    }
    return $this;
  }

  /**
   *
   * @param  bool $margin
   * @return $this for a fluent interface
   */
  public function useMargin(bool $margin = true) {
    if ($margin) {
      $this->cssClasses()->add('grid-margin-x');
    } else {
      $this->cssClasses()->remove('grid-margin-x');
    }
    return $this;
  }

  /**
   *
   * @param  bool $padding
   * @return $this for a fluent interface
   */
  public function usePadding(bool $padding = true) {
    if ($padding) {
      $this->cssClasses()->add('grid-padding-x');
    } else {
      $this->cssClasses()->remove('grid-padding-x');
    }
    return $this;
  }

  /**
   * Sets the block grid value of the given target screen types
   *
   * @precondition `$screenSize` == `small|medium|large|xlarge|xxlarge`
   * @param  string $screenSize the target screen size
   * @return $this for a fluent interface
   */
  public function collapse(string $screenSize) {
    $this->reset($screenSize);
    $this->cssClasses()->add("$screenSize-collapse");
    return $this;
  }

  /**
   * Sets the block grid value of the given target screen types
   *
   * @precondition `$screenSize` == `small|medium|large|xlarge|xxlarge`
   * @param  string $screenSize the target screen size
   * @return $this for a fluent interface
   */
  public function uncollapse(string $screenSize) {
    $this->reset($screenSize);
    $this->cssClasses()->add("$screenSize-uncollapse");
    return $this;
  }

  /**
   * Unsets the block grid setting for the given screen widths
   *
   * @precondition `$screenSize` == `medium|large|xlarge|xxlarge`
   * @param  string $screenSize the target screen size
   * @return $this for a fluent interface
   */
  public function reset(string $screenSize) {
    $classes = [];
    $classes[] = "$screenSize-collapse";
    $classes[] = "$screenSize-uncollapse";
    $this->cssClasses()->remove($classes);
    return $this;
  }

  public function setCells($columns) {
    if (!is_array($columns)) {
      $columns = [$columns];
    }

    $this->columns->clear();
    //print_r($sType);
    foreach ($columns as $column) {
      if ($column instanceof Cell) {
        $this->append($column);
      } else {
        $this->appendCell($column);
      }
    }
    return $this;
  }

  public function append(Cell $column) {
    $this->columns->append($column);
    return $this;
  }

  public function prepend(Cell $column) {
    $this->columns->prepend($column);
    return $this;
  }

  public function appendCell($content): Cell {
    $cell = new ContainerCell($content);
    $this->append($cell);
    return $cell;
  }

  public function appendMdColumn($md): Cell {
    $cell = new ContainerCell();
   // $cell->layout()->setLayouts($sizes);
    $cell->appendMd($md);
    $this->append($cell);
    return $cell;
  }

  /**
   * Create a new iterator to iterate through Row content
   *
   * @return Traversable iterator
   */
  public function getIterator(): Traversable {
    return $this->columns->getIterator();
  }

  public function contentToString(): string {
    return $this->columns->getHtml();
  }

}


text:
package uphold

// TODO: Write tests for Transaction endpoint


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>Table of Contents - RDoc Documentation</title>

<link href="./fonts.css" rel="stylesheet">
<link href="./rdoc.css" rel="stylesheet">

Table of Contents - RDoc Documentation

Classes and Modules

    Thing

Methods

    ::new
    —
    Thing

    #message
    —
    Thing

    #word_match?
    —
    Thing

Validate

Generated by RDoc 4.1.1.

Based on Darkfish by Michael Granger.


text:
namespace content {

ShellContentClient::~ShellContentClient() {
}

void ShellContentClient::SetActiveURL(const GURL& url) {
}

void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}

void ShellContentClient::AddPepperPlugins(
    std::vector<content::PepperPluginInfo>* plugins) {
}

void ShellContentClient::AddNPAPIPlugins(
    webkit::npapi::PluginList* plugin_list) {
}

bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
  return false;
}

bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
  return false;
}

std::string ShellContentClient::GetUserAgent(bool* overriding) const {
  *overriding = false;
  return std::string("Chrome/15.16.17.18");
}

string16 ShellContentClient::GetLocalizedString(int message_id) const {
  return string16();
}

base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
  return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id);
}

#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
                                       sandbox::TargetPolicy* policy) {
  return false;
}
#endif

#if defined(OS_MACOSX)
bool ShellContentClient::GetSandboxProfileForSandboxType(
    int sandbox_type,
    int* sandbox_profile_resource_id) const {
  return false;
}
#endif

}  // namespace content


text:
<?php

namespace PHPExiftool\Driver\Tag\XMPPrism;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class KillDateDate extends AbstractTag
{

    protected $Id = 'killDateDate';

    protected $Name = 'KillDateDate';

    protected $FullName = 'XMP::prism';

    protected $GroupName = 'XMP-prism';

    protected $g0 = 'XMP';

    protected $g1 = 'XMP-prism';

    protected $g2 = 'Document';

    protected $Type = 'date';

    protected $Writable = true;

    protected $Description = 'Kill Date Date';

    protected $local_g2 = 'Time';

}


text: A Visual Studio Code extension for the textX language support.


text:
> This is the article repertory for my blog addressed at www.sjming.net

### Book list
* Programming
    * [ ] 程序是怎么跑起来的
* Deep Learning
    * [ ] caffe源代码
    * [x] neuralnetworksanddeeplearning中文版
    * [x] 21天实战caffe


text:
<?php

namespace Welcomebac\StatistiquesBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

/**
 *
 * @author Gaetan Hautecoeur
 */
class ControllerListener
{
    public function __construct()
    {
    }
    public function onKernelController(FilterControllerEvent $event)
    {
    	/*
        $request = $event->getRequest();
        if($request->attributes->get("_stats")){
        	echo $request->attributes->get("_stats");
        }
        */
    }
}


text:
test/test_app.bat
version = "1.2.1"
build_hour = "11H00"

echo "Build ${build_hour}"
echo "version ${version}"


text:
package featureswitch.api.controllers

import featureswitch.api.services.FeatureSwitchService
import featureswitch.core.config.FeatureSwitching
import featureswitch.core.models.FeatureSwitchSetting
import play.api.Configuration
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent, InjectedController}

import javax.inject.{Inject, Singleton}

@Singleton
class FeatureSwitchApiController @Inject()(config: Configuration,
                                           featureSwitchService: FeatureSwitchService
                                          ) extends InjectedController with FeatureSwitching {
  def getFeatureSwitches: Action[AnyContent] = Action {
    Ok(Json.toJson(featureSwitchService.getFeatureSwitches))
  }

  def updateFeatureSwitches(): Action[Seq[FeatureSwitchSetting]] = Action(parse.json[Seq[FeatureSwitchSetting]]) {
    req =>
      val updatedFeatureSwitches = featureSwitchService.updateFeatureSwitches(req.body)
      Ok(Json.toJson(updatedFeatureSwitches))
  }

}


text:
var APIPATH = getSitePath() + "api/";
var FORMSPATH = getSitePath() + "forms/";

// Returns the base URL of the website, assuming that this script is in the '/js' subdirectory of the site.
function getSitePath() {
    var scripts = document.getElementsByTagName('script'),
        script = scripts[scripts.length - 1];

    if (script.getAttribute.length !== undefined) {
		scriptPath = script.src;
    }

    scriptPath = script.getAttribute('src', -1);

	var basePath = scriptPath.substr(0, scriptPath.lastIndexOf( '/js' )+1 );
	return basePath;
}

function getTemplateAjax(path) {
	var source;
	var template;
	$.ajax({
		url: path, //ex. js/templates/mytemplate.handlebars
		async: false,
		success: function(data) {
			source    = data;
			template  = Handlebars.compile(source);
		}
	});
	return template;
}

function formatCurrency(val) {
	var s = val.toString();
	if (s.indexOf('.') == -1) s += '.';
	while (s.length < s.indexOf('.') + 3) s += '0';
	return s;
}

function formatPhone(num) {
	num = num.replace(/[^0-9]/, '', num);
	var len = num.length;
	if(len == 7)
	num = num.replace(/([0-9]{3})([0-9]{4})/, '$1-$2');
	else if(len == 10)
	num = num.replace(/([0-9]{3})([0-9]{3})([0-9]{4})/, '($1) $2-$3');
	return num;
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

function isValidPhone(phone) {
	var pattern = new RegExp(/^[0-9\-\(\)\s]+/i);
	return pattern.test(phone);
}

function isValidDate(date) {
	var pattern = new RegExp(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}/i);
	return pattern.test(date);
}

function isValidTime(time) {
	var pattern = new RegExp(/^[0-9]{1,2}:[0-9]{2} [am|pm]/i);
	return pattern.test(time);
}

// Converts SQL datetime of the form YYYY-MM-DD HH:MM:SS into milliseconds
// Assumes we are using the datejs extension to Date
function sqlDateToMilliseconds(sqlDateStr) {
	sqlDateStr = sqlDateStr.replace(/ /g,"T");
	return Date.parse(sqlDateStr).getTime();
}

// Convert milliseconds into a Javascript date object
function millisecondsToDate(sqlDateStr) {
	var msTime = sqlDateToMilliseconds(sqlDateStr);
	var dateTime = new Date();
	dateTime.setTime(msTime);
	return dateTime;
}

function formatDate1(stamp) {
	var formatted = {};
	formatted['stamp'] = stamp;
	var dateTime = new Date(stamp);
	formatted['date'] = dateTime.toString("MMM dS, yyyy");
	formatted['day'] = dateTime.toString("dddd");
	formatted['time'] = dateTime.toString("h:mm tt");
	return formatted;
}

function toTitleCase(str) {
    if (str.match(/^[A-Z]*$/)) {
		return str;
	} else {
		return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	}
}

// Get the value of a URI parameter from the current page by name.
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Find an object in an array of objects that has the corresponding field value
function findObjectByField(arr, field_value, field_name){
	field_name = typeof field_name !== 'undefined' ? field_name : "id";
	var item = null;
	jQuery.each(arr, function (a,b){
		if (b[field_name] == field_value){
			item = b;
		}
	});
	return item;
}

function getKeys(obj) {
	var keys = [];
	$.each( obj, function( key, value ) {
		keys.push(key);
	});
	return keys;
}

// Create an old-fashion html style select dropdown with typeahead capability
function typeaheadDropdown(typeahead_element, suggestions, suggestion_render_template, options) {
	var default_id = false;
	var disabled = false;
	if (options['default_id'])
		default_id = options['default_id'];
	if (options['disabled'])
		disabled = options['disabled'];

	var template = Handlebars.compile(suggestion_render_template);
	// Enable item
	//jQuery.fn._typeahead.noConflict();
	// Test array: var colors = ["red", "blue", "green", "yellow", "brown", "black"];
	$(typeahead_element).typeahead({
		//name: classLabel,     // Update 2/19/2014: remove name to keep typeahead from caching data
		minLength: 0,
		limit: 100,
        highlight: true,
		local: suggestions,
		template: template,
		engine: Handlebars
	}).on('typeahead:closed', function (object, datum) {
		// Check to make sure that the inputted value is in the list of values.  If so, set the hidden -id field to the corresponding id
		var found = false;
		jQuery.each(suggestions, function(idx, item) {
			// Match the item name against the suggestions list
			if (item['name'].toLowerCase() == $(typeahead_element).val().toLowerCase())
				found = item;
		});
		if (found ) {
			// Set the selected hidden id and trigger the "change" event
			var selected_id = found['id'];
			$(typeahead_element).data("selected_id", selected_id).trigger('change');
		} else {
			$(typeahead_element).typeahead('setQuery', "");
		}

	});

	// Set default value if specified
	if (default_id) {
		// Look for name
		var found = false;
		jQuery.each(suggestions, function(idx, item) {
			// Match the item name against the suggestions list
			if (item['id'] == default_id)
				found = item;
		});
		if (found ) {
			// Set the selected hidden id and trigger the "change" event
			var selected_id = found['id'];
			$(typeahead_element).typeahead('setQuery', found['name']);
			$(typeahead_element).data("selected_id", selected_id).trigger('change');
		} else {
			$(typeahead_element).typeahead('setQuery', "");
		}
	}
	// Disable if specified
	if (disabled) {
		$(typeahead_element).typeahead('destroy');
		$(typeahead_element).prop('disabled', true);
	}
}

function validateFormFields(dialog_id) {
	// Check all input fields
	var errorMessages = [];
	var $fields = $('#' + dialog_id + ' .form-control');
	$fields.each(function(idx, input) {
		// Get handle for closest input-group indicator
		var closestGroup = $( this ).closest('.input-group');
		// Skip disabled fields
		if ($(this).prop('disabled')) {
			console.log("Field " + $(this).prop("name") + "is disabled");
			return;  //this is equivalent of 'continue' for jQuery loop
		}
		// Get field value
		var val = "";
		// Check that radio box has one option selected
		if ($( this ).attr('type') == "radio") {
			var checkedOption = $('input[name="' + input.name + '"]' ).filter(':checked');
			if (checkedOption.length != 0)
				val = checkedOption.val();
			console.log(val);
		} else {
			val = input.value;
		}
		console.log("validating field: " + input.name + "='" + val + "'");
		var fieldErrors = 0;
		// Get validation metadata
		var validationData = $(this).data('validate');
		if (validationData){
			// If no field label specified, use a generic label
			var label = "One of the fields";
			if (validationData.label) {
				label = validationData.label;
			}
			// Skip blank, optional fields
			if (!(validationData.optional && val == "")) {
				if (validationData.minLength && validationData.maxLength) {
					if (val.length < validationData.minLength || val.length > validationData.maxLength) {
						errorMessages.push("'" + label + "' must be between " + validationData.minLength + " and " + validationData.maxLength + " characters long.");
						fieldErrors += 1;
					}
				}
				if (validationData.minLength && !validationData.maxLength) {
					if (val.length < validationData.minLength) {
						errorMessages.push("'" + label + "' must be at least " + validationData.minLength + " characters long.");
						fieldErrors += 1;
					}
				}
				if (!validationData.minLength && validationData.maxLength) {
					if (val.length > validationData.maxLength) {
						errorMessages.push("'" + label + "' must be at most " + validationData.maxLength + " characters long.");
						fieldErrors += 1;
					}
				}
				if (validationData.email) {
					if (!isValidEmailAddress(val)) {
						errorMessages.push("'" + label + "' must be a valid email address.");
						fieldErrors += 1;
					}
				}
				if (validationData.number) {
					if (isNaN(val) || val == "") {
						errorMessages.push("'" + label + "' must be a number.");
						fieldErrors += 1;
					}
				}
				if (validationData.phone) {
					if (!isValidPhone(val)) {
						errorMessages.push("'" + label + "' must be a valid phone number.");
						fieldErrors += 1;
					}
				}
				if (validationData.date) {
					if (!isValidDate(val)) {
						errorMessages.push("'" + label + "' must be a date in the format mm/dd/yyyy.");
						fieldErrors += 1;
					}
				}
				if (validationData.time) {
					if (!isValidTime(val)) {
						errorMessages.push("'" + label + "' must be a time in the format h:mm am or h:mm pm.");
						fieldErrors += 1;
					}
				}
				if (validationData.selected) {
					var msg = "You must select an option for '" + label + "'.";
					if (val == "") {
						if ($.inArray(msg, errorMessages) == -1) {
							errorMessages.push(msg);
						}
						fieldErrors += 1;
					}
				}
				if (validationData.passwordMatch) {
					var other = $('#' + dialog_id + ' input[name="' + validationData.passwordMatch + '"]');
					if (val != other.val()) {
						errorMessages.push("Passwords must match!");
						fieldErrors += 1;
					}
				}
			}
		}
		if (fieldErrors > 0) {
			closestGroup.addClass('has-error');
			closestGroup.removeClass('has-success');
		} else {
			closestGroup.removeClass('has-error');
			closestGroup.addClass('has-success');
		}
	});
	//console.log(errorMessages);
	return errorMessages;
}

function loadCurrentUser() {
	var url = APIPATH + 'load_current_user.php';
	var result = $.ajax({
	  type: "GET",
	  url: url,
	  async: false
	}).responseText;
	var resultJSON = processJSONResult(result);

	if (resultJSON['user_id']) {
		return resultJSON;
	} else {
		addAlert("danger", "We couldn't load your account. We'll try to get this fixed right away!");
		window.location.replace('logout.php');
		return;
	}
}
function loadCurrentUserPhone() {
	var url = APIPATH + 'load_current_user_phone.php';
	var result = $.ajax({
	  type: "GET",
	  url: url,
	  async: false
	}).responseText;
  //alert(result);
  if(result){
	var resultJSON = processJSONResult(result);}
else
{
  var resultJSON=array();
}
	if (resultJSON['phoneNum']) {
		return resultJSON;
	} else {
    resultJSON['phoneNum']=" ";
		return resultJSON;
	}
}
function loadCurrentUserAddr() {
	var url = APIPATH + 'load_current_user_addr.php';
	var result = $.ajax({
	  type: "GET",
	  url: url,
	  async: false
	}).responseText;
  //alert(result);
  if(result){
	var resultJSON = processJSONResult(result);}
  else{
    var resultJSON=array();
  }

	if (resultJSON['address']) {
		return resultJSON;
	} else {
	resultJSON['address']=' ';
		return resultJSON;
	}
}
function loadCurrentUserEmp() {
	var url = APIPATH + 'load_current_user_emp.php';
	var result = $.ajax({
	  type: "GET",
	  url: url,
	  async: false
	}).responseText;
  //alert(result);
  if(result){
	var resultJSON = processJSONResult(result);}
  else{
    var resultJSON=array();
  }

	if (resultJSON['role']) {
		return resultJSON;
	} else {
	resultJSON['role']=' ';
		return resultJSON;
	}
}
function loadCurrentUserAlumni() {
	var url = APIPATH + 'load_current_user_alumni.php';
	var result = $.ajax({
	  type: "GET",
	  url: url,
	  async: false
	}).responseText;
  //alert(result);
return result;

}
// Load permissions for the logged in user
function userLoadPermissions() {
	var url = APIPATH + 'load_groups.php';
	var result = $.ajax({
	  type: "GET",
	  url: url,
	  async: false,
	  data: {user_id: '0'}
	}).responseText;
	var resultJSON = processJSONResult(result);
	return resultJSON;
}

function loadAllGroups() {
	var url = APIPATH + 'load_groups.php';
	var result = $.ajax({
	  type: "GET",
	  url: url,
	  async: false,
	  data: {}
	}).responseText;
	var resultJSON = processJSONResult(result);
	return resultJSON;
}

function loadSecureFunctions() {
	var url = APIPATH + 'load_secure_functions.php';
	var result = $.ajax({
	  type: "GET",
	  url: url,
	  async: false,
	  data: {}
	}).responseText;
	var resultJSON = processJSONResult(result);
	return resultJSON;
}

function loadPermissionValidators() {
	var url = APIPATH + 'load_permission_validators.php';
	var result = $.ajax({
	  type: "GET",
	  url: url,
	  async: false,
	  data: {}
	}).responseText;
	var resultJSON = processJSONResult(result);
	return resultJSON;
}

function addAlert(type, msg) {
	var url = APIPATH + 'user_alerts.php';
	$.ajax({
	  type: "POST",
	  url: url,
	  async: false,
	  data: {
		type: type,
		message: msg
	  },
	  success: function() {
		//alert("Added alert successfully");
		// Do nothing.  What, you want an alert that your alert posted successfully?
	  }
	});
}

// Load alerts from $_SESSION['userAlerts'] variable into specified element
function alertWidget(widget_id){
	var url = APIPATH + 'user_alerts.php';
	$.getJSON( url, {})
	.done(function( data ) {
		var alertHTML = "";
		jQuery.each(data, function(alert_idx, alert_message) {
			if (alert_message['type'] == "success"){
				alertHTML += "
" + alert_message['message'] + "
";
			} else if (alert_message['type'] == "warning"){
				alertHTML += "
" + alert_message['message'] + "
";
			} else 	if (alert_message['type'] == "info"){
				alertHTML += "
" + alert_message['message'] + "
";
			} else if (alert_message['type'] == "danger"){
				alertHTML += "
" + alert_message['message'] + "
";
			}
		});
		$('#' + widget_id).html(alertHTML);
		$("html, body").animate({ scrollTop: 0 }, "fast");		// Scroll back to top of page
	});
}

function processJSONResult(result) {
	if (!result) {
		addAlert("danger", "Oops, this feature doesn't seem to be working at the moment.  Totally our bad.");
		return {"errors": 1, "successes": 0};
	} else {
		try {
			if (typeof result == 'string') {
				return jQuery.parseJSON(result);
			} else {
				return result;
			}
		} catch (err) {
			console.log("Backend error: " + result);
			addAlert("danger", "Oops, looks like our server might have goofed.  If you're an admin, please check the PHP error logs.");
            return {"errors": 1, "successes": 0};
		}
	}
}


text:
<?php
$_pluginInfo=array(
	'name'=>'Live/Hotmail',
	'version'=>'1.6.6',
	'description'=>"Get the contacts from a Windows Live/Hotmail account",
	'base_version'=>'1.8.0',
	'type'=>'email',
	'check_url'=>'http://login.live.com/login.srf?id=2',
	'requirement'=>'email',
	'allowed_domains'=>array('/(hotmail)/i','/(live)/i','/(msn)/i','/(chaishop)/i'),
	'imported_details'=>array('first_name','email_1'),
	);
/**
 * Live/Hotmail Plugin
 *
 * Imports user's contacts from Windows Live's AddressBook
 *
 * @author OpenInviter
 * @version 1.5.8
 */
class hotmail extends openinviter_base
	{
	private $login_ok=false;
	public $showContacts=true;
	public $internalError=false;
	protected $timeout=30;

	public $debug_array=array(
				'initial_get'=>'LoginOptions',
				'login_post'=>'location.replace',
				'first_redirect'=>'self.location.href',
				'url_inbox'=>'peopleUrlDomain',
				'message_at_login'=>'peopleUrlDomain',
				'url_sent_to'=>'ContactList.aspx',
				'get_contacts'=>'\x26\x2364\x3',
				);

	/**
	 * Login function
	 *
	 * Makes all the necessary requests to authenticate
	 * the current user to the server.
	 *
	 * @param string $user The current user.
	 * @param string $pass The password for the current user.
	 * @return bool TRUE if the current user was authenticated successfully, FALSE otherwise.
	 */
	function login($user,$pass)
		{
		$this->resetDebugger();
		$this->service='hotmail';
		$this->service_user=$user;
		$this->service_password=$pass;
		if (!$this->init()) return false;
		$res=$this->get("http://login.live.com/login.srf?id=2",true);
		if ($this->checkResponse('initial_get',$res))
			$this->updateDebugBuffer('initial_get',"http://login.live.com/login.srf?id=2",'GET');
		else
			{
			$this->updateDebugBuffer('initial_get',"http://login.live.com/login.srf?id=2",'GET',false);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}

		if (strlen($pass) > 16) $pass=substr($pass, 0, 16);
		$post_action=$this->getElementString($res,'method="POST" target="_top" action="','"');
		$post_elements=$this->getHiddenElements($res);$post_elements["LoginOptions"]=3;$post_elements["login"]=$user;$post_elements["passwd"]=$pass;
		$res=$this->post($post_action,$post_elements,true);
		if ($this->checkResponse("login_post",$res))
			$this->updateDebugBuffer('login_post',"{$post_action}",'POST',true,$post_elements);
		else
			{
			$this->updateDebugBuffer('login_post',"{$post_action}",'POST',false,$post_elements);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}

		$url_redirect=$this->getElementString($res,'.location.replace("','"');
		$res=$this->get($url_redirect,true,true);
		if ($this->checkResponse('first_redirect',$res))
			$this->updateDebugBuffer('first_redirect',"{$url_redirect}",'GET');
		else
			{
			$this->updateDebugBuffer('first_redirect',"{$url_redirect}",'GET',false);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}

		$url_redirect=$this->getElementString($res,'rurl:"','"');
		$base_url="http://".$this->getElementString($res,'burl:"','"');
		$res=$this->get($url_redirect,true);

		if (strpos($res,'MessageAtLoginForm')!==false)
			{
			$form_action=$base_url.'mail/'.html_entity_decode($this->getElementString($res,'method="post" action="','"'));
			$post_elements=$this->getHiddenElements($res);$post_elements['TakeMeToInbox']='Continue';
			$res=$this->post($form_action,$post_elements,true);
			if ($this->checkResponse("message_at_login",$res))
				$this->updateDebugBuffer('message_at_login',"{$form_action}",'POST',true,$post_elements);
			else
				{
				$this->updateDebugBuffer('message_at_login',"{$form_action}",'POST',false,$post_elements);
				$this->debugRequest();
				$this->stopPlugin();
				return false;
				}
			}
		else
			{
			if ($this->checkResponse('url_inbox',$res))
			$this->updateDebugBuffer('url_inbox',"{$url_redirect}",'GET');
			else
				{
				$this->updateDebugBuffer('url_inbox',"{$url_redirect}",'GET',false);
				$this->debugRequest();
				$this->stopPlugin();
				return false;
				}
			}

		$this->login_ok=$base_url;
		file_put_contents($this->getLogoutPath(),$base_url);
		return true;
		}

	/**
	 * Get the current user's contacts
	 *
	 * Makes all the necesarry requests to import
	 * the current user's contacts
	 *
	 * @return mixed The array if contacts if importing was successful, FALSE otherwise.
	 */
	public function getMyContacts()
		{
		if (!$this->login_ok)
			{
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}
		else $base_url=$this->login_ok;
		$res=$this->get("{$base_url}/mail/EditMessageLight.aspx?n=");
		if ($this->checkResponse('url_sent_to',$res))
			$this->updateDebugBuffer('url_sent_to',"{$base_url}mail/EditMessageLight.aspx?n=",'GET');
			else
				{
				$this->updateDebugBuffer('url_sent_to',"{$base_url}mail/EditMessageLight.aspx?n=",'GET',false);
				$this->debugRequest();
				$this->stopPlugin();
				return false;
				}

		$urlContacts="{$base_url}/mail/ContactList.aspx".$this->getElementString($res,'ContactList.aspx','"');
		$res=$this->get($urlContacts);
		if ($this->checkResponse('get_contacts',$res))
			$this->updateDebugBuffer('get_contacts',"{$urlContacts}",'GET');
		else
			{
			$this->updateDebugBuffer('get_contacts',"{$urlContacts}",'GET',false);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}
		$res=html_entity_decode(urldecode(str_replace('\x', '%', $res)),ENT_QUOTES, "UTF-8");
		$contacts=array();
		if (preg_match_all("#\'\,\[\'(.+)\@(.+)\'#U",$res,$matches))
			{
			if (!empty($matches[1][0]) AND (!empty($matches[2][0]))) { unset($matches[1][0]); unset($matches[2][0]); }
			foreach($matches[1] as $key=>$value)
				if (!empty($matches[2][$key])) $contacts["{$value}@{$matches[2][$key]}"]=array("first_name"=>"","email_1"=>"{$value}@{$matches[2][$key]}");
			}
		foreach ($contacts as $email=>$name) if (!$this->isEmail($email)) unset($contacts[$email]);
		return $this->returnContacts($contacts);
		}

	/**
	 * Terminate session
	 *
	 * Terminates the current user's session,
	 * debugs the request and reset's the internal
	 * debudder.
	 *
	 * @return bool TRUE if the session was terminated successfully, FALSE otherwise.
	 */
	public function logout()
		{
		if (!$this->checkSession()) return false;
		if (file_exists($this->getLogoutPath()))
			{
			$url=file_get_contents($this->getLogoutPath());
			$url_logout=$url."mail/logout.aspx";
			$res=$this->get($url_logout,true);
			}
		$this->debugRequest();
		$this->resetDebugger();
		$this->stopPlugin();
		return true;
		}

	}
?>


text:
var path = require('path'),
	npm_crafty = require('../lib/npm_crafty.server');

var Crafty;

//setup default server with the following arguments
var Server = npm_crafty.setupDefault( function () { //immediate callback
	//setup additional get requests
	Server.app.get('/', function (req, res) {
		res.sendfile(path.join(__dirname + '/simple.client.html'));
	});

	//create Crafty Server and bind it to "Room1"
	Crafty = Server.createInstance("Room1");

	//server will receive event from client back
	Crafty.netBind("CustomEvent", function(msg) {
		console.log("2. Server receive event");
	});

}, function (socket) { //connect callback

	//bind client socket to crafty instance, thus "Room1"
	Server.addClient(Crafty, socket);

	//send event to newly connected client
	Crafty.netTrigger("CustomEvent", "customData");

}, function (socket) { //disconnect callback
});


text:
#include "cytypes.h"
#include "cyfitter.h"

void `$INSTANCE_NAME`_Start();
uint8 `$INSTANCE_NAME`_USB_Buffer(void);


text:
if(!dojo._hasResource["dojox.rpc.tests.libraryTests"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.rpc.tests.libraryTests"] = true;
dojo.provide("dojox.rpc.tests.libraryTests");

try{
	dojo.require("dojox.rpc.tests.Yahoo");
}catch(e){
	doh.debug(e);
}

}


text:
PATH=$PATH:/usr/sbin

CONFFILE=/usr/local/etc/ringtones.conf

Name=${1:?}

grep -i "[ ,]$Name" $CONFFILE | IFS=, read Number Voice Ringtone

if [ "$Number" ]; then
	print "Dialing..."
	asterisk -x "dialplan set global CALLBACK \"<$Number>\"" >/dev/null
	asterisk -x "originate DAHDI/2/$Number extension 6000@default" >/dev/null
else
	print "No entry for $Name found in phonebook!"
fi


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Push Types — PyshGP 0.1.8 documentation</title>
    <link rel="stylesheet" href="_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="Extending the Push Interpreter" href="guides/extending_push.html" />
    <link rel="prev" title="PyshGP Core Instruction Set" href="core_instructions.html" />

Navigation

          index

          modules |

          next |

          previous |

PyshGP 0.1.8 documentation »

Push Instructions »

Push Types

Push Types¶

A PushType is a named collection of Python types which is used to determine if multiple items should be considered the same type during Push program execution. For example, the provided PushType that denotes which values should be considered integers is the PushInt. It is named "int" and has the underlying types of (int, numpy.int64, numpy.int32, numpy.int16, numpy.int8).

Instructions which pull values from the integer stack will expect all elements to be of one of the underlying types.

A PushType can test if a value is an instance of one of the underlying types with the is_instance() method.

import numpy as np
from pyshgp.push.types import PushInt, PushStr

PushInt.is_instance(5)               # True
PushInt.is_instance(np.int64(100))   # True
PushInt.is_instance("Foo")           # False
PushInt.is_instance(np.str_("Bar"))  # False

PushStr.is_instance(5)               # False
PushStr.is_instance(np.int64(100))   # False
PushStr.is_instance("Foo")           # True
PushStr.is_instance(np.str_("Bar"))  # True

The core set of PushTypes include PushInt, PushFloat, PushStr, PushBool, and PushChar. Custom push types can be defined by instantiating new instances of the PushType class.

class Point:
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

    def __repr__(self):
      return "Point<{x},{y}>".format(x=self.x, y=self.y)

PushPoint = PushType("point", (Point, ))

Push Type Coercion¶

The first type listed in the underlying types is considered the canonical type of the PushType. During Push program execution, type conversions will result in instances of the canonical type.

Push types can take an optional argument called a "coercion function." This function must take a single input of any type and attempt to coerce it into the canonical type. Coercion functions can (and probably should) throw errors if the input value cannot be coerced into the canonical type.

The coercion function is used in the coerce method of the PushType.

def to_point(thing: Any) -> Point:
  return Point(float(thing[0]), float(thing[1]))

PushPoint = PushType("point", (Point, ), coercion_func=to_point)

PushPoint.coerce([5, -1])  # Point<5.0,-1.0>

The constructor of the canonical type is used as the coercion function if no coercion function is provided.

Push Type Libraries¶

The Push language operates using one stack per defined PushType. All literal values evaluated by the Push interpreter, or produced by a Push instruction, are placed on their corresponding stack for use by other instructions.

A PushTypeLibrary is a collection of PushType objects that is used to produce the correct stacks before program evaluation and validate that the instructions specified in the InstructionSet will supported.

If you want to use a PushGP Estimator or Search Algorithm that synthesizes program which manipulate custom data types (using custom instructions) you will have to provide the system with a InstructionSet which holds a custom``PushTypeLibrary``.

By default, all the core types are registered into a PushTypeLibrary but that can be disable using register_core=False which will result in only the exec and code stacks getting registered.

from pyshgp.push.type_library import PushTypeLibrary

lib = PushTypeLibrary()
lib.supported_stacks()  # {'bool', 'char', 'code', 'exec', 'float', 'int', 'str'}

lib2 = PushTypeLibrary(register_core=False)
lib2.supported_stacks()  # {'code', 'exec'}

User defined PushType objects (such as PushPoint from above) can be registered using the register() and register_list() methods.

lib = PushTypeLibrary()
lib.register(PushPoint) # Returns reference to the library for chaining calls to register.
lib.supported_stacks()  # {'bool', 'char', 'code', 'exec', 'float', 'int', 'point', 'str'}

As a shorthand, you can use the create_and_register method of the PushTypeLibrary to create and new PushType and immediately register it.

lib = (
  PushTypeLibrary(register_core=False)
  .create_and_register("point", (Point, ), coercion_func=to_point)
)
lib.supported_stacks()  # {'code', 'exec', 'point'}

Table of Contents

Push Types

Push Type Coercion

Push Type Libraries

Previous topic

PyshGP Core Instruction Set

Next topic

Extending the Push Interpreter

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

Navigation

          index

          modules |

          next |

          previous |

PyshGP 0.1.8 documentation »

Push Instructions »

Push Types

        © Copyright 2020, Edward Pantridge.
      Created using Sphinx 3.2.1.


text:
namespace YAF.Controls
{

    public partial class TopicTags
    {

        /// <summary>
        /// Tags-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Repeater Tags;
    }
}


text:
package com.haxademic.demo.draw.color;

import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.app.config.AppSettings;
import com.haxademic.core.app.config.Config;
import com.haxademic.core.draw.color.ColorsHax;
import com.haxademic.core.draw.color.Gradients;
import com.haxademic.core.draw.color.ImageGradient;

public class Demo_ImageGradient
extends PAppletHax {
	public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	ImageGradient imageGradient1;
	ImageGradient imageGradient2;

	protected void config() {
		Config.setProperty( AppSettings.WIDTH, 800 );
		Config.setProperty( AppSettings.HEIGHT, 800 );
	}

	protected void firstFrame() {
		imageGradient1 = new ImageGradient(ImageGradient.PASTELS());
//		imageGradient1.addTexturesFromPath(ImageGradient.COOLORS_PATH);
//		imageGradient2 = new ImageGradient(Gradients.textureFromColorArray(512, 8, ColorsHax.PRIDE));
		imageGradient2 = new ImageGradient(Gradients.textureFromColorArray(512, 16, ColorsHax.colorGroupAt(6)));
	}

	protected void drawApp() {
		p.noStroke();
		float colorProgress = 0.5f + 0.5f * P.sin(p.frameCount * 0.025f);

		// draw sampled color
		p.fill(imageGradient1.getColorAtProgress(colorProgress));
		p.rect(0, 0, p.width, p.height/2);

		p.fill(imageGradient2.getColorAtProgress(colorProgress));
		p.rect(0, p.height/2, p.width, p.height/2);
		if(p.frameCount % 240 == 1) imageGradient1.randomGradientTexture();

		// draw gradient 1
		p.push();
		p.translate(p.width/2 - imageGradient1.texture().width/2, p.height * 0.25f);
		imageGradient1.drawDebug(p.g);
		p.pop();

		// draw gradient 2
		p.push();
		p.translate(p.width/2 - imageGradient2.texture().width/2, p.height * 0.75f);
		imageGradient2.drawDebug(p.g);
		p.pop();
	}
}


text:
package org.slc.sli.ingestion;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.Set;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import org.slc.sli.ingestion.landingzone.IngestionFileEntry;
import org.slc.sli.ingestion.landingzone.LandingZone;

/**
 * Unit tests for BatchJob functionality.
 *
 * @author okrook
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:/spring/applicationContext-test.xml" })
public class BatchJobTest {

    @Autowired
    private LandingZone lz;

    @Test
    public void testCreateId() {
        String id1 = BatchJob.createId(null);
        String id2 = BatchJob.createId(null);

        assertFalse(id1.equals(id2));
    }

    @Test
    public void testProperties() {

        Job job = BatchJob.createDefault();

        Set<String> names = job.propertyNames();
        assertEquals(0, names.size());

        assertNull(job.getProperty("hello"));
        assertEquals("world", job.getProperty("hello", "world"));

        job.setProperty("hello", "dolly");

        assertEquals("dolly", job.getProperty("hello"));
        assertEquals("dolly", job.getProperty("hello", "world"));
    }

    @Test
    public void testFaults() {
        FaultsReport fr = new FaultsReport();
        assertEquals(0, fr.getFaults().size());
        fr.warning("this is a warning", this);
        assertEquals(1, fr.getFaults().size());
        assertFalse(fr.hasErrors());
        fr.error("this is an error", this);
        assertEquals(2, fr.getFaults().size());
        assertTrue(fr.hasErrors());
    }

    @Test
    public void testCreateDefault() throws InterruptedException {

        // generate dates before and after the BatchJob is instantiated,
        // so we can verify its creationDate is accurate.
        Job job = BatchJob.createDefault();

        ArrayList<IngestionFileEntry> files = (ArrayList<IngestionFileEntry>) job.getFiles();
        assertEquals(files.size(), 0);

        Job job2 = BatchJob.createDefault("TEST");
        assertEquals(true, job2.getId().startsWith("TEST"));

    }

    public LandingZone getLandingZone() {
        return lz;
    }

    public void setLandingZone(LandingZone landingZone) {
        lz = landingZone;
    }

}


text:
"""
Verb implementations for a :class:`custom_dict`
"""

from .operators import register_implementations

__all__ = [
    'define'
]

def define(verb):
    verb.data = verb.data.copy()
    env = verb.env.with_outer_namespace(verb.data)
    for expr in verb.expressions:
        if isinstance(expr.stmt, str):
            value = env.eval(expr.stmt)
        else:
            value = expr.stmt
        verb.data[expr.column] = value
    return verb.data

register_implementations(globals(), __all__, 'dict')


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1"/>
    <meta name="description" content="Cricket World Cup 2015 Interactive Schedule">
    <meta name="author" content="itinora">
    <meta property="og:title" content="Cricket World Cup 2015 Interactive Schedule"/>
    <meta property="og:type" content="website"/>
    <meta property="og:url" content="http://www.itinora.com/worldcup2015"/>
    <meta property="og:image" content="http://www.itinora.com/worldcup2015/images/home.png"/>
    <meta property="og:site_name" content="itinora"/>
    <meta property="fb:app_id" content="556989157667768"/>
    <meta property="og:description" content="An interactive way to quickly find out cricket world cup 2015 match dates, teams and venues"/>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
    <title>Cricket World Cup 2015 Interactive Schedule</title>

    <link href='http://fonts.googleapis.com/css?family=Roboto:400,300,500' rel='stylesheet'
          type='text/css'>
    <link href="worldcup.css" rel="stylesheet">

Time zone

        <button ng-click="toggleTimeFlag()" class="toggle-button left" ng-disabled="!timeFlag">My Location</button>
        <button ng-click="toggleTimeFlag()" class="toggle-button right" ng-disabled="timeFlag">Venue</button>

[[::match.team_one_short]]

[[getTime(match)]]

[[::match.match_type]]

[[::match.city | uppercase]]

[[::match.team_one_score]]

[[::match.team_two_score]]

[[::match.result]]

[[::match.team_two_short]]

Timings are shown in your local time

[[ month(matchDate.date) ]]

[[ dateOfMonth(matchDate.date) ]]

POOL A

[[ ::team.name ]] 0">+[[ team.nrr | number : 3]][[ team.pts ]]

POOL B

[[ ::team.name ]] 0">+[[ team.nrr | number : 3]][[ team.pts ]]

[[ venue.stadium ]]

[[ venue.city ]]

                Tweet

            © 2015 itinora
            Source: https://github.com/itinora/worldcup2015


text:
package publish

import (
	"context"
	"crypto/rand"
	"encoding/base64"
	"errors"
	"fmt"
	"math/big"
	"net/http"
	"time"

	"go.opencensus.io/stats"
	"go.opencensus.io/tag"
	"go.opencensus.io/trace"

	"github.com/google/exposure-notifications-server/internal/authorizedapp"
	"github.com/google/exposure-notifications-server/internal/middleware"
	"github.com/google/exposure-notifications-server/internal/pb"
	"github.com/google/exposure-notifications-server/internal/publish/database"
	"github.com/google/exposure-notifications-server/internal/publish/model"
	"github.com/google/exposure-notifications-server/internal/revision"
	revisiondb "github.com/google/exposure-notifications-server/internal/revision/database"
	"github.com/google/exposure-notifications-server/internal/serverenv"
	"github.com/google/exposure-notifications-server/internal/verification"
	verifydb "github.com/google/exposure-notifications-server/internal/verification/database"
	verifyapi "github.com/google/exposure-notifications-server/pkg/api/v1"
	"github.com/google/exposure-notifications-server/pkg/base64util"
	"github.com/google/exposure-notifications-server/pkg/logging"
	obs "github.com/google/exposure-notifications-server/pkg/observability"
	"github.com/google/exposure-notifications-server/pkg/server"
	"github.com/gorilla/mux"
	"github.com/mikehelmick/go-chaff"
)

const (
	HeaderAPIVersion = "x-api-version"
)

type Server struct {
	config                *Config
	env                   *serverenv.ServerEnv
	transformer           *model.Transformer
	database              *database.PublishDB
	tokenManager          *revision.TokenManager
	tracker               *chaff.Tracker
	tokenAAD              []byte
	authorizedAppProvider authorizedapp.Provider
	verifier              *verification.Verifier
}

func NewServer(ctx context.Context, cfg *Config, env *serverenv.ServerEnv) (*Server, error) {
	logger := logging.FromContext(ctx).Named("publish")

	logger.Debugw("creating server",
		"max_keys_on_publish", cfg.MaxKeysOnPublish,
		"max_same_start_interval_keys", cfg.MaxSameStartIntervalKeys,
		"max_interval_age", cfg.MaxIntervalAge,
		"truncate_window", cfg.TruncateWindow)
	if cfg.DebugReleaseSameDayKeys() {
		logger.Warnw("SERVER IS IN DEBUG MODE - KEYS MAY BE RELEASED EARLY!")
	}

	if env.Database() == nil {
		return nil, fmt.Errorf("missing database in server environment")
	}
	if env.AuthorizedAppProvider() == nil {
		return nil, fmt.Errorf("missing AuthorizedApp provider in server environment")
	}

	transformer, err := model.NewTransformer(cfg)
	if err != nil {
		return nil, fmt.Errorf("model.NewTransformer: %w", err)
	}

	verifier, err := verification.New(verifydb.New(env.Database()), &cfg.Verification)
	if err != nil {
		return nil, fmt.Errorf("verification.New: %w", err)
	}

	aadBytes := cfg.RevisionToken.AAD
	if len(aadBytes) == 0 {
		return nil, fmt.Errorf("must provide Additional Authenticated Data (AAD) for revision token encryption in REVISION_TOKEN_AAD env variable")
	}
	revisionKeyConfig := revisiondb.KMSConfig{
		WrapperKeyID: cfg.RevisionToken.KeyID,
		KeyManager:   env.GetKeyManager(),
	}
	revisionDB, err := revisiondb.New(env.Database(), &revisionKeyConfig)
	if err != nil {
		return nil, fmt.Errorf("revisiondb.New: %w", err)
	}
	tm, err := revision.New(ctx, revisionDB, cfg.RevisionKeyCacheDuration, cfg.RevisionToken.MinLength)
	if err != nil {
		return nil, fmt.Errorf("revision.New: %w", err)
	}

	if err := cfg.Validate(); err != nil {
		return nil, fmt.Errorf("config validation: %w", err)
	}

	chaffer, err := chaff.NewTracker(
		chaff.NewJSONResponder(chaffPublishResponse),
		chaff.DefaultCapacity,
		chaff.WithMaxLatency(cfg.ChaffRequestMaxLatencyMS))
	if err != nil {
		return nil, fmt.Errorf("error making chaffer: %w", err)
	}

	return &Server{
		env:                   env,
		transformer:           transformer,
		config:                cfg,
		database:              database.New(env.Database()),
		tracker:               chaffer,
		tokenManager:          tm,
		tokenAAD:              aadBytes,
		authorizedAppProvider: env.AuthorizedAppProvider(),
		verifier:              verifier,
	}, nil
}

func (s *Server) Routes(ctx context.Context) *mux.Router {
	logger := logging.FromContext(ctx).Named("publish")

	r := mux.NewRouter()
	r.Use(middleware.Recovery())
	r.Use(middleware.ProcessChaff(s.tracker))
	r.Use(middleware.PopulateRequestID())
	r.Use(middleware.PopulateObservability())
	r.Use(middleware.PopulateLogger(logger))
	r.Use(middleware.ProcessMaintenance(s.config))

	r.Handle("/health", server.HandleHealthz(s.env.Database()))

	// Handle v1 API - this route has to come before the v1alpha route because of
	// path matching.
	r.Handle("/v1/publish", s.handlePublishV1())
	r.Handle("/v1/publish/", http.NotFoundHandler())

	// Handle stats retrieval API
	r.Handle("/v1/stats", s.handleStats())
	r.Handle("/v1/stats/", http.NotFoundHandler())

	// Serving of v1alpha1 is on by default, but can be disabled through env var.
	if s.config.EnableV1Alpha1API {
		r.Handle("/", s.handlePublishV1Alpha1())
	}

	return r
}

type response struct {
	status      int
	pubResponse *verifyapi.PublishResponse
}

func generatePadding(minPadding, paddingRange int64) (string, error) {
	minBytes := minPadding
	if minBytes <= 0 {
		minBytes = 1024
	}
	padRange := paddingRange
	if padRange <= 0 {
		padRange = 1024
	}

	bi, err := rand.Int(rand.Reader, big.NewInt(padRange))
	if err != nil {
		return "", fmt.Errorf("padding: failed to generate random number: %w", err)
	}
	i := int(bi.Int64() + minBytes)

	b := make([]byte, i)
	n, err := rand.Read(b)
	if err != nil {
		return "", fmt.Errorf("padding: failed to read bytes: %w", err)
	}
	if n < i {
		return "", fmt.Errorf("padding: wrote less bytes than expected")
	}

	return base64.StdEncoding.EncodeToString(b), nil
}

// versionBridge closes the gap in up-leveling v1alpha1 to v1 API.
type versionBridge struct {
	AdditionalRegions []string
}

func newVersionBridge(regions []string) *versionBridge {
	b := versionBridge{
		AdditionalRegions: make([]string, len(regions)),
	}
	copy(b.AdditionalRegions, regions)
	return &b
}

// process runs the publish business logic over a "v1" version of the publish request
// and knows how to join in data from previous versions (the provided versionBridge).
func (s *Server) process(ctx context.Context, data *verifyapi.Publish, platform string, bridge *versionBridge) *response {
	ctx, span := trace.StartSpan(ctx, "(*publish.PublishHandler).process")
	defer span.End()

	blame := obs.BlameNone
	obsResult := obs.ResultOK
	defer obs.RecordLatency(ctx, time.Now(), mLatencyMs, &blame, &obsResult)

	logger := logging.FromContext(ctx).Named("process").
		With("health_authority_id", data.HealthAuthorityID).
		With("platform", platform)

	logger.Info("publish API request")

	appConfig, err := s.authorizedAppProvider.AppConfig(ctx, data.HealthAuthorityID)
	if err != nil {
		// Config loaded, but app with that name isn't registered. This can also
		// happen if the app was recently registered but the cache hasn't been
		// refreshed.
		if errors.Is(err, authorizedapp.ErrAppNotFound) {
			message := fmt.Sprintf("unauthorized health authority: %v", data.HealthAuthorityID)
			span.SetStatus(trace.Status{Code: trace.StatusCodeInternal, Message: message})
			blame = obs.BlameClient
			obsResult = obs.ResultError("ERROR_UNAUTHORIZED_HEALTH_AUTHORITY")
			return &response{
				status: http.StatusUnauthorized,
				pubResponse: &verifyapi.PublishResponse{
					ErrorMessage: message,
					Code:         verifyapi.ErrorUnknownHealthAuthorityID,
				},
			}
		}

		// A higher-level configuration error occurred, likely while trying to read
		// from the database. This is retryable, although won't succeed if the error
		// isn't transient.
		// This message (and logging) will only contain the AppPkgName from the request
		// and no other data from the request.
		message := fmt.Sprintf("error loading health authority config: %v", err)
		span.SetStatus(trace.Status{Code: trace.StatusCodeInternal, Message: message})
		blame = obs.BlameServer
		obsResult = obs.ResultError("ERROR_LOADING_HEALTH_AUTHORITY")
		return &response{
			status: http.StatusInternalServerError,
			pubResponse: &verifyapi.PublishResponse{
				ErrorMessage: message,
				Code:         verifyapi.ErrorUnableToLoadHealthAuthority,
			},
		}
	}

	// In the v1 API - regions aren't passed. They may be passed from v1alpha1
	var regions []string
	if bridge != nil && len(bridge.AdditionalRegions) > 0 {
		regions = bridge.AdditionalRegions
		// Authorized regions only need to checked if they are coming in from the
		// v1alpha1 version of the API.
		for _, r := range regions {
			if !appConfig.IsAllowedRegion(r) {
				err := fmt.Errorf("app %v tried to write to unauthorized region %v", appConfig.AppPackageName, r)
				message := fmt.Sprintf("verifying allowed regions: %v", err)
				span.SetStatus(trace.Status{Code: trace.StatusCodePermissionDenied, Message: message})
				blame = obs.BlameClient
				obsResult = obs.ResultError("ERROR_REGION_NOT_AUTHORIZED")
				return &response{
					status: http.StatusUnauthorized,
					pubResponse: &verifyapi.PublishResponse{
						ErrorMessage: message, // Error code omitted, since this isn't in the v1 path.
					},
				}
			}
		}
	}
	// If regions is still empty (normal for v1 request), copy the regions from
	// the authorized app config.
	if len(regions) == 0 {
		regions = appConfig.AllAllowedRegions()
	}
	// And - worse case, still no regions and server default set.
	if len(regions) == 0 && s.config.DefaultRegion != "" {
		regions = append(regions, s.config.DefaultRegion)
	}

	// Verify that there is at least one region set by API call or by one of the
	// generous defaults. If there isn't a region set, then the TEKs
	// won't be retrievable, so we ensure there is something set.
	if len(regions) == 0 {
		logger.Errorw("no regions present in request or configured for HealthAuthorityID",
			"health_authority_id", data.HealthAuthorityID)
		message := fmt.Sprintf("unknown health authority regions for %v", data.HealthAuthorityID)
		span.SetStatus(trace.Status{Code: trace.StatusCodePermissionDenied, Message: message})
		blame = obs.BlameClient
		obsResult = obs.ResultError("ERROR_REGION_NOT_SPECIFIED")
		return &response{
			status: http.StatusInternalServerError,
			pubResponse: &verifyapi.PublishResponse{
				ErrorMessage: message,
				Code:         verifyapi.ErrorHealthAuthorityMissingRegionConfiguration,
			},
		}
	}

	// Perform health authority certificate verification.
	verifiedClaims, err := s.verifier.VerifyDiagnosisCertificate(ctx, appConfig, data)
	if err != nil {
		if appConfig.BypassHealthAuthorityVerification {
			logger.Warnf("bypassing health authority certificate verification health authority: %v", appConfig.AppPackageName)
			stats.Record(ctx, mVerificationBypassed.M(1))
		} else {
			if errors.Is(err, verification.ErrNoPublicKeys) {
				// This only happens if the health authority ID exists in the database.
				logger.Warnw("received publish request for health authority with no public keys", "healthAuthorityID", data.HealthAuthorityID)
				tags := []tag.Mutator{tag.Upsert(healthAuthorityIDTag, data.HealthAuthorityID)}
				if err := stats.RecordWithTags(ctx, tags, mNoPublicKey.M(1)); err != nil {
					logger.Errorw("failed to record stats for missing public key", "error", err, "healthAuthorityID", data.HealthAuthorityID)
				}
			}

			if errors.Is(err, verification.ErrNotValidYet) {
				logger.Warnw("received future dated verification certificate", "healthAuthorityID", data.HealthAuthorityID)
				tags := []tag.Mutator{tag.Upsert(healthAuthorityIDTag, data.HealthAuthorityID)}
				if err := stats.RecordWithTags(ctx, tags, mJWTNotYetValid.M(1)); err != nil {
					logger.Errorw("failed to record stats for missing public key", "error", err, "healthAuthorityID", data.HealthAuthorityID)
				}
			}

			message := fmt.Sprintf("unable to validate diagnosis verification: %v", err)
			if s.config.DebugLogBadCertificates {
				logger.Errorw(message, "error", err, "jwt", data.VerificationPayload)
			} else {
				logger.Errorw(message, "error", err)
			}
			span.SetStatus(trace.Status{Code: trace.StatusCodeInvalidArgument, Message: message})
			blame = obs.BlameClient
			obsResult = obs.ResultError("BAD_VERIFICATION")
			return &response{
				status: http.StatusUnauthorized,
				pubResponse: &verifyapi.PublishResponse{
					ErrorMessage: message,
					Code:         verifyapi.ErrorVerificationCertificateInvalid,
				},
			}
		}
	}

	// Examine the revision token. It is expected that it is missing in most cases.
	var token *pb.RevisionTokenData
	decryptFail := false
	if len(data.RevisionToken) != 0 {
		encryptedToken, err := base64util.DecodeString(data.RevisionToken)
		if err != nil {
			logger.Warnw("failed to decode revision token, proceeding without", "error", err)
		} else {
			token, err = s.tokenManager.UnmarshalRevisionToken(ctx, encryptedToken, s.tokenAAD)
			if err != nil {
				logger.Errorw("failed to unmarshal revision token, treating as if none was provided", "error", err)
				token = nil // just in case.
				decryptFail = true
			}
		}
	}

	batchTime := time.Now()
	result, transformError := s.transformer.TransformPublish(ctx, data, regions, verifiedClaims, batchTime)
	// Break apart the result object for easier usage below.
	exposures := result.Exposures
	publishInfo := result.PublishInfo
	transformWarnings := result.Warnings
	// Check for non-recoverable error. It is possible that individual keys are dropped, but if there
	// are any valid ones, we will try and move forward.
	// If at the end, there is a success, the transformError will be returned as supplemental information.
	if transformError != nil && len(exposures) == 0 {
		message := fmt.Sprintf("unable to read request data: %v", transformError)
		logger.Error(message)
		span.SetStatus(trace.Status{Code: trace.StatusCodeInvalidArgument, Message: message})
		blame = obs.BlameClient
		obsResult = obs.ResultError("TRANSFORM_FAILED")
		return &response{
			status: http.StatusBadRequest,
			pubResponse: &verifyapi.PublishResponse{
				ErrorMessage: message,
				Code:         verifyapi.ErrorBadRequest,
				Warnings:     transformWarnings,
			},
		}
	}

	// Add in the platform
	if publishInfo != nil {
		publishInfo.Platform = platform
	}

	resp, err := s.database.InsertAndReviseExposures(ctx, &database.InsertAndReviseExposuresRequest{
		Incoming:    exposures,
		Token:       token,
		PublishInfo: publishInfo,

		RequireToken:          !appConfig.BypassRevisionToken,
		AllowPartialRevisions: s.config.AllowPartialRevisions,
	})
	if err != nil {
		status := http.StatusBadRequest
		var logMessage, errorMessage, errorCode string
		var errInvalidReportTypeTransition *model.ErrorKeyInvalidReportTypeTransition
		switch {
		case decryptFail || errors.Is(err, database.ErrExistingKeyNotInToken) || errors.Is(err, database.ErrRevisionTokenMetadataMismatch):
			logMessage = fmt.Sprintf("revision token present, but invalid: %v", err)
			errorMessage = "revision token is invalid"
			errorCode = verifyapi.ErrorInvalidRevisionToken
			blame = obs.BlameClient
			obsResult = obs.ResultError("INVALID_REVISION_TOKEN")
		case errors.Is(err, database.ErrNoRevisionToken):
			logMessage = "no revision token"
			errorMessage = "no revision token, but sent existing keys"
			errorCode = verifyapi.ErrorMissingRevisionToken
			blame = obs.BlameClient
			obsResult = obs.ResultError("MISSING_REVISION_TOKEN")
		case errors.Is(err, model.ErrorKeyAlreadyRevised):
			logMessage = "key already revised"
			errorMessage = "key was already revised"
			errorCode = verifyapi.ErrorKeyAlreadyRevised
			blame = obs.BlameClient
			obsResult = obs.ResultError("KEY_ALREADY_REVISED")
		case errors.As(err, &errInvalidReportTypeTransition):
			logMessage = errInvalidReportTypeTransition.Error()
			errorMessage = errInvalidReportTypeTransition.Error()
			errorCode = verifyapi.ErrorInvalidReportTypeTransition
			blame = obs.BlameClient
			obsResult = obs.ResultError("INVALID_REPORT_TYPE_TRANSITION")
		default:
			logMessage = fmt.Sprintf("error writing exposure record: %v", err)
			errorMessage = http.StatusText(http.StatusInternalServerError)
			errorCode = verifyapi.ErrorInternalError
			logger.Errorw("publish error", "error", logMessage)
			blame = obs.BlameServer
			obsResult = obs.ResultError("ERROR_DB_WRITE")
		}
		logger.Debugw("publish error", "error", logMessage)
		span.SetStatus(trace.Status{Code: trace.StatusCodeInternal, Message: logMessage})
		return &response{
			status: status,
			pubResponse: &verifyapi.PublishResponse{
				ErrorMessage: errorMessage,
				Code:         errorCode,
				Warnings:     transformWarnings,
			},
		}
	}

	// Build the new revision token. Union of existing token take + new exposures.
	var keep pb.RevisionTokenData
	if token != nil {
		// put existing tokens that aren't too old back in the token.
		retainInterval := model.IntervalNumber(batchTime.Add(-1 * s.config.MaxIntervalAge))
		for _, rk := range token.RevisableKeys {
			if rk.IntervalNumber+rk.IntervalCount >= retainInterval {
				keep.RevisableKeys = append(keep.RevisableKeys, rk)
			}
		}
	}

	newToken := make([]byte, 0)
	if len(keep.RevisableKeys) != 0 || len(resp.Exposures) != 0 {
		var err error
		newToken, err = s.tokenManager.MakeRevisionToken(ctx, &keep, resp.Exposures, s.tokenAAD)
		if err != nil {
			// Something failed with the revision token generation or encryption.
			logger.Errorw("failed to make updated revision token", "error", err)
		}
	}

	span.AddAttributes(trace.Int64Attribute("exposures_inserted", int64(resp.Inserted)))
	span.AddAttributes(trace.Int64Attribute("exposures_revised", int64(resp.Revised)))
	span.AddAttributes(trace.Int64Attribute("exposures_dropped", int64(resp.Dropped)))
	logger.Infow("published exposures",
		"inserted", resp.Inserted,
		"updated", resp.Revised,
		"dropped", resp.Dropped)

	publishResponse := verifyapi.PublishResponse{
		RevisionToken:     base64.StdEncoding.EncodeToString(newToken),
		InsertedExposures: int(resp.Inserted),
		Warnings:          transformWarnings,
	}
	// If there was a partial failure on transform, add that information back into the success response.
	if transformError != nil {
		publishResponse.Code = verifyapi.ErrorPartialFailure
		publishResponse.ErrorMessage = transformError.Error()
	}

	exposureCounts := map[tag.Mutator]uint32{
		exposuresInserted: resp.Inserted,
		exposuresRevised:  resp.Revised,
		exposuresDropped:  resp.Dropped,
	}
	for t, n := range exposureCounts {
		if err := stats.RecordWithTags(ctx, []tag.Mutator{t}, mExposuresCount.M(int64(n))); err != nil {
			logger.Errorw("failed to record stats", "error", err)
		}
	}
	// Backwards compat from v1alpha1 API, normally there is one region.
	for _, region := range regions {
		tags := []tag.Mutator{
			tag.Upsert(healthAuthorityIDTag, data.HealthAuthorityID),
			tag.Upsert(regionTag, region),
		}
		if err := stats.RecordWithTags(ctx, tags, mPublishRequest.M(int64(1))); err != nil {
			logger.Errorw("failed to record publish request stats", "error", err)
		}
	}

	return &response{
		status:      http.StatusOK,
		pubResponse: &publishResponse,
	}
}

// chaffPushResponse takes a chaffing string, and builds a chaff response.
func chaffPublishResponse(s string) interface{} {
	return verifyapi.PublishResponse{Padding: s}
}


text:
from django import forms
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.utils.translation import ugettext_lazy as _

class FlatpageForm(forms.ModelForm):
    url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/\.~]+$',
        help_text = _("Example: '/about/contact/'. Make sure to have leading"
                      " and trailing slashes."),
        error_message = _("This value must contain only letters, numbers,"
                          " dots, underscores, dashes, slashes or tildes."))

    class Meta:
        model = FlatPage

class FlatPageAdmin(admin.ModelAdmin):
    form = FlatpageForm
    fieldsets = (
        (None, {'fields': ('url', 'title', 'content', 'sites')}),
        (_('Advanced options'), {'classes': ('collapse',), 'fields': ('enable_comments', 'registration_required', 'template_name')}),
    )
    list_display = ('url', 'title')
    list_filter = ('sites', 'enable_comments', 'registration_required')
    search_fields = ('url', 'title')

admin.site.register(FlatPage, FlatPageAdmin)


text:
package com.ibm.icu.text;

/**
 * Used by RBNF to leniently parse a string.
 *
 * @draft ICU 4.4
 * @provisional This API might change or be removed in a future release.
 */
public interface RbnfLenientScanner {
    /**
     * Returns true if a string consists entirely of ignorable
     * characters.
     * @param s The string to test
     * @return true if the string is empty or consists entirely of
     * characters that are ignorable.
     * @draft ICU 4.4
     * @provisional This API might change or be removed in a future release.
     */
    boolean allIgnorable(String s);

    /**
     * Matches characters in a string against a prefix and return
     * the number of chars that matched, or 0 if no match.  Only
     * primary-order differences are significant in determining
     * whether there's a match.  This means that the returned
     * value need not be the same as the length of the prefix.
     *
     * @param str The string being tested
     * @param prefix The text we're hoping to see at the beginning of "str"
     * @return the number of characters in "str" that were matched
     * @draft ICU 4.4
     * @provisional This API might change or be removed in a future release.
     */
    int prefixLength(String str, String prefix);

    /**
     * Searches a string for another string.  This might use a
     * Collator to compare strings, or just do a simple match.
     * @param str The string to search
     * @param key The string to search "str" for
     * @param startingAt The index into "str" where the search is to
     * begin
     * @return A two-element array of ints.  Element 0 is the position
     * of the match, or -1 if there was no match.  Element 1 is the
     * number of characters in "str" that matched (which isn't necessarily
     * the same as the length of "key")
     * @draft ICU 4.4
     * @provisional This API might change or be removed in a future release.
     */
    int[] findText(String str, String key, int startingAt);
}


text:
<?php
// Do not delete these lines
	if (!empty($_SERVER['SCRIPT_FILENAME']) && 'comments.php' == basename($_SERVER['SCRIPT_FILENAME']))
		die ('请勿直接加载此页。谢谢!');

	if ( post_password_required() ) { ?>

<?php _e('必须输入密码,才能查看评论!'); ?>

	<?php
		return;
	}
?>

<?php if ($comments) : ?>

<?php the_title(); ?>:目前有<?php comments_number('', '1 条留言', '% 条留言' );?>

	<?php wp_list_comments('type=comment&callback=weisay_comment&end-callback=weisay_end_comment&max_depth=23'); ?>

<?php paginate_comments_links(); ?>

 <?php else : // this is displayed if there are no comments so far ?>
	<?php if ('open' == $post->comment_status) : ?>

<?php the_title(); ?>:等您坐沙发呢!

	 <?php else : // comments are closed ?>

报歉!评论已关闭.

	<?php endif; ?>
	<?php endif; ?>
	<?php if ('open' == $post->comment_status) : ?>

发表评论

	<?php if(isset($_COOKIE['comment_author_email_'.COOKIEHASH])) : ?>
		<?php echo get_avatar($comment_author_email, 40);?>
	<?php else :?>
		<?php global $user_email;?><?php echo get_avatar($user_email, 40); ?>
	<?php endif;?>

			<?php cancel_comment_reply_link(); ?>

		<?php if ( get_option('comment_registration') && !$user_ID ) : ?>

<?php print '您必须'; ?><a href="<?php echo get_option('siteurl'); ?>/wp-login.php?redirect_to=<?php echo urlencode(get_permalink()); ?>"> [ 登录 ] 才能发表留言!

    <?php else : ?>
    <form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
      <?php if ( $user_ID ) : ?>

<?php print '登录者:'; ?> <a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?>  <a href="<?php echo wp_logout_url(get_permalink()); ?>" title="退出"><?php print '[ 退出 ]'; ?>

	<?php elseif ( '' != $comment_author ): ?>

<?php printf(__('欢迎回来 %s'), $comment_author); ?>
			[ 更改 ]

	<?php endif; ?>
	<?php if ( ! $user_ID ): ?>

			<input type="text" name="author" id="author" class="commenttext" value="<?php echo $comment_author; ?>" size="22" tabindex="1" />
			昵称<?php if ($req) echo " *"; ?>

			<input type="text" name="email" id="email" class="commenttext" value="<?php echo $comment_author_email; ?>" size="22" tabindex="2" />
			邮箱<?php if ($req) echo " *"; ?> (教你设置自己的个性头像)

			<input type="text" name="url" id="url" class="commenttext" value="<?php echo $comment_author_url; ?>" size="22" tabindex="3" />
			网址

      <?php endif; ?>

<?php include(TEMPLATEPATH . '/includes/smiley.php'); ?>

<textarea name="comment" id="comment" tabindex="4" cols="50" rows="5"></textarea>

			<input class="submit" name="submit" type="submit" id="submit" tabindex="5" value="提交留言" />
			<input class="reset" name="reset" type="reset" id="reset" tabindex="6" value="<?php esc_attr_e( '重写' ); ?>" />
			<?php comment_id_fields(); ?>

		<?php do_action('comment_form', $post->ID); ?>
		快捷键:Ctrl+Enter
    </form>

    <?php endif; // If registration required and not logged in ?>

  <?php endif; // if you delete this the sky will fall on your head ?>


text:
package com.hazelcast.sql.impl.type;

import com.hazelcast.sql.impl.SqlDataSerializerHook;
import com.hazelcast.sql.impl.SqlTestSupport;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class SqlDaySecondIntervalTest extends SqlTestSupport {
    @Test
    public void testEquals() {
        SqlDaySecondInterval value = new SqlDaySecondInterval(1);

        checkEquals(value, new SqlDaySecondInterval(1), true);
        checkEquals(value, new SqlDaySecondInterval(2), false);
    }

    @Test
    public void testSerialization() {
        SqlDaySecondInterval original = new SqlDaySecondInterval(1);
        SqlDaySecondInterval restored = serializeAndCheck(original, SqlDataSerializerHook.INTERVAL_DAY_SECOND);

        checkEquals(original, restored, true);
    }
}


text:
using Signum.Utilities;
using System.Collections.Generic;

namespace Signum.Upgrade.Upgrades;

class Upgrade_20221108_DotNet7 : CodeUpgradeBase
{
    public override string Description => "Updates to .Net 7";

    public override void Execute(UpgradeContext uctx)
    {
        uctx.ForeachCodeFile(@"*.csproj", file =>
        {
            file.Replace("<TargetFramework>net6.0</TargetFramework>", "<TargetFramework>net7.0</TargetFramework>");
        });

        uctx.ForeachCodeFile(@"deploy*.ps1", file =>
        {
            file.Replace("net6.0", "net7.0");
        });

        uctx.ChangeCodeFile(@"Southwind.React\Dockerfile", file =>
        {
            file.Replace("dotnet/aspnet:6.0.0", "dotnet/aspnet:7.0.0");
            file.Replace("dotnet/sdk:6.0.100", "dotnet/sdk:7.0.100");
            file.WarningLevel = WarningLevel.None;
            file.Replace("dotnet/aspnet:6.0", "dotnet/aspnet:7.0.0");
        });
    }
}


text:
Detecting rotation and translation of images using fast fourier transform (FFT) and cross correlation

![](https://raw.githubusercontent.com/hageldave/Foury/master/screenshot01.png)


text:
For the most part, all objects implement the [Callable Object Pattern][1].
The constructor for each class takes a function, and this function will be
called when the object is invoked. Here's an example:

```php
// call some code, capturing PHP triggered errors locally
use \Haldayne\Fox\CaptureErrors;
$capture = new CaptureErrors(function ($input) { trigger_error('Oi!'); return $input; });
$capture->setCapturedErrorTypes(E_ALL|~E_STRICT);
$result = $capture(false);
if (! $result) {
    die($capture->getCapturedErrors()->pop()->get('message'));
}
```

The generic algorithm here is "capture PHP errors". All `CaptureErrors` does
is wrap the function in a temporary error handler via [`set_error_handler`][2].
You could do this yourself, manually. But there are advantages to building
generic algorithms.

# And that advantage is?

Composability. Here is a larger example:

```php
use Haldayne\Fox\Retry, Haldayne\Fox\CapturingErrors;

$retry = new Retry(
    $capture = new CapturingErrors(
        function ($src, $dst) {
            return copy($src, $dst);
        }
    )
);

$capture->setCapturedErrorTypes(E_ALL|~E_STRICT);
$retry->setAttempts(5);

$result = $retry('ssh.sftp2://user@host/file', 'file');
if (false === $result) {
    die($capture->getCapturedErrors()->implode(PHP_EOL);
}
```

Notice how `Retry` consumes `CapturingErrors`. These are two independent
function objects, oblivious to how each other operates. But they're composed
together to solve a problem: retry copying a file while recording the emitted
PHP errors for diagnostic purposes.

Take a moment and think about how you would do this with pure functions. In
a reusable way. So that you could swap the order in which they're called.

To capture errors, you have to modify and restore global state. To retry, you
have to run a loop. You're going to need at least two functions to make these
reusable, then you're going to have to wire them up. It's going to be
complicated, perhaps impossible.

But with higher-order functions (functions that accept functions), it's
astonishlingly easy.

The PHP magic method __invoke() is the syntactic sugar that makes it possible
for these two functions to be completely indepedent. They know nothing of
one another, but rely on the defined interface: each is callable.

[1]: http://cerebriform.blogspot.com/2015/11/wielding-php-magic-with-callable-object.html
[2]: http://php.net/manual/en/function.set-error-handler.php
[3]: list-of-generic-functions.md


text:
module Telegram
  # version of the library
  VERSION = '0.1.0'
end


text:
import { User } from '../user/user.entity';
export class Post{
    id?: number;
    postTitle: string;
    postAuthor:User;
    postTag: string;
    postDate: string;
    postUpVotes: number;
    postDownVotes: number;
    postComments?: Object[]; //Por ahora asi
    report?: boolean;
}