text:
package ai.verta.modeldb.cron_jobs;

import ai.verta.modeldb.ModelDBConstants;
import ai.verta.modeldb.artifactStore.ArtifactStoreDAO;
import ai.verta.modeldb.artifactStore.ArtifactStoreDAORdbImpl;
import ai.verta.modeldb.artifactStore.storageservice.ArtifactStoreService;
import ai.verta.modeldb.common.exceptions.ModelDBException;
import ai.verta.modeldb.config.MDBConfig;
import ai.verta.modeldb.entities.ArtifactEntity;
import ai.verta.modeldb.entities.ExperimentRunEntity;
import ai.verta.modeldb.utils.ModelDBHibernateUtil;
import ai.verta.modeldb.utils.ModelDBUtils;
import ai.verta.modeldb.versioning.EnvironmentBlob;
import ai.verta.modeldb.versioning.PythonEnvironmentBlob;
import ai.verta.modeldb.versioning.PythonRequirementEnvironmentBlob;
import ai.verta.modeldb.versioning.VersionEnvironmentBlob;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.MalformedJsonException;
import com.google.rpc.Code;
import io.grpc.StatusRuntimeException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TimerTask;
import java.util.regex.Pattern;
import javax.persistence.OptimisticLockException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;

public class PopulateEnvironmentInRunCron extends TimerTask {
  private static final Logger LOGGER = LogManager.getLogger(PopulateEnvironmentInRunCron.class);
  private final ModelDBHibernateUtil modelDBHibernateUtil = ModelDBHibernateUtil.getInstance();
  private final ArtifactStoreDAO artifactStoreDAO;
  private final Integer recordUpdateLimit;

  public PopulateEnvironmentInRunCron(
      ArtifactStoreService artifactStoreService, Integer recordUpdateLimit, MDBConfig mdbConfig) {
    this.artifactStoreDAO = new ArtifactStoreDAORdbImpl(artifactStoreService, mdbConfig);
    this.recordUpdateLimit = recordUpdateLimit;
  }

  /** The action to be performed by this timer task. */
  @Override
  public void run() {
    LOGGER.info("PopulateEnvironmentInRunCron wakeup");

    try (var session = modelDBHibernateUtil.getSessionFactory().openSession()) {
      // Update experimentRun
      updateExperimentRuns(session);
    } catch (Exception ex) {
      if (ex instanceof StatusRuntimeException) {
        StatusRuntimeException exception = (StatusRuntimeException) ex;
        if (exception.getStatus().getCode().value() == Code.PERMISSION_DENIED_VALUE) {
          LOGGER.warn("PopulateEnvironmentInRunCron Exception: {}", ex.getMessage());
        } else {
          LOGGER.warn("PopulateEnvironmentInRunCron Exception: ", ex);
        }
      } else {
        LOGGER.warn("PopulateEnvironmentInRunCron Exception: ", ex);
      }
    }
    LOGGER.info("PopulateEnvironmentInRunCron finish tasks and reschedule");
  }

  private void updateExperimentRuns(Session session) {
    LOGGER.trace("ExperimentRun updating");

    var getExperimentRunQueryString =
        new StringBuilder("SELECT expr FROM ")
            .append(ExperimentRunEntity.class.getSimpleName())
            .append(" expr LEFT JOIN ArtifactEntity ar ")
            .append(" ON expr.id = ar.experimentRunEntity.id ")
            .append(" WHERE expr.")
            .append(ModelDBConstants.DELETED)
            .append(" = :deleted ")
            .append(" AND ar.field_type = :fieldType")
            .append(" AND ar.key IN (:keys)")
            .append(" AND expr.environment IS NULL")
            .toString();

    var getExperimentRunQuery = session.createQuery(getExperimentRunQueryString);
    getExperimentRunQuery.setParameter("deleted", false);
    getExperimentRunQuery.setParameter("fieldType", ModelDBConstants.ARTIFACTS);
    getExperimentRunQuery.setParameter(
        "keys", Arrays.asList(ModelDBConstants.MODEL_API_JSON, ModelDBConstants.REQUIREMENTS_TXT));
    getExperimentRunQuery.setMaxResults(this.recordUpdateLimit);
    List<ExperimentRunEntity> experimentRunEntities = getExperimentRunQuery.list();

    List<String> experimentRunIds = new ArrayList<>();
    if (!experimentRunEntities.isEmpty()) {
      for (ExperimentRunEntity experimentRunEntity : experimentRunEntities) {
        try {
          List<ArtifactEntity> experimentRunArtifacts =
              (experimentRunEntity.getArtifactEntityMap() != null
                      && experimentRunEntity
                          .getArtifactEntityMap()
                          .containsKey(ModelDBConstants.ARTIFACTS))
                  ? experimentRunEntity.getArtifactEntityMap().get(ModelDBConstants.ARTIFACTS)
                  : Collections.emptyList();
          if (!experimentRunArtifacts.isEmpty()) {
            var pythonEnvironmentBuilder = PythonEnvironmentBlob.newBuilder();
            createPythonEnvironmentFromArtifacts(
                artifactStoreDAO, experimentRunArtifacts, pythonEnvironmentBuilder);

            if (pythonEnvironmentBuilder.getConstraintsCount() > 0
                || pythonEnvironmentBuilder.hasVersion()) {
              var environmentBlobBuilder = EnvironmentBlob.newBuilder();
              environmentBlobBuilder.setPython(pythonEnvironmentBuilder.build());
              experimentRunEntity.setEnvironment(
                  ModelDBUtils.getStringFromProtoObject(environmentBlobBuilder.build()));
            }

            try {
              var transaction = session.beginTransaction();
              session.update(experimentRunEntity);
              transaction.commit();
              experimentRunIds.add(experimentRunEntity.getId());
            } catch (OptimisticLockException ex) {
              LOGGER.info(
                  "PopulateEnvironmentInRunCron : updateExperimentRuns : Exception: {}",
                  ex.getMessage());
            }
          }
        } catch (Exception ex) {
          LOGGER.debug("PopulateEnvironmentInRunCron : updateExperimentRuns : Exception:", ex);
        }
      }
    }

    LOGGER.debug(
        "ExperimentRun updated successfully : Updated experimentRuns count {}",
        experimentRunIds.size());
  }

  private void createPythonEnvironmentFromArtifacts(
      ArtifactStoreDAO artifactStoreDAO,
      List<ArtifactEntity> artifacts,
      PythonEnvironmentBlob.Builder pythonEnvironmentBuilder)
      throws ModelDBException {
    for (ArtifactEntity artifact : artifacts) {
      if (artifact.getKey().equals(ModelDBConstants.MODEL_API_JSON)) {
        addVersionInPythonEnvironmentBlob(artifactStoreDAO, pythonEnvironmentBuilder, artifact);
      } else if (artifact.getKey().equals(ModelDBConstants.REQUIREMENTS_TXT)) {
        addRequirementsInPythonEnvironmentBlob(
            artifactStoreDAO, pythonEnvironmentBuilder, artifact);
      }
    }
  }

  private void addRequirementsInPythonEnvironmentBlob(
      ArtifactStoreDAO artifactStoreDAO,
      PythonEnvironmentBlob.Builder pythonEnvironmentBuilder,
      ArtifactEntity artifact)
      throws ModelDBException {
    var inputStream = artifactStoreDAO.downloadArtifact(artifact.getPath());

    try (var br = new BufferedReader(new InputStreamReader(inputStream))) {
      var pattern = Pattern.compile(ModelDBConstants.VER_SPEC_PATTERN);
      String line;
      while ((line = br.readLine()) != null) {
        var matcher = pattern.matcher(line);
        var requirementEnvironmentBlob = PythonRequirementEnvironmentBlob.newBuilder();
        if (matcher.find()) {
          String[] requirementArr = pattern.split(line);
          requirementEnvironmentBlob.setLibrary(requirementArr[0]);
          requirementEnvironmentBlob.setConstraint(matcher.group());
          requirementEnvironmentBlob.setVersion(getVersionEnvironmentBlob(requirementArr[1]));
        } else {
          requirementEnvironmentBlob.setLibrary(line);
        }
        pythonEnvironmentBuilder.addRequirements(requirementEnvironmentBlob.build());
      }
    } catch (IOException e) {
      LOGGER.warn(e.getMessage());
      throw new ModelDBException(e.getMessage(), Code.INTERNAL, e);
    }
  }

  public VersionEnvironmentBlob getVersionEnvironmentBlob(String version) {
    var versionBuilder = VersionEnvironmentBlob.newBuilder();
    String[] versionArr = version.split("\\.");
    var validVersionLength = 0;
    if (versionArr.length > 0) {
      String majorStr = versionArr[0];
      try {
        versionBuilder.setMajor(Integer.parseInt(majorStr));
        validVersionLength = validVersionLength + majorStr.length();
      } catch (NumberFormatException ex) {
        String[] requirementArr = majorStr.split(ModelDBConstants.VER_NUM_PATTERN);
        if (requirementArr.length > 0 && !requirementArr[0].isEmpty()) {
          try {
            versionBuilder.setMajor(Integer.parseInt(requirementArr[0]));
            validVersionLength = validVersionLength + requirementArr[0].length();
            versionBuilder.setSuffix(version.substring(validVersionLength));
            return versionBuilder.build();
          } catch (NumberFormatException e) {
            versionBuilder.setSuffix(version);
            return versionBuilder.build();
          }
        } else {
          versionBuilder.setSuffix(version);
          return versionBuilder.build();
        }
      }
      validVersionLength = validVersionLength + 1;
    }
    if (versionArr.length > 1) {
      String minorStr = versionArr[1];
      try {
        versionBuilder.setMinor(Integer.parseInt(minorStr));
        validVersionLength = validVersionLength + minorStr.length();
      } catch (NumberFormatException ex) {
        String[] requirementArr = minorStr.split(ModelDBConstants.VER_NUM_PATTERN);
        if (requirementArr.length > 0) {
          try {
            versionBuilder.setMinor(Integer.parseInt(requirementArr[0]));
            validVersionLength = validVersionLength + requirementArr[0].length();
            versionBuilder.setSuffix(version.substring(validVersionLength));
            return versionBuilder.build();
          } catch (NumberFormatException e) {
            versionBuilder.setSuffix(version.substring(validVersionLength));
            return versionBuilder.build();
          }
        } else {
          versionBuilder.setSuffix(version.substring(validVersionLength));
          return versionBuilder.build();
        }
      }
      validVersionLength = validVersionLength + 1;
    }
    if (versionArr.length > 2) {
      String patchStr = versionArr[2];
      try {
        versionBuilder.setPatch(Integer.parseInt(patchStr));
        validVersionLength = validVersionLength + patchStr.length();
      } catch (NumberFormatException ex) {
        String[] requirementArr = patchStr.split(ModelDBConstants.VER_NUM_PATTERN);
        if (requirementArr.length > 0) {
          try {
            versionBuilder.setPatch(Integer.parseInt(requirementArr[0]));
            validVersionLength = validVersionLength + requirementArr[0].length();
            versionBuilder.setSuffix(version.substring(validVersionLength));
            return versionBuilder.build();
          } catch (NumberFormatException e) {
            versionBuilder.setSuffix(version.substring(validVersionLength));
            return versionBuilder.build();
          }
        } else {
          versionBuilder.setSuffix(version.substring(validVersionLength));
          return versionBuilder.build();
        }
      }
    }
    if (versionArr.length > 3) {
      versionBuilder.setSuffix(versionArr[3]);
    }
    return versionBuilder.build();
  }

  private void addVersionInPythonEnvironmentBlob(
      ArtifactStoreDAO artifactStoreDAO,
      PythonEnvironmentBlob.Builder pythonEnvironmentBuilder,
      ArtifactEntity artifact)
      throws ModelDBException {
    var inputStream = artifactStoreDAO.downloadArtifact(artifact.getPath());

    addVersionInPythonEnvironmentBlob(pythonEnvironmentBuilder, inputStream);
  }

  public void addVersionInPythonEnvironmentBlob(
      PythonEnvironmentBlob.Builder pythonEnvironmentBuilder, InputStream inputStream)
      throws ModelDBException {

    try (var bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
      var sb = new StringBuilder();
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        sb.append(line);
      }

      var gson = new Gson();
      var jsonObject = gson.fromJson(sb.toString(), JsonObject.class);
      if (jsonObject.has("model_packaging")) {
        var modelPackagingObject = jsonObject.get("model_packaging").getAsJsonObject();
        if (modelPackagingObject.has("python_version")) {
          var version = modelPackagingObject.get("python_version").getAsString();
          pythonEnvironmentBuilder.setVersion(getVersionEnvironmentBlob(version));
        }
      }
    } catch (JsonSyntaxException | MalformedJsonException e) {
      var errorMessage = "model_api.json file could not be parsed";
      LOGGER.info(errorMessage);
      throw new ModelDBException(errorMessage, Code.INVALID_ARGUMENT);
    } catch (Exception e) {
      LOGGER.warn(e.getMessage());
      throw new ModelDBException(e);
    }
  }
}


text:
using namespace mongocxx;

TEST_CASE("pool", "[pool][option]") {
    instance::current();

    {
        options::pool pool_opts{};
        REQUIRE(!pool_opts.client_opts().ssl_opts());
    }

    {
        options::pool pool_opts{options::client().ssl_opts(options::ssl())};
        REQUIRE(pool_opts.client_opts().ssl_opts());
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Verh. zool. -bot. Ges. Wien 69: 360 (1919)

#### Original name
Otthia rosae f. rubi Rehm

### Remarks
null


text:
<?php

namespace OpenOrchestra\ThemeBundle\Twig;

use Symfony\Bundle\FrameworkBundle\Templating\Helper\AssetsHelper;

/**
 * Class OpenOrchestraExtension
 */
class OpenOrchestraExtension extends \Twig_Extension
{
    const FILETYPE_CSS = 'stylesheet';
    const FILETYPE_JS = 'javascript';

    protected $assetsHelper;
    protected $themes;

    /**
     * @param AssetsHelper $assetsHelper
     * @param array        $themes
     */
    public function __construct(AssetsHelper $assetsHelper, array $themes)
    {
        $this->assetsHelper = $assetsHelper;
        $this->themes = $themes;
    }

    /**
     * @return array
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('openOrchestraCss', array($this, 'openOrchestraCss'), array('is_safe' => array('html'))),
            new \Twig_SimpleFunction('openOrchestraJs', array($this, 'openOrchestraJs'), array('is_safe' => array('html'))),
        );
    }

    /**
     * Return the html tags including the css from the theme
     *
     * @param string $themeId
     *
     * @return string
     */
    public function openOrchestraCss($themeId)
    {
        $tags = '';

        if (isset($this->themes[$themeId]) && isset($this->themes[$themeId]['stylesheets'])) {
            $stylesheets = $this->themes[$themeId]['stylesheets'];
            foreach ($stylesheets as $stylesheet) {
                $tags .= $this->getHtmlTag($stylesheet, self::FILETYPE_CSS);
            }
        }

        return $tags;
    }

     /**
     * Return the html tags to include js files from the theme
     *
     * @param string $themeId
      *
      * @return string
     */
    public function openOrchestraJs($themeId)
    {
        $tags = '';

        if (isset($this->themes[$themeId]) && isset($this->themes[$themeId]['javascripts'])) {
            $javascripts = $this->themes[$themeId]['javascripts'];
            foreach ($javascripts as $javascript) {
                $tags .= $this->getHtmlTag($javascript, self::FILETYPE_JS);
            }
        }

        return $tags;
    }

    /**
     * Generate html tag for a javascript or stylesheet asset
     *
     * @param string $file (bundleName:themeName:subpathToFile)
     * @param string $fileType
     *
     * @return string
     */
    protected function getHtmlTag($file, $fileType)
    {
        list($bundleName, $themeName, $filePath) = explode(':', $file);

        $assetsPath = $this->assetsHelper->getUrl($themeName . DIRECTORY_SEPARATOR . $filePath, $bundleName);

        switch ($fileType) {
            case self::FILETYPE_CSS:
                $tag = '<link type="text/css" rel="stylesheet" href="' . $assetsPath . '">' . PHP_EOL;
                break;
            case self::FILETYPE_JS:
                $tag = '<script type="text/javascript" src="' . $assetsPath . '"></script>' . PHP_EOL;
                break;
            default:
                $tag = '';
        }

        return $tag;
    }

    /**
     * @see Twig_ExtensionInterface::getName()
     */
    public function getName()
    {
        return 'open_orchestra_extension';
    }
}


text:
require File.join( File.dirname(__FILE__), '..', 'lib',"jzform" )

include JZForm

describe Template::Runner do
  before(:each) do
    @obj = mock("context object")
    @r = Template::Runner.new(File.join(File.dirname(__FILE__),"/templates/form.screen.rb"))
  end

  it "should call script with object" do
    @obj.should_receive(:hi_from).with("form.screen.rb")
    @r.call(@obj)
  end

end


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

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import io.trino.client.ClientTypeSignatureParameter.ParameterKind;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static io.trino.client.ClientStandardTypes.ARRAY;
import static io.trino.client.ClientStandardTypes.BIGINT;
import static io.trino.client.ClientStandardTypes.BING_TILE;
import static io.trino.client.ClientStandardTypes.BOOLEAN;
import static io.trino.client.ClientStandardTypes.CHAR;
import static io.trino.client.ClientStandardTypes.DATE;
import static io.trino.client.ClientStandardTypes.DECIMAL;
import static io.trino.client.ClientStandardTypes.DOUBLE;
import static io.trino.client.ClientStandardTypes.GEOMETRY;
import static io.trino.client.ClientStandardTypes.INTEGER;
import static io.trino.client.ClientStandardTypes.INTERVAL_DAY_TO_SECOND;
import static io.trino.client.ClientStandardTypes.INTERVAL_YEAR_TO_MONTH;
import static io.trino.client.ClientStandardTypes.IPADDRESS;
import static io.trino.client.ClientStandardTypes.JSON;
import static io.trino.client.ClientStandardTypes.MAP;
import static io.trino.client.ClientStandardTypes.REAL;
import static io.trino.client.ClientStandardTypes.ROW;
import static io.trino.client.ClientStandardTypes.SMALLINT;
import static io.trino.client.ClientStandardTypes.SPHERICAL_GEOGRAPHY;
import static io.trino.client.ClientStandardTypes.TIME;
import static io.trino.client.ClientStandardTypes.TIMESTAMP;
import static io.trino.client.ClientStandardTypes.TIMESTAMP_WITH_TIME_ZONE;
import static io.trino.client.ClientStandardTypes.TIME_WITH_TIME_ZONE;
import static io.trino.client.ClientStandardTypes.TINYINT;
import static io.trino.client.ClientStandardTypes.UUID;
import static io.trino.client.ClientStandardTypes.VARCHAR;
import static java.util.Collections.unmodifiableList;
import static java.util.Objects.requireNonNull;

final class FixJsonDataUtils
{
    private FixJsonDataUtils() {}

    public static Iterable<List<Object>> fixData(List<Column> columns, List<List<Object>> data)
    {
        if (data == null) {
            return null;
        }
        requireNonNull(columns, "columns is null");
        ClientTypeSignature[] signatures = columns.stream()
                .map(Column::getTypeSignature)
                .toArray(ClientTypeSignature[]::new);
        ImmutableList.Builder<List<Object>> rows = ImmutableList.builderWithExpectedSize(data.size());
        for (List<Object> row : data) {
            checkArgument(row.size() == signatures.length, "row/column size mismatch");
            List<Object> newRow = new ArrayList<>(row.size());
            for (int i = 0; i < row.size(); i++) {
                newRow.add(fixValue(signatures[i], row.get(i)));
            }
            rows.add(unmodifiableList(newRow)); // allow nulls in list
        }
        return rows.build();
    }

    /**
     * Force values coming from Jackson to have the expected object type.
     */
    private static Object fixValue(ClientTypeSignature signature, Object value)
    {
        if (value == null) {
            return null;
        }

        if (signature.getRawType().equals(ARRAY)) {
            List<?> listValue = ((List<?>) value);
            List<Object> fixedValue = new ArrayList<>(listValue.size());
            for (Object object : listValue) {
                fixedValue.add(fixValue(signature.getArgumentsAsTypeSignatures().get(0), object));
            }
            return fixedValue;
        }
        if (signature.getRawType().equals(MAP)) {
            ClientTypeSignature keySignature = signature.getArgumentsAsTypeSignatures().get(0);
            ClientTypeSignature valueSignature = signature.getArgumentsAsTypeSignatures().get(1);
            Map<?, ?> mapValue = (Map<?, ?>) value;
            Map<Object, Object> fixedValue = Maps.newHashMapWithExpectedSize(mapValue.size());
            for (Map.Entry<?, ?> entry : mapValue.entrySet()) {
                fixedValue.put(fixValue(keySignature, entry.getKey()), fixValue(valueSignature, entry.getValue()));
            }
            return fixedValue;
        }
        if (signature.getRawType().equals(ROW)) {
            List<?> listValue = ((List<?>) value);
            checkArgument(listValue.size() == signature.getArguments().size(), "Mismatched data values and row type");
            Row.Builder row = Row.builderWithExpectedSize(listValue.size());
            for (int i = 0; i < listValue.size(); i++) {
                ClientTypeSignatureParameter parameter = signature.getArguments().get(i);
                checkArgument(
                        parameter.getKind() == ParameterKind.NAMED_TYPE,
                        "Unexpected parameter [%s] for row type",
                        parameter);
                NamedClientTypeSignature namedTypeSignature = parameter.getNamedTypeSignature();
                Object fixedValue = fixValue(namedTypeSignature.getTypeSignature(), listValue.get(i));
                if (namedTypeSignature.getName().isPresent()) {
                    row.addField(namedTypeSignature.getName().get(), fixedValue);
                }
                else {
                    row.addUnnamedField(fixedValue);
                }
            }
            return row.build();
        }
        switch (signature.getRawType()) {
            case BIGINT:
                if (value instanceof String) {
                    return Long.parseLong((String) value);
                }
                return ((Number) value).longValue();
            case INTEGER:
                if (value instanceof String) {
                    return Integer.parseInt((String) value);
                }
                return ((Number) value).intValue();
            case SMALLINT:
                if (value instanceof String) {
                    return Short.parseShort((String) value);
                }
                return ((Number) value).shortValue();
            case TINYINT:
                if (value instanceof String) {
                    return Byte.parseByte((String) value);
                }
                return ((Number) value).byteValue();
            case DOUBLE:
                if (value instanceof String) {
                    return Double.parseDouble((String) value);
                }
                return ((Number) value).doubleValue();
            case REAL:
                if (value instanceof String) {
                    return Float.parseFloat((String) value);
                }
                return ((Number) value).floatValue();
            case BOOLEAN:
                if (value instanceof String) {
                    return Boolean.parseBoolean((String) value);
                }
                return (Boolean) value;
            case VARCHAR:
            case JSON:
            case TIME:
            case TIME_WITH_TIME_ZONE:
            case TIMESTAMP:
            case TIMESTAMP_WITH_TIME_ZONE:
            case DATE:
            case INTERVAL_YEAR_TO_MONTH:
            case INTERVAL_DAY_TO_SECOND:
            case IPADDRESS:
            case UUID:
            case DECIMAL:
            case CHAR:
            case GEOMETRY:
            case SPHERICAL_GEOGRAPHY:
                return (String) value;
            case BING_TILE:
                // Bing tiles are serialized as strings when used as map keys,
                // they are serialized as json otherwise (value will be a LinkedHashMap).
                return value;
            default:
                // for now we assume that only the explicit types above are passed
                // as a plain text and everything else is base64 encoded binary
                if (value instanceof String) {
                    return Base64.getDecoder().decode((String) value);
                }
                return value;
        }
    }
}


text:
![TriVert header] (images/header.png)
[![Build Status](https://travis-ci.org/K-Finlay/TriVert-Project.svg?branch=master)](https://travis-ci.org/K-Finlay/TriVert-Project)
[![Build status](https://ci.appveyor.com/api/projects/status/ncgqw72hyyflj6dt?svg=true)](https://ci.appveyor.com/project/K-Finlay/trivert-project)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceské Houby 4-5: 824 (1922)

#### Original name
Lycoperdon opizii Velen.

### Remarks
null


text:
package skinny.orm.feature

import skinny.orm._
import skinny.orm.feature.associations._
import skinny.orm.feature.includes.IncludesQueryRepository
import scalikejdbc._

/**
  * Provides #joins APIs.
  *
  * NOTE: CRUDFeature has copy implementation from this trait.
  */
trait JoinsFeature[Entity] extends SkinnyMapperBase[Entity] with AssociationsFeature[Entity] { self: IdFeature[_] =>

  /**
    * Appends join definition on runtime.
    *
    * @param associations associations
    * @return self
    */
  def joins[Id](
      associations: Association[_]*
  ): JoinsFeature[Entity]
    with IdFeature[Id]
    with FinderFeatureWithId[Id, Entity]
    with QueryingFeatureWithId[
      Id,
      Entity
    ] = {
    val _self         = this
    val _associations = associations

    new JoinsFeature[Entity] with IdFeature[Id] with FinderFeatureWithId[Id, Entity]
    with QueryingFeatureWithId[Id, Entity] {
      override protected val underlying = _self
      override def defaultAlias         = _self.defaultAlias

      override def tableName   = _self.tableName
      override def columnNames = _self.columnNames

      override def primaryKeyField     = _self.primaryKeyField
      override def primaryKeyFieldName = _self.primaryKeyFieldName

      override def rawValueToId(value: Any) = _self.rawValueToId(value).asInstanceOf[Id]
      override def idToRawValue(id: Id)     = id

      override val associations = _self.associations ++ _associations

      override val defaultJoinDefinitions     = _self.defaultJoinDefinitions
      override val defaultBelongsToExtractors = _self.defaultBelongsToExtractors
      override val defaultHasOneExtractors    = _self.defaultHasOneExtractors
      override val defaultOneToManyExtractors = _self.defaultOneToManyExtractors

      override def autoSession        = underlying.autoSession
      override def connectionPoolName = underlying.connectionPoolName
      override def connectionPool     = underlying.connectionPool

      override def defaultScope(alias: Alias[Entity]) = _self.defaultScope(alias)
      //override def singleSelectQuery = _self.singleSelectQuery

      def extract(rs: WrappedResultSet, n: ResultName[Entity]) = underlying.extract(rs, n)
    }
  }

  override def extract(sql: SQL[Entity, NoExtractor])(
      implicit includesRepository: IncludesQueryRepository[Entity]
  ): SQL[Entity, HasExtractor] = {
    extractWithAssociations(
      sql,
      belongsToAssociations,
      hasOneAssociations,
      hasManyAssociations
    )
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>fabric-project</artifactId>
        <groupId>io.fabric8</groupId>
        <version>1.0.0.redhat-379</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.fabric8</groupId>
    <artifactId>fabric-features-service</artifactId>
    <version>1.0.0.redhat-379</version>
    <packaging>bundle</packaging>

    <name>Fabric8 :: Karaf Features Service</name>

    <properties>
        <fuse.osgi.import>
            io.fabric8.api*,
            org.osgi.service.event;resolution:=optional,
            *
        </fuse.osgi.import>
        <fuse.osgi.export>
            org.apache.karaf.features;version=${karaf-version},
            io.fabric8.features;version=${project.version};-noimport:=true,
        </fuse.osgi.export>
        <fuse.osgi.private.pkg>
            io.fabric8.utils.features,
            org.apache.karaf.features.internal,
            org.apache.felix.utils.version;-split-package:=merge-first,
            org.apache.felix.utils.manifest;-split-package:=merge-first,
            org.apache.karaf.util.collections;-split-package:=merge-first
        </fuse.osgi.private.pkg>
        <fuse.osgi.services.export>org.apache.karaf.features.FeaturesService</fuse.osgi.services.export>
        <fuse.osgi.service.component>OSGI-INF/*</fuse.osgi.service.component>
    </properties>

    <dependencies>

        <dependency>
          <groupId>io.fabric8</groupId>
          <artifactId>fabric-api</artifactId>
        </dependency>

        <dependency>
            <groupId>io.fabric8</groupId>
            <artifactId>fabric-core</artifactId>
        </dependency>
        <dependency>
            <groupId>io.fabric8</groupId>
            <artifactId>fabric-utils</artifactId>
        </dependency>
        <dependency>
            <groupId>io.fabric8</groupId>
            <artifactId>fabric-zookeeper</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.karaf.features</groupId>
            <artifactId>org.apache.karaf.features.core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.scr.annotations</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>scr</goal>
                        </goals>
                        <configuration>
                            <specVersion>1.2</specVersion>
                            <strictMode>false</strictMode>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
<?php

/**
 * Created by PhpStorm.
 * User: oli2002
 * Date: 10/15/14
 * Time: 11:57 AM
 */

namespace App\VacReqBundle\Controller;

use App\UserdirectoryBundle\Util\LargeFileDownloader;
use Symfony\Component\HttpFoundation\Request;
//use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
//use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Routing\Annotation\Route;

use App\UserdirectoryBundle\Controller\UploadController;
use Symfony\Component\HttpFoundation\Response;

class VacReqUploadController extends UploadController {

    /**
     * @Route("/file-delete", name="vacreq_file_delete", methods={"GET", "POST", "DELETE"})
     */
    public function deleteFileAction(Request $request) {
        return $this->deleteFileMethod($request);
    }

    /**
     * $id - document id
     *
     * @Route("/file-download/{id}/{eventtype}", name="vacreq_file_download", methods={"GET"}, requirements={"id" = "\d+"})
     */
    public function downloadFileAction(Request $request,$id,$eventtype=null) {
        return $this->downloadFileMethod($request,$id,$this->getParameter('vacreq.sitename'),$eventtype);
    }

    /**
     * $id - document id
     *
     * @Route("/file-view/{id}/{viewType}/{eventtype}", name="vacreq_file_view", methods={"GET"}, requirements={"id" = "\d+"})
     */
    public function viewFileAction(Request $request,$id,$eventtype=null, $viewType=null) {
        return $this->viewFileMethod($request,$id,$this->getParameter('vacreq.sitename'),$eventtype,$viewType);
    }

}


text:
var host = 'ws://192.168.0.5:9090';

// This function connects to the rosbridge server running on the local computer on port 9090

var rbServer = new ROSLIB.Ros({
url : host
});

// This function is called upon the rosbridge connection event
rbServer.on('connection', function() {
		// Write appropriate message to #feedback div when successfully connected to rosbridge
		var fbDiv = document.getElementById('feedback');
		fbDiv.innerHTML += "
Connected to websocket server.
";
		});

// This function is called when there is an error attempting to connect to rosbridge
rbServer.on('error', function(error) {
		// Write appropriate message to #feedback div upon error when attempting to connect to rosbridge
		var fbDiv = document.getElementById('feedback');
		fbDiv.innerHTML += "
Error connecting to websocket server.
";
		});

// This function is called when the connection to rosbridge is closed
rbServer.on('close', function() {
		// Write appropriate message to #feedback div upon closing connection to rosbridge
		var fbDiv = document.getElementById('feedback');
		fbDiv.innerHTML += "
Connection to websocket server closed.
";
		});

// These lines create a topic object as defined by roslibjs
var cmdVelTopic = new ROSLIB.Topic({
ros : rbServer,
name : '/turtle1/cmd_vel',
messageType : 'geometry_msgs/Twist'
});

// These lines create a message that conforms to the structure of the Twist defined in our ROS installation
// It initalizes all properties to zero. They will be set to appropriate values before we publish this message.
var twist = new ROSLIB.Message({
linear : {
x : 0.0,
y : 0.0,
z : 0.0
},
angular : {
x : 0.0,
y : 0.0,
z : 0.0
}
});

/* This function:
   - retrieves numeric values from the text boxes
   - assigns these values to the appropriate values in the twist message
   - publishes the message to the cmd_vel topic.
 */
function pubMessage() {
	/**
	  Set the appropriate values on the twist message object according to values in text boxes
	  It seems that turtlesim only uses the x property of the linear object
	  and the z property of the angular object
	 **/
	var linearX = 0.0;
	var angularZ = 0.0;

	// get values from text input fields. Note for simplicity we are not validating.
	linearX = 0 + Number(document.getElementById('linearXText').value);
	angularZ = 0 + Number(document.getElementById('angularZText').value);

	// Set the appropriate values on the message object
	twist.linear.x = linearX;
	twist.angular.z = angularZ;

	// Publish the message
	cmdVelTopic.publish(twist);
}


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import six

from docutils.nodes import Body, Element
from docutils.parsers.rst import directives

class only_base(Body, Element):
    def dont_traverse(self, *args, **kwargs):
        return []

class html_only(only_base):
    pass

class latex_only(only_base):
    pass

def run(content, node_class, state, content_offset):
    text = '\n'.join(content)
    node = node_class(text)
    state.nested_parse(content, content_offset, node)
    return [node]

def html_only_directive(name, arguments, options, content, lineno,
                        content_offset, block_text, state, state_machine):
    return run(content, html_only, state, content_offset)

def latex_only_directive(name, arguments, options, content, lineno,
                         content_offset, block_text, state, state_machine):
    return run(content, latex_only, state, content_offset)

def builder_inited(app):
    if app.builder.name == 'html':
        latex_only.traverse = only_base.dont_traverse
    else:
        html_only.traverse = only_base.dont_traverse

def setup(app):
    app.add_directive('htmlonly', html_only_directive, True, (0, 0, 0))
    app.add_directive('latexonly', latex_only_directive, True, (0, 0, 0))

    # This will *really* never see the light of day As it turns out,
    # this results in "broken" image nodes since they never get
    # processed, so best not to do this.
    # app.connect('builder-inited', builder_inited)

    # Add visit/depart methods to HTML-Translator:
    def visit_perform(self, node):
        pass

    def depart_perform(self, node):
        pass

    def visit_ignore(self, node):
        node.children = []

    def depart_ignore(self, node):
        node.children = []

    app.add_node(html_only,
                 html=(visit_perform, depart_perform),
                 latex=(visit_ignore, depart_ignore))
    app.add_node(latex_only,
                 latex=(visit_perform, depart_perform),
                 html=(visit_ignore, depart_ignore))

    metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
    return metadata


text:
package models.test

case class Tree[T](node: T, children: Seq[Tree[T]] = Nil) {
  def toSeq(indentionLevel: Int = 0): Seq[(Int, T)] = (indentionLevel, node) +: children.flatMap(_.toSeq(indentionLevel + 1))
}


text:
define([], function() {
  return {
    "PropertyPaneDescription": "Description",
    "BasicGroupName": "Group Name",
    "DescriptionFieldLabel": "Description Field",
    "LibraryTitleLabel": "Library Name",
    "RowLimitLabel": "Row Limit"
  }
});


text:
#include "SoundflowerEngine.h"
#include <IOKit/IOLib.h>

// here, instead of clipping, we save the buffer

IOReturn SoundflowerEngine::clipOutputSamples(const void *mixBuf, void *sampleBuf, UInt32 firstSampleFrame, UInt32 numSampleFrames, const IOAudioStreamFormat *streamFormat, IOAudioStream *audioStream)
{
    UInt32 channelCount = streamFormat->fNumChannels;
    UInt32 offset = firstSampleFrame * channelCount;
    UInt32 byteOffset = offset * sizeof(float);
    UInt32 numBytes = numSampleFrames * channelCount * sizeof(float);

    if (((SoundflowerDevice *)audioDevice)->mMuteIn[0])
        memset((UInt8 *)thruBuffer + byteOffset, 0, numBytes);
    else {
        memcpy((UInt8 *)thruBuffer + byteOffset, (UInt8 *)mixBuf + byteOffset, numBytes);
        float masterGain =   ((SoundflowerDevice *)audioDevice)->mGain[0]/(float)SoundflowerDevice::kGainMax;
        float masterVolume = ((SoundflowerDevice *)audioDevice)->mVolume[0]/(float)SoundflowerDevice::kVolumeMax;

        for(UInt32 channelBufferIterator = 0; channelBufferIterator < numSampleFrames; channelBufferIterator++)
            for(UInt32 channel = 0; channel < channelCount; channel++) {
                float channelGain =   ((SoundflowerDevice *)audioDevice)->mGain[channel+1]/(float)SoundflowerDevice::kGainMax;
                float channelVolume = ((SoundflowerDevice *)audioDevice)->mVolume[channel+1]/(float)SoundflowerDevice::kVolumeMax;

                thruBuffer[offset + channelBufferIterator*channelCount + channel] *= masterVolume * channelVolume * masterGain * channelGain;
            }

    }

    return kIOReturnSuccess;
}

// This is called when client apps need input audio.  Here we give them saved audio from the clip routine.

IOReturn SoundflowerEngine::convertInputSamples(const void *sampleBuf, void *destBuf, UInt32 firstSampleFrame, UInt32 numSampleFrames, const IOAudioStreamFormat *streamFormat, IOAudioStream *audioStream)
{
    UInt32 offset;
    UInt32 frameSize = streamFormat->fNumChannels * sizeof(float);
    offset = firstSampleFrame * frameSize;

    if (((SoundflowerDevice *)audioDevice)->mMuteOut[0])
        memset((UInt8 *)destBuf, 0, numSampleFrames * frameSize);
    else
        memcpy((UInt8 *)destBuf, (UInt8 *)thruBuffer + offset, numSampleFrames * frameSize);

    return kIOReturnSuccess;
}


text:
#include "query_optimizer/logical/Project.hpp"

#include <string>
#include <vector>

#include "query_optimizer/OptimizerTree.hpp"
#include "query_optimizer/expressions/ExpressionUtil.hpp"
#include "query_optimizer/expressions/NamedExpression.hpp"
#include "query_optimizer/expressions/PatternMatcher.hpp"
#include "utility/Cast.hpp"

#include "glog/logging.h"

namespace quickstep {
namespace optimizer {
namespace logical {

namespace E = ::quickstep::optimizer::expressions;

LogicalPtr Project::copyWithNewChildren(
    const std::vector<LogicalPtr> &new_children) const {
  DCHECK_EQ(children().size(), new_children.size());
  return Project::Create(new_children[0], project_expressions_);
}

std::vector<E::AttributeReferencePtr> Project::getOutputAttributes() const {
  return ToRefVector(project_expressions_);
}

std::vector<E::AttributeReferencePtr> Project::getReferencedAttributes() const {
  std::vector<E::AttributeReferencePtr> referenced_attributes;
  for (const E::NamedExpressionPtr &project_expression : project_expressions_) {
    const std::vector<E::AttributeReferencePtr> referenced_attributes_in_expression =
        project_expression->getReferencedAttributes();
    referenced_attributes.insert(referenced_attributes.end(),
                                 referenced_attributes_in_expression.begin(),
                                 referenced_attributes_in_expression.end());
  }
  return referenced_attributes;
}

LogicalPtr Project::copyWithNewInputExpressions(
    const std::vector<E::ExpressionPtr> &input_expressions) const {
  DCHECK_EQ(project_expressions_.size(), input_expressions.size());
  std::vector<E::NamedExpressionPtr> new_project_expressions;
  for (const E::ExpressionPtr &input_expression : input_expressions) {
    E::NamedExpressionPtr project_expression;
    E::SomeNamedExpression::MatchesWithConditionalCast(input_expression, &project_expression);
    DCHECK(project_expression != nullptr);
    new_project_expressions.emplace_back(project_expression);
  }
  return Create(input_, new_project_expressions);
}

void Project::getFieldStringItems(
    std::vector<std::string> *inline_field_names,
    std::vector<std::string> *inline_field_values,
    std::vector<std::string> *non_container_child_field_names,
    std::vector<OptimizerTreeBaseNodePtr> *non_container_child_fields,
    std::vector<std::string> *container_child_field_names,
    std::vector<std::vector<OptimizerTreeBaseNodePtr>> *container_child_fields) const {
  non_container_child_field_names->push_back("input");
  non_container_child_fields->push_back(input_);

  container_child_field_names->push_back("project_list");
  container_child_fields->push_back(
      CastSharedPtrVector<OptimizerTreeBase>(project_expressions_));
}

}  // namespace logical
}  // namespace optimizer
}  // namespace quickstep


text:
<?php

namespace Zend\ServiceManager\Exception;

class CircularReferenceException extends RuntimeException
{
}


text:
#include <q/lib.hpp>
#include <q/pp.hpp>

#include <vector>

namespace {

std::vector< q::function< void( void ) > >* get_initializers( )
{
	static std::vector< q::function< void( void ) > > initializers;
	return &initializers;
}

} // anomymous namespace

namespace q {

namespace detail {

void register_internal_initializer( q::function< void( void ) >&& func )
{
	get_initializers( )->push_back(
#if defined( LIBQ_ON_GCC ) && ( LIBQ_ON_GCC < 50300 )
		q::function< void( void ) >( func )
#else
		std::move( func )
#endif
	);
}

} // namespace detail

void initialize( settings )
{
	auto initializers = *get_initializers( );

	for ( auto& func : initializers )
		func( );
	initializers.clear( );
}

void uninitialize( )
{ }

scope scoped_initialize( settings settings )
{
	initialize( settings );

	return make_scoped_function( uninitialize );
}

} // namespace q


text:
<!DOCTYPE html>

    <title>OlimpicRings - Task</title>

Europe

Africa

America

Asia

Australia


text:
curl -i -X PUT http://localhost:10018/riak/people/oj -H "Content-type: application/json" --data-binary @oj.json \
  -H 'Link: </riak/people/amy>; riaktag="wife"' \
  -H 'x-riak-index-gender_bin: male' \
  -H 'x-riak-index-height_int: 180'

curl -i -X PUT http://localhost:10018/riak/people/amy -H "Content-type: application/json" --data-binary @amy.json \
  -H 'Link: </riak/people/oj>; riaktag="husband"' \
  -H 'x-riak-index-gender_bin: female' \
  -H 'x-riak-index-height_int: 165'


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
---

# searchbutton

Событие возникает, когда пользователь нажимает кнопку Поиск на Android.

    document.addEventListener("searchbutton", yourCallbackFunction, false);

## Подробности

Если необходимо переопределить поведение по умолчанию кнопки поиск на Android вы можете зарегистрировать обработчик события для события «searchbutton».

Приложения обычно должны использовать `window.addEventListener` чтобы добавить обработчик события после того как произойдет событие `deviceready`.

## Поддерживаемые платформы

*   Android

## Краткий пример

    document.addEventListener("searchbutton", onSearchKeyDown, false);

    function onSearchKeyDown() {
        // Handle the search button
    }

## Развернутый пример

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
                          "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <title>Search Button Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }

        // device APIs are available
        //
        function onDeviceReady() {
            // Register the event listener
            document.addEventListener("searchbutton", onSearchKeyDown, false);
        }

        // Handle the search button
        //
        function onSearchKeyDown() {
        }

        </script>
      </head>
      <body onload="onLoad()">
      </body>
    </html>


text:
package com.github.benmanes.caffeine.jcache.configuration;

import java.util.Map;

import javax.cache.integration.CacheLoader;

/**
 * @author ben.manes@gmail.com (Ben Manes)
 */
public final class TestCacheLoader implements CacheLoader<Integer, Integer> {
  @Override public Integer load(Integer key) {
    return null;
  }
  @Override public Map<Integer, Integer> loadAll(Iterable<? extends Integer> keys) {
    return null;
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 40: 9 (1951)

#### Original name
Phakopsora elephantopi Hirats.

### Remarks
null