text:
import {TypeAny} from "./any";

export class TypeArray extends TypeAny {}


text:
// ------------------------------------------------------------------------------
//  <auto-generated>
//      This code was generated by SpecFlow (http://www.specflow.org/).
//      SpecFlow Version:1.8.0.0
//      SpecFlow Generator Version:1.8.0.0
//      Runtime Version:4.0.30319.239
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </auto-generated>
// ------------------------------------------------------------------------------

#region Designer generated code

using TechTalk.SpecFlow;

#pragma warning disable

namespace Pickles.Example.Features._032FeatureContext
{
    [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.8.0.0")]
    [System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [NUnit.Framework.TestFixtureAttribute()]
    [NUnit.Framework.DescriptionAttribute("FeatureContext features")]
    [NUnit.Framework.CategoryAttribute("showUpInScenarioInfo")]
    [NUnit.Framework.CategoryAttribute("andThisToo")]
    public partial class FeatureContextFeaturesFeature
    {
        private static TechTalk.SpecFlow.ITestRunner testRunner;

#line 1 "FeatureContextFeatures.feature"
#line hidden

        [NUnit.Framework.TestFixtureSetUpAttribute()]
        public virtual void FeatureSetup()
        {
            testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
            var featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"),
                                                                "FeatureContext features",
                                                                "In order to show how to use FeatureContext\r\nAs a SpecFlow evangelist\r\nI want to w" +
                                                                "rite some simple scenarios with data in FeatureContext",
                                                                ProgrammingLanguage.CSharp, new string[]
                                                                                {
                                                                                "showUpInScenarioInfo"
                                                                                ,
                                                                                "andThisToo"
                                                                                });
            testRunner.OnFeatureStart(featureInfo);
        }

        [NUnit.Framework.TestFixtureTearDownAttribute()]
        public virtual void FeatureTearDown()
        {
            testRunner.OnFeatureEnd();
            testRunner = null;
        }

        [NUnit.Framework.SetUpAttribute()]
        public virtual void TestInitialize()
        {
        }

        [NUnit.Framework.TearDownAttribute()]
        public virtual void ScenarioTearDown()
        {
            testRunner.OnScenarioEnd();
        }

        public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
        {
            testRunner.OnScenarioStart(scenarioInfo);
        }

        public virtual void ScenarioCleanup()
        {
            testRunner.CollectScenarioErrors();
        }

        [NUnit.Framework.TestAttribute()]
        [NUnit.Framework.DescriptionAttribute("Store and retrive Person Marcus from FeatureContext Current")]
        public virtual void StoreAndRetrivePersonMarcusFromFeatureContextCurrent()
        {
            var scenarioInfo =
                new TechTalk.SpecFlow.ScenarioInfo("Store and retrive Person Marcus from FeatureContext Current",
                                                   ((string[]) (null)));
#line 7
            this.ScenarioSetup(scenarioInfo);
#line 8
            testRunner.When("I store a person called Marcus in the current FeatureContext");
#line 9
            testRunner.Then("a person called Marcus can easily be retrieved from the current FeatureContext");
#line hidden
            this.ScenarioCleanup();
        }

        [NUnit.Framework.TestAttribute()]
        [NUnit.Framework.DescriptionAttribute("Showing information of the feature")]
        public virtual void ShowingInformationOfTheFeature()
        {
            var scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Showing information of the feature",
                                                                  ((string[]) (null)));
#line 11
            this.ScenarioSetup(scenarioInfo);
#line 12
            testRunner.When("I execute any scenario in the feature");
#line hidden
            var table1 = new TechTalk.SpecFlow.Table(new string[]
                                                         {
                                                             "Field",
                                                             "Value"
                                                         });
            table1.AddRow(new string[]
                              {
                                  "Tags",
                                  "showUpInScenarioInfo, andThisToo"
                              });
            table1.AddRow(new string[]
                              {
                                  "Title",
                                  "FeatureContext features"
                              });
            table1.AddRow(new string[]
                              {
                                  "TargetLanguage",
                                  "CSharp"
                              });
            table1.AddRow(new string[]
                              {
                                  "Language",
                                  "en-US"
                              });
            table1.AddRow(new string[]
                              {
                                  "Description",
                                  "In order to"
                              });
#line 13
            testRunner.Then("the FeatureInfo contains the following information", ((string) (null)), table1);
#line hidden
            this.ScenarioCleanup();
        }
    }
}

#pragma warning restore

#endregion

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.cloud.stream.app.micrometer.common;

import io.micrometer.core.instrument.MeterRegistry;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * Micrometer common tags for Cloud Foundry deployment properties. Based on the CF application environment variables:
 * https://docs.cloudfoundry.org/devguide/deploy-apps/environment-variable.html
 *
 * Tags are set only if the "cloud" Spring profile is set. The "cloud" profile is activated automatically when an
 * application is deployed in CF: https://docs.cloudfoundry.org/buildpacks/java/configuring-service-connections/spring-service-bindings.html#cloud-profiles
 *
 * Use the spring.cloud.stream.app.metrics.cf.tags.enabled=false property to disable inserting those tags.
 *
 * @author Christian Tzolov
 */
@Configuration
@Profile("cloud")
@ConditionalOnProperty(name = "spring.cloud.stream.app.metrics.cf.tags.enabled", havingValue = "true", matchIfMissing = true)
public class CloudFoundryMicrometerCommonTags {

	@Value("${vcap.application.org_name:default}")
	private String organizationName;

	@Value("${vcap.application.space_id:unknown}")
	private String spaceId;

	@Value("${vcap.application.space_name:unknown}")
	private String spaceName;

	@Value("${vcap.application.application_name:unknown}")
	private String applicationName;

	@Value("${vcap.application.application_id:unknown}")
	private String applicationId;

	@Value("${vcap.application.application_version:unknown}")
	private String applicationVersion;

	@Value("${vcap.application.instance_index:0}")
	private String instanceIndex;

	@Bean
	public MeterRegistryCustomizer<MeterRegistry> cloudFoundryMetricsCommonTags() {
		return registry -> registry.config()
				.commonTags("cf.org.name", organizationName)
				.commonTags("cf.space.id", spaceId)
				.commonTags("cf.space.name", spaceName)
				.commonTags("cf.app.id", applicationId)
				.commonTags("cf.app.name", applicationName)
				.commonTags("cf.app.version", applicationVersion)
				.commonTags("cf.instance.index", instanceIndex);
	}
}


text:
<?php

namespace Acme\FmpsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;

class BonLivraisonType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $data = $options['data'];
        if($data && $data->getBonCommandeId() && $data->getId() == ''){
            $bon_commande_id = $data->getBonCommandeId();
            $builder->add('bonCommande', 'entity', array('class' => 'AcmeFmpsBundle:BonCommande', 'label' => 'Bon de commande',
                'query_builder' => function (EntityRepository $er) use ($bon_commande_id)
                     {
                         return $er->createQueryBuilder('b')
                                ->where('b.id = ?1')
                                ->setParameter(1, $bon_commande_id);
                     }
                     ));
        }
        else{
            $builder->add('bonCommande', 'entity', array('class' => 'AcmeFmpsBundle:BonCommande', 'label' => 'Bon de commande'));
        }
        $builder
            ->add('fichier', 'file', array('label' => 'Fichier', 'required' => true));
    }

	  public function getDefaultOptions(array $options)
	  {
	    return array(
	      'data_class' => 'Acme\FmpsBundle\Entity\BonLivraison'
	    );
	  }

    public function getName()
    {
        return 'bon_livraison';
    }
}


text:
package org.apache.hadoop.hive.conf;

import com.google.common.collect.Iterables;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.common.classification.InterfaceAudience.Private;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hive.common.util.HiveStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.stream.Stream;

import static org.apache.hive.common.util.HiveStringUtils.COMMA;
import static org.apache.hive.common.util.HiveStringUtils.EQUALS;

/**
 * Hive Configuration utils
 */
@Private
public class HiveConfUtil {
  private static final String CLASS_NAME = HiveConfUtil.class.getName();
  private static final Logger LOG = LoggerFactory.getLogger(CLASS_NAME);
  /**
   * Check if metastore is being used in embedded mode.
   * This utility function exists so that the logic for determining the mode is same
   * in HiveConf and HiveMetaStoreClient
   * @param msUri - metastore server uri
   * @return
   */
  public static boolean isEmbeddedMetaStore(String msUri) {
    return (msUri == null) ? true : msUri.trim().isEmpty();
  }

  /**
   * Dumps all HiveConf for debugging.  Convenient to dump state at process start up and log it
   * so that in later analysis the values of all variables is known
   */
  public static StringBuilder dumpConfig(HiveConf conf) {
    StringBuilder sb = new StringBuilder("START========\"HiveConf()\"========\n");
    sb.append("hiveDefaultUrl=").append(conf.getHiveDefaultLocation()).append('\n');
    sb.append("hiveSiteURL=").append(HiveConf.getHiveSiteLocation()).append('\n');
    sb.append("hiveServer2SiteUrl=").append(HiveConf.getHiveServer2SiteLocation()).append('\n');
    sb.append("hivemetastoreSiteUrl=").append(HiveConf.getMetastoreSiteLocation()).append('\n');
    dumpConfig(conf, sb);
    return sb.append("END========\"new HiveConf()\"========\n");
  }

  /**
   * Getting the set of the hidden configurations
   * @param configuration The original configuration
   * @return The list of the configuration values to hide
   */
  public static Set<String> getHiddenSet(Configuration configuration) {
    Set<String> hiddenSet = new HashSet<String>();
    String hiddenListStr = HiveConf.getVar(configuration, HiveConf.ConfVars.HIVE_CONF_HIDDEN_LIST);
    if (hiddenListStr != null) {
      for (String entry : hiddenListStr.split(",")) {
        hiddenSet.add(entry.trim());
      }
    }
    return hiddenSet;
  }

  /**
   * Strips hidden config entries from configuration
   * @param conf The configuration to strip from
   * @param hiddenSet The values to strip
   */
  public static void stripConfigurations(Configuration conf, Set<String> hiddenSet) {

    // Find all configurations where the key contains any string from hiddenSet
    Iterable<Map.Entry<String, String>> matching =
        Iterables.filter(conf, confEntry -> {
          for (String name : hiddenSet) {
            if (confEntry.getKey().startsWith(name)) {
              return true;
            }
          }
          return false;
        });

    // Remove the value of every key found matching
    matching.forEach(entry -> conf.set(entry.getKey(), StringUtils.EMPTY));
  }

  /**
   * Searches the given configuration object and replaces all the configuration values for keys
   * defined hive.conf.hidden.list by empty String
   *
   * @param conf - Configuration object which needs to be modified to remove sensitive keys
   */
  public static void stripConfigurations(Configuration conf) {
    Set<String> hiddenSet = getHiddenSet(conf);
    stripConfigurations(conf, hiddenSet);
  }

  public static void dumpConfig(Configuration originalConf, StringBuilder sb) {
    Set<String> hiddenSet = getHiddenSet(originalConf);
    sb.append("Values omitted for security reason if present: ").append(hiddenSet).append("\n");
    Configuration conf = new Configuration(originalConf);
    stripConfigurations(conf, hiddenSet);

    Iterator<Map.Entry<String, String>> configIter = conf.iterator();
    List<Map.Entry<String, String>> configVals = new ArrayList<>();
    while(configIter.hasNext()) {
      configVals.add(configIter.next());
    }
    Collections.sort(configVals, new Comparator<Map.Entry<String, String>>() {
      @Override
      public int compare(Map.Entry<String, String> ent, Map.Entry<String, String> ent2) {
        return ent.getKey().compareTo(ent2.getKey());
      }
    });
    for(Map.Entry<String, String> entry : configVals) {
      //use get() to make sure variable substitution works
      if(entry.getKey().toLowerCase().contains("path")) {
        StringTokenizer st = new StringTokenizer(conf.get(entry.getKey()), File.pathSeparator);
        sb.append(entry.getKey()).append("=\n");
        while(st.hasMoreTokens()) {
          sb.append("    ").append(st.nextToken()).append(File.pathSeparator).append('\n');
        }
      }
      else {
        sb.append(entry.getKey()).append('=').append(conf.get(entry.getKey())).append('\n');
      }
    }
  }

  /**
   * Updates the job configuration with the job specific credential provider information available
   * in the HiveConf.It uses the environment variables HADOOP_CREDSTORE_PASSWORD or
   * HIVE_JOB_CREDSTORE_PASSWORD to get the custom password for all the keystores configured in the
   * provider path. This usage of environment variables is similar in lines with Hadoop credential
   * provider mechanism for getting the keystore passwords. The other way of communicating the
   * password is through a file which stores the password in clear-text which needs to be readable
   * by all the consumers and therefore is not supported.
   *
   *

   *
If HIVE_SERVER2_JOB_CREDENTIAL_PROVIDER_PATH is set in the hive configuration this method
   * overrides the MR job configuration property hadoop.security.credential.provider.path with its
   * value. If not set then it does not change the value of hadoop.security.credential.provider.path
   *
In order to choose the password for the credential provider we check :
   *
   *   (1) if job credential provider path HIVE_SERVER2_JOB_CREDENTIAL_PROVIDER_PATH is set we check if
   *       HIVE_SERVER2_JOB_CREDSTORE_PASSWORD_ENVVAR is set. If it is set we use it.
   *   (2) If password is not set using (1) above we use HADOOP_CREDSTORE_PASSWORD if it is set.
   *   (3) If none of those are set, we do not set any password in the MR task environment. In this
   *       case the hadoop credential provider should use the default password of "none" automatically
   *

   * @param jobConf - job specific configuration
   */
  public static void updateJobCredentialProviders(Configuration jobConf) {
    if(jobConf == null) {
      return;
    }

    String jobKeyStoreLocation = jobConf.get(HiveConf.ConfVars.HIVE_SERVER2_JOB_CREDENTIAL_PROVIDER_PATH.varname);
    String oldKeyStoreLocation = jobConf.get(Constants.HADOOP_CREDENTIAL_PROVIDER_PATH_CONFIG);

    if (StringUtils.isNotBlank(jobKeyStoreLocation)) {
      jobConf.set(Constants.HADOOP_CREDENTIAL_PROVIDER_PATH_CONFIG, jobKeyStoreLocation);
      LOG.debug("Setting job conf credstore location to " + jobKeyStoreLocation
          + " previous location was " + oldKeyStoreLocation);
    }

    String credstorePassword = getJobCredentialProviderPassword(jobConf);
    if (credstorePassword != null) {
      String execEngine = jobConf.get(ConfVars.HIVE_EXECUTION_ENGINE.varname);

      if ("mr".equalsIgnoreCase(execEngine)) {
        // if the execution engine is MR set the map/reduce env with the credential store password

        Collection<String> redactedProperties =
            jobConf.getStringCollection(MRJobConfig.MR_JOB_REDACTED_PROPERTIES);

        Stream.of(
            JobConf.MAPRED_MAP_TASK_ENV,
            JobConf.MAPRED_REDUCE_TASK_ENV,
            MRJobConfig.MR_AM_ADMIN_USER_ENV)

            .forEach(property -> {
              addKeyValuePair(jobConf, property,
                  Constants.HADOOP_CREDENTIAL_PASSWORD_ENVVAR, credstorePassword);
              redactedProperties.add(property);
            });

        // Hide sensitive configuration values from MR HistoryUI by telling MR to redact the following list.
        jobConf.set(MRJobConfig.MR_JOB_REDACTED_PROPERTIES,
            StringUtils.join(redactedProperties, COMMA));
      }
    }
  }

  /*
   * If HIVE_SERVER2_JOB_CREDSTORE_LOCATION is set check HIVE_SERVER2_JOB_CREDSTORE_PASSWORD_ENVVAR before
   * checking HADOOP_CREDENTIAL_PASSWORD_ENVVAR
   */
  public static String getJobCredentialProviderPassword(Configuration conf) {
    String jobKeyStoreLocation =
        conf.get(HiveConf.ConfVars.HIVE_SERVER2_JOB_CREDENTIAL_PROVIDER_PATH.varname);
    String password = null;
    if(StringUtils.isNotBlank(jobKeyStoreLocation)) {
      password = System.getenv(Constants.HIVE_SERVER2_JOB_CREDSTORE_PASSWORD_ENVVAR);
      if (StringUtils.isNotBlank(password)) {
        return password;
      }
    }
    password = System.getenv(Constants.HADOOP_CREDENTIAL_PASSWORD_ENVVAR);
    if (StringUtils.isNotBlank(password)) {
      return password;
    }
    return null;
  }

  private static void addKeyValuePair(Configuration jobConf, String property, String keyName, String newKeyValue) {
    String existingValue = jobConf.get(property);

    if (StringUtils.isBlank(existingValue)) {
      jobConf.set(property, (keyName + EQUALS + newKeyValue));
      return;
    }
    String propertyValue = HiveStringUtils.insertValue(keyName, newKeyValue, existingValue);
    jobConf.set(property, propertyValue);
  }
}


text:
class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.references :business_unit, foreign_key: true
      t.string :name

      t.timestamps
    end
  end
end


text:
package integration_tests

import . "github.com/onsi/ginkgo"

func testNFSShare(aws infrastructureProvisioner, distro linuxDistro) {
	nfsServers, err := aws.CreateNFSServers()
	FailIfError(err, "Couldn't set up NFS shares")

	WithMiniInfrastructure(distro, aws, func(node NodeDeets, sshKey string) {
		By("Setting up a plan file with NFS Shares and no storage")
		plan := PlanAWS{
			Etcd:         []NodeDeets{node},
			Master:       []NodeDeets{node},
			Worker:       []NodeDeets{node},
			LoadBalancer: node.PublicIP,
			SSHKeyFile:   sshKey,
			SSHUser:      node.SSHUser,
			NFSVolume: []NFSVolume{
				{Host: nfsServers[0].IpAddress},
			},
		}

		err := installKismaticWithPlan(plan)
		FailIfError(err, "Error installing cluster with NFS shares")
	})
}


text:
package azkaban.trigger;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.log4j.Logger;

import org.joda.time.DateTime;

import azkaban.database.AbstractJdbcLoader;
import azkaban.utils.GZIPUtils;
import azkaban.utils.JSONUtils;
import azkaban.utils.Props;

public class JdbcTriggerLoader extends AbstractJdbcLoader implements
    TriggerLoader {
  private static Logger logger = Logger.getLogger(JdbcTriggerLoader.class);

  private EncodingType defaultEncodingType = EncodingType.GZIP;

  private static final String triggerTblName = "triggers";

  private static final String GET_UPDATED_TRIGGERS =
      "SELECT trigger_id, trigger_source, modify_time, enc_type, data FROM "
          + triggerTblName + " WHERE modify_time>=?";

  private static String GET_ALL_TRIGGERS =
      "SELECT trigger_id, trigger_source, modify_time, enc_type, data FROM "
          + triggerTblName;

  private static String GET_TRIGGER =
      "SELECT trigger_id, trigger_source, modify_time, enc_type, data FROM "
          + triggerTblName + " WHERE trigger_id=?";

  private static String ADD_TRIGGER = "INSERT INTO " + triggerTblName
      + " ( modify_time) values (?)";

  private static String REMOVE_TRIGGER = "DELETE FROM " + triggerTblName
      + " WHERE trigger_id=?";

  private static String UPDATE_TRIGGER =
      "UPDATE "
          + triggerTblName
          + " SET trigger_source=?, modify_time=?, enc_type=?, data=? WHERE trigger_id=?";

  public EncodingType getDefaultEncodingType() {
    return defaultEncodingType;
  }

  public void setDefaultEncodingType(EncodingType defaultEncodingType) {
    this.defaultEncodingType = defaultEncodingType;
  }

  public JdbcTriggerLoader(Props props) {
    super(props);
  }

  @Override
  public List<Trigger> getUpdatedTriggers(long lastUpdateTime)
      throws TriggerLoaderException {
    logger.info("Loading triggers changed since "
        + new DateTime(lastUpdateTime).toString());
    Connection connection = getConnection();

    QueryRunner runner = new QueryRunner();
    ResultSetHandler<List<Trigger>> handler = new TriggerResultHandler();

    List<Trigger> triggers;

    try {
      triggers =
          runner.query(connection, GET_UPDATED_TRIGGERS, handler,
              lastUpdateTime);
    } catch (SQLException e) {
      logger.error(GET_ALL_TRIGGERS + " failed.");

      throw new TriggerLoaderException("Loading triggers from db failed. ", e);
    } finally {
      DbUtils.closeQuietly(connection);
    }

    logger.info("Loaded " + triggers.size() + " triggers.");

    return triggers;
  }

  @Override
  public List<Trigger> loadTriggers() throws TriggerLoaderException {
    logger.info("Loading all triggers from db.");
    Connection connection = getConnection();

    QueryRunner runner = new QueryRunner();
    ResultSetHandler<List<Trigger>> handler = new TriggerResultHandler();

    List<Trigger> triggers;

    try {
      triggers = runner.query(connection, GET_ALL_TRIGGERS, handler);
    } catch (SQLException e) {
      logger.error(GET_ALL_TRIGGERS + " failed.");

      throw new TriggerLoaderException("Loading triggers from db failed. ", e);
    } finally {
      DbUtils.closeQuietly(connection);
    }

    logger.info("Loaded " + triggers.size() + " triggers.");

    return triggers;
  }

  @Override
  public void removeTrigger(Trigger t) throws TriggerLoaderException {
    logger.info("Removing trigger " + t.toString() + " from db.");

    QueryRunner runner = createQueryRunner();
    try {
      int removes = runner.update(REMOVE_TRIGGER, t.getTriggerId());
      if (removes == 0) {
        throw new TriggerLoaderException("No trigger has been removed.");
      }
    } catch (SQLException e) {
      logger.error(REMOVE_TRIGGER + " failed.");
      throw new TriggerLoaderException("Remove trigger " + t.toString()
          + " from db failed. ", e);
    }
  }

  @Override
  public void addTrigger(Trigger t) throws TriggerLoaderException {
    logger.info("Inserting trigger " + t.toString() + " into db.");
    t.setLastModifyTime(System.currentTimeMillis());
    Connection connection = getConnection();
    try {
      addTrigger(connection, t, defaultEncodingType);
    } catch (Exception e) {
      throw new TriggerLoaderException("Error uploading trigger", e);
    } finally {
      DbUtils.closeQuietly(connection);
    }
  }

  private synchronized void addTrigger(Connection connection, Trigger t,
      EncodingType encType) throws TriggerLoaderException {

    QueryRunner runner = new QueryRunner();

    long id;

    try {
      runner.update(connection, ADD_TRIGGER, DateTime.now().getMillis());
      connection.commit();
      id =
          runner.query(connection, LastInsertID.LAST_INSERT_ID,
              new LastInsertID());

      if (id == -1l) {
        logger.error("trigger id is not properly created.");
        throw new TriggerLoaderException("trigger id is not properly created.");
      }

      t.setTriggerId((int) id);
      updateTrigger(t);
      logger.info("uploaded trigger " + t.getDescription());
    } catch (SQLException e) {
      throw new TriggerLoaderException("Error creating trigger.", e);
    }

  }

  @Override
  public void updateTrigger(Trigger t) throws TriggerLoaderException {
    if (logger.isDebugEnabled()) {
      logger.debug("Updating trigger " + t.getTriggerId() + " into db.");
    }
    t.setLastModifyTime(System.currentTimeMillis());
    Connection connection = getConnection();
    try {
      updateTrigger(connection, t, defaultEncodingType);
    } catch (Exception e) {
      e.printStackTrace();
      throw new TriggerLoaderException("Failed to update trigger "
          + t.toString() + " into db!");
    } finally {
      DbUtils.closeQuietly(connection);
    }
  }

  private void updateTrigger(Connection connection, Trigger t,
      EncodingType encType) throws TriggerLoaderException {

    String json = JSONUtils.toJSON(t.toJson());
    byte[] data = null;
    try {
      byte[] stringData = json.getBytes("UTF-8");
      data = stringData;

      if (encType == EncodingType.GZIP) {
        data = GZIPUtils.gzipBytes(stringData);
      }
      logger.debug("NumChars: " + json.length() + " UTF-8:" + stringData.length
          + " Gzip:" + data.length);
    } catch (IOException e) {
      throw new TriggerLoaderException("Error encoding the trigger "
          + t.toString());
    }

    QueryRunner runner = new QueryRunner();

    try {
      int updates =
          runner.update(connection, UPDATE_TRIGGER, t.getSource(),
              t.getLastModifyTime(), encType.getNumVal(), data,
              t.getTriggerId());
      connection.commit();
      if (updates == 0) {
        throw new TriggerLoaderException("No trigger has been updated.");
      } else {
        if (logger.isDebugEnabled()) {
          logger.debug("Updated " + updates + " records.");
        }
      }
    } catch (SQLException e) {
      logger.error(UPDATE_TRIGGER + " failed.");
      throw new TriggerLoaderException("Update trigger " + t.toString()
          + " into db failed. ", e);
    }
  }

  private static class LastInsertID implements ResultSetHandler<Long> {
    private static String LAST_INSERT_ID = "SELECT LAST_INSERT_ID()";

    @Override
    public Long handle(ResultSet rs) throws SQLException {
      if (!rs.next()) {
        return -1l;
      }

      long id = rs.getLong(1);
      return id;
    }

  }

  public class TriggerResultHandler implements ResultSetHandler<List<Trigger>> {

    @Override
    public List<Trigger> handle(ResultSet rs) throws SQLException {
      if (!rs.next()) {
        return Collections.<Trigger> emptyList();
      }

      ArrayList<Trigger> triggers = new ArrayList<Trigger>();
      do {
        int triggerId = rs.getInt(1);
        int encodingType = rs.getInt(4);
        byte[] data = rs.getBytes(5);

        Object jsonObj = null;
        if (data != null) {
          EncodingType encType = EncodingType.fromInteger(encodingType);

          try {
            // Convoluted way to inflate strings. Should find common package or
            // helper function.
            if (encType == EncodingType.GZIP) {
              // Decompress the sucker.
              String jsonString = GZIPUtils.unGzipString(data, "UTF-8");
              jsonObj = JSONUtils.parseJSONFromString(jsonString);
            } else {
              String jsonString = new String(data, "UTF-8");
              jsonObj = JSONUtils.parseJSONFromString(jsonString);
            }
          } catch (IOException e) {
            throw new SQLException("Error reconstructing trigger data ");
          }
        }

        Trigger t = null;
        try {
          t = Trigger.fromJson(jsonObj);
          triggers.add(t);
        } catch (Exception e) {
          e.printStackTrace();
          logger.error("Failed to load trigger " + triggerId);
        }
      } while (rs.next());

      return triggers;
    }

  }

  private Connection getConnection() throws TriggerLoaderException {
    Connection connection = null;
    try {
      connection = super.getDBConnection(false);
    } catch (Exception e) {
      DbUtils.closeQuietly(connection);
      throw new TriggerLoaderException("Error getting DB connection.", e);
    }

    return connection;
  }

  @Override
  public Trigger loadTrigger(int triggerId) throws TriggerLoaderException {
    logger.info("Loading trigger " + triggerId + " from db.");
    Connection connection = getConnection();

    QueryRunner runner = new QueryRunner();
    ResultSetHandler<List<Trigger>> handler = new TriggerResultHandler();

    List<Trigger> triggers;

    try {
      triggers = runner.query(connection, GET_TRIGGER, handler, triggerId);
    } catch (SQLException e) {
      logger.error(GET_TRIGGER + " failed.");
      throw new TriggerLoaderException("Loading trigger from db failed. ", e);
    } finally {
      DbUtils.closeQuietly(connection);
    }

    if (triggers.size() == 0) {
      logger.error("Loaded 0 triggers. Failed to load trigger " + triggerId);
      throw new TriggerLoaderException(
          "Loaded 0 triggers. Failed to load trigger " + triggerId);
    }

    return triggers.get(0);
  }

}


text:
class SubscriptionService
  LIST_ID = ENV['MAILCHIMP_LIST_ID']
  API_KEY = ENV['MAILCHIMP_API_KEY']

  def initialize(subscription_params)
    @subscription_params = subscription_params
    @email_address = subscription_params[:email]
    @subscription_id = subscription_params[:id]
    @api_request = Gibbon::Request.new(api_key: API_KEY)
  end

  def subscribe
    # @todo <alex> Better error-handling/reporting here obvs
    return if @email_address.nil?
    @api_request.lists(LIST_ID).members.create(create_params)
  end

  def update
    # @todo <alex> Better error-handling/reporting here obvs
    return unless should_update?
    @api_request.lists(LIST_ID).members(@subscription_id).update(update_params)
  end

  private
  def create_params
    {
      body: {
        email_address: @email_address,
        status: "subscribed",
        merge_fields: {
          FNAME: @subscription_params[:first_name],
          LNAME: @subscription_params[:last_name]
        }
      }
    }
  end

  def update_params
    {
      body: {
        email_address: @email_address,
        status: "subscribed",
        merge_fields: {
          FNAME: @subscription_params[:first_name],
          LNAME: @subscription_params[:last_name]
        }
      }
    }
  end

  def should_update?
    has_name? && @subscription_id.present?
  end

  def has_name?
    @subscription_params[:first_name].present? ||
      @subscription_params[:last_name].present?
  end
end


text:
#import "MSOutlookFetchers.h"

/** Implementation for MSOutlookSubscriptionOperations
 *
 */
@implementation MSOutlookSubscriptionOperations

- (instancetype)initOperationWithUrl:(NSString *)urlComponent parent:(id<MSOrcExecutable>)parent {

    return [super initOperationWithUrl:urlComponent parent:parent];
}

@end


text:
			{{$kegiatans->appends(Input::all())->links()}}

		@if(!count($kegiatans)>0)

Tidak ada Kegiatan

		@else

					Kegiatan

				@foreach($kegiatans as $kegiatan)

					{{$kegiatan->kegiatan}}
					{{date('d M Y',strtotime($kegiatan->tanggal))}}
					{{$kegiatan->tempat}}
					{{round($kegiatan->nilai,2)}}

id_vendor.'/edit/'.$kegiatan->id)}}"> Ubah

id_vendor.'/delete/'.$kegiatan->id)}}"> Hapus

				@endforeach

		@endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ads.Client.Common;

namespace Ads.Client.CommandResponse
{
    public class AdsReadStateCommandResponse : AdsCommandResponse
    {
        private AdsState adsState;
        public AdsState AdsState
        {
            get { return adsState; }
        }

        protected override void AdsResponseIsChanged()
        {
            adsState = new AdsState();
            adsState.State = BitConverter.ToUInt16(this.AdsResponse, 4);
            adsState.DeviceState = BitConverter.ToUInt16(this.AdsResponse, 6);
        }
    }
}


text:
//
//  TraceViewController.m
//  SMCLocationDemo
//
//  Created by SMC-MAC on 16/9/13.
//  Copyright © 2016年 heyou. All rights reserved.
//

#import "TraceViewController.h"
#import <BaiduTraceSDK/BaiduTraceSDK-Swift.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import "DeviceInfo.h"

#define T_LATITUDE  31.263805
#define T_LONGITUDE 121.427416

#define T_IDENTIFIER    @"ypc"
#define T_SID   125280

#define K_FENCE_RADIUS  100     // 围栏半径

@interface TraceViewController () <ApplicationServiceDelegate, ApplicationFenceDelegate, BMKMapViewDelegate, BMKLocationServiceDelegate> {
    BTRACE* _traceInstance;

    NSMutableString* _logs;

    BMKMapView* _mapView;
    BMKLocationService* _locService;
}
- (IBAction)onButtonClear:(id)sender;
- (IBAction)onButtonStart:(id)sender;
@property (weak, nonatomic) IBOutlet UITextView *textView;

@end

@implementation TraceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    _logs = [NSMutableString string];

    //使用鹰眼SDK第一步必须先实例化BTRACE对象
    BTRACE * traceInstance = [[BTRACE alloc] initWithAk:@"ZMqzchrdY7u67A5kNT5APfmL4382y7xF"
                                                  mcode:@"com.smc.test.location"
                                              serviceId:T_SID entityName:T_IDENTIFIER operationMode:2];

    //setInterval代表采集周期,packInterval代表打包上传周期
//    BOOL intervalSetRet = [traceInstance setInterval:10 packInterval:60];

#if 0
    // 创建围栏
    [[BTRACEAction shared] createCircularFence:self
                                     serviceId:sid
                                     fenceName:@"fenceA"
                                     fenceDesc:@"围栏描述"
                                       creator:T_IDENTIFIER
                              monitoredPersons:T_IDENTIFIER
                                     observers:T_IDENTIFIER
                                    validTimes:@"0000,2359"
                                    validCycle:4
                                     validDate:nil
                                     validDays:nil
                                     coordType:3
                                        center:@"121.427416,31.263805"
                                        radius:500
                                alarmCondition:3
                                     precision:100];
#endif

    //开始追踪,异步执行
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[BTRACEAction shared] startTrace:self trace:traceInstance];
    });

    NSLog(@"%s", __FUNCTION__);
    _traceInstance = traceInstance;

#if 1
    _locService = [[BMKLocationService alloc]init];
    BMKMapView* mapView = [[BMKMapView alloc]initWithFrame:self.view.bounds];
    mapView.zoomLevel = 19;
    mapView.mapType = BMKMapTypeStandard;
//    [self.view addSubview:mapView];
    [self.view insertSubview:mapView atIndex:0];

    CLLocationCoordinate2D baiduCoor = CLLocationCoordinate2DMake(T_LATITUDE, T_LONGITUDE);
    //添加 圆形覆盖物
    BMKCircle* circle = [BMKCircle circleWithCenterCoordinate:baiduCoor radius:K_FENCE_RADIUS];
    [mapView addOverlay:circle];
    [mapView setCenterCoordinate:baiduCoor];

    _mapView = mapView;
#endif

    self.textView.text = @"abcd";
    [self.view bringSubviewToFront:self.textView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    //结束轨迹追踪
    [[BTRACEAction shared] stopTrace:self trace:_traceInstance];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
    _locService.delegate = self;

    [_locService startUserLocationService];
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时,置nil
    _locService.delegate = nil;

    [_locService stopUserLocationService];
}

/**
 *在地图View将要启动定位时,会调用此函数
 */
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

/**
 *用户方向更新后,会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
//    NSLog(@"heading is %@",userLocation.heading);
}

/**
 *用户位置更新后,会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [_mapView updateLocationData:userLocation];
}

/**
 *在地图View停止定位后,会调用此函数
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后,会调用此函数
 *@param error 错误号,参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation {
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = NO;// 设置该标注点动画显示
        return newAnnotationView;
    }
    return nil;
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
    NSLog(@"%s", __FUNCTION__);
}

// Override
- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay{
    if ([overlay isKindOfClass:[BMKCircle class]]){
        //        BMKCircleView* circleView = [[[BMKCircleView alloc] initWithOverlay:overlay] autorelease];
        BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.fillColor = [[UIColor blueColor] colorWithAlphaComponent:0.5];
        circleView.strokeColor = [[UIColor redColor] colorWithAlphaComponent:0.5];
        circleView.lineWidth = 2.0;

        return circleView;
    }
    return nil;
}

#pragma mark -- ApplicationServiceDelegate
- (void)onStartTrace:(NSInteger)errNo errMsg:(NSString * _Nonnull)errMsg {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"errNo = %ld, msg = %@", errNo, errMsg);

    [self notify:[NSString stringWithFormat:@"%s", __FUNCTION__]];
    [self notify:errMsg];
}

/// 获取附加数据的回调方法,开发者需要实现这个方法,在此方法中返回自定义列的键和值
///
/// returns: 用户自定义列的键值对
- (NSDictionary<NSString *, NSString *> * _Nullable)trackAttr {
    NSLog(@"%s", __FUNCTION__);
    NSDictionary* tDic = @{@"name":@"ypc", @"inc":@"smc"};
    return tDic;
}

- (void)onStopTrace:(NSInteger)errNo errMsg:(NSString * _Nonnull)errMsg {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"errNo = %ld, msg = %@", errNo, errMsg);

    [self notify:[NSString stringWithFormat:@"%s", __FUNCTION__]];
    [self notify:errMsg];
}

// 围栏报警
- (void)onPushTrace:(uint8_t)msgType msgContent:(NSString * _Nonnull)msgContent {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"msgType = %i, content = %@", msgType, msgContent);
    [self notify:[NSString stringWithFormat:@"%s", __FUNCTION__]];
    [self notify:msgContent];
}

- (void)onChangeGatherAndPackIntervalsAfterStartTrace:(NSInteger)errNo errMsg:(NSString * _Nonnull)errMsg {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"errNo = %ld, msg = %@", errNo, errMsg);
    [self notify:[NSString stringWithFormat:@"%s", __FUNCTION__]];
    [self notify:errMsg];
}

- (void)notify:(NSString*)msg {
    [_logs appendString:msg];
//    [DeviceInfo scheduleNotification:@"test" body:msg delay:1];

    dispatch_async(dispatch_get_main_queue(), ^{
        self.textView.text = _logs;
    });
}

#if 1
#pragma mark -- ApplicationFenceDelegate
/// 创建地理围栏的回调方法
///
/// param:
///
/// data JSON格式的返回内容
- (void)onCreateFence:(NSData * _Nonnull)data {
    NSLog(@"%s - %@", __FUNCTION__, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [self notify:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}

/// 更新地理围栏的回调方法
///
/// param:
///
/// data JSON格式的返回内容
- (void)onUpdateFence:(NSData * _Nonnull)data {
    NSLog(@"%s - %@", __FUNCTION__, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [self notify:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}

/// 删除地理围栏的回调方法
///
/// param:
///
/// data JSON格式的返回内容
- (void)onDeleteFence:(NSData * _Nonnull)data {
    NSLog(@"%s - %@", __FUNCTION__, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [self notify:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}

/// 查询地理围栏列表的回调方法
///
/// param:
///
/// data JSON格式的返回内容
- (void)onFenceList:(NSData * _Nonnull)data {
    NSLog(@"%s - %@", __FUNCTION__, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [self notify:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}

/// 查询地理围栏监控对象的状态的回调方法
///
/// param:
///
/// data JSON格式的返回内容
- (void)onQueryFenceStatus:(NSData * _Nonnull)data {
    NSLog(@"%s - %@", __FUNCTION__, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [self notify:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}

/// 查询地理围栏历史报警信息的回调方法
///
/// param:
///
/// data JSON格式的返回内容
- (void)onQueryFenceHistoryAlarm:(NSData * _Nonnull)data {
    NSLog(@"%s - %@", __FUNCTION__, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [self notify:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}

/// 设置地理围栏延迟报警的回调方法
///
/// param:
///
/// data JSON格式的返回内容
- (void)onFenceDelayAlarm:(NSData * _Nonnull)data {
    NSLog(@"%s - %@", __FUNCTION__, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [self notify:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}

#endif

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)onButtonClear:(id)sender {
#if 1
    _logs = [NSMutableString string];
    self.textView.text = _logs;
    [self.textView resignFirstResponder];
#endif
//    static int fid = 1;
//    [[BTRACEAction shared] deleteFence:self serviceId:T_SID fenceId:fid];
//    fid++;
//    NSLog(@"fid === %i", fid);
}

- (IBAction)onButtonStart:(id)sender {
#if 0
    // 创建围栏
    NSString* tCenter = [NSString stringWithFormat:@"%f,%f", T_LONGITUDE, T_LATITUDE];
    [[BTRACEAction shared] createCircularFence:self
                                     serviceId:T_SID
                                     fenceName:@"斯迈康"
                                     fenceDesc:@"品尊国际十八英尺"
                                       creator:T_IDENTIFIER
                              monitoredPersons:T_IDENTIFIER
                                     observers:T_IDENTIFIER
                                    validTimes:@"0000,2359"
                                    validCycle:4
                                     validDate:nil
                                     validDays:nil
                                     coordType:3
                                        center:tCenter
//                                        center:@"121.427416,31.263805"
                                        radius:K_FENCE_RADIUS
                                alarmCondition:3
                                     precision:50];
#endif
    // 查询围栏列表
    [[BTRACEAction shared] queryFenceList:self serviceId:T_SID creator:T_IDENTIFIER fenceIds:nil];
}
@end


text:
"""
Routes and views for the flask application.
"""
from controller import *
from model import *
from datetime import datetime
from flask import render_template
from Herkansing6B import app
from os import environ

#Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app

#create a new instance of the controller class
controller = controller()

@app.route('/')
@app.route('/home')
def home():
    return controller.index()

@app.route('/easy', methods=['GET', 'POST'])
def Ex_easy():
    return controller.Ex_easy()

@app.route('/medium', methods=['GET', 'POST'])
def Ex_medium():
    return controller.Ex_medium()

@app.route('/hard', methods=['GET', 'POST'])
def Ex_hard():
    return controller.Ex_hard()

@app.route('/inputusertest', methods=['GET', 'POST'])
def InputuserTest():
    return controller.InputuserTest()

@app.route('/resulttest', methods=['GET', 'POST'])
def ResultTest():
    return controller.ResultTest()

@app.route('/easytest', methods=['GET', 'POST'])
def Ex_easyTest():
    return controller.Ex_easyTest()

@app.route('/mediumtest', methods=['GET', 'POST'])
def Ex_mediumTest():
    return controller.Ex_mediumTest()

@app.route('/hardtest', methods=['GET', 'POST'])
def Ex_hardTest():
    return controller.Ex_hardTest()


text:
package mcjty.rftools.blocks.logic.sensor;

import mcjty.rftools.varia.NamedEnum;

public enum AreaType implements NamedEnum {
    AREA_1("Area 1", 1, "1 block in front of sensor"),
    AREA_3("Area 3", 3, "3 blocks in front of sensor"),
    AREA_5("Area 5", 5, "5 blocks in front of sensor"),
    AREA_3X3("Area 3x3", -3, "3x3 blocks in front of sensor"),
    AREA_5X5("Area 5x5", -5, "5x5 blocks in front of sensor"),
    AREA_7X7("Area 7x7", -7, "7x7 blocks in front of sensor");

    private final String name;
    private final String[] description;
    private final int blockCount;

    AreaType(String name, int blockCount, String... description) {
        this.name = name;
        this.blockCount = blockCount;
        this.description = description;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String[] getDescription() {
        return description;
    }

    public int getBlockCount() {
        return blockCount;
    }
}


text:
import yaml

# TODO: Formalize output and validate schema
def get_config():
    with open('config.yaml') as config_file:
        config = yaml.safe_load(config_file)
        return config


text:
package com.intellijob.exceptions;

import com.intellijob.enums.Error;

/**
 * Default application exception.
 *

 * Error Code - 5000000 Error.BAD_REQUEST
 */
public class BadRequestException extends BaseException {

    /**
     * Default Constructor.
     */
    public BadRequestException() {
        super(Error.BAD_REQUEST);
    }
}


text:
#ifndef AVCODEC_AACADTSDEC_H
#define AVCODEC_AACADTSDEC_H

#include "get_bits.h"

#define AAC_ADTS_HEADER_SIZE 7

typedef struct {
    uint32_t sample_rate;
    uint32_t samples;
    uint32_t bit_rate;
    uint8_t  crc_absent;
    uint8_t  object_type;
    uint8_t  sampling_index;
    uint8_t  chan_config;
    uint8_t  num_aac_frames;
} AACADTSHeaderInfo;

/**
 * Parse AAC frame header.
 * Parse the ADTS frame header to the end of the variable header, which is
 * the first 54 bits.
 * @param[in]  gbc BitContext containing the first 54 bits of the frame.
 * @param[out] hdr Pointer to struct where header info is written.
 * @return Returns 0 on success, -1 if there is a sync word mismatch,
 * -2 if the version element is invalid, -3 if the sample rate
 * element is invalid, or -4 if the bit rate element is invalid.
 */
int avpriv_aac_parse_header(GetBitContext *gbc, AACADTSHeaderInfo *hdr);

#endif /* AVCODEC_AACADTSDEC_H */


text:
import _ from 'lodash';

export function instance({ actionTypes }) {
  return (state, action) => {
    switch (action.type) {

      case actionTypes.CITY_LOADING:
        return Object.assign({}, state, {
          isLoading: true,
          hasError: false
        });

      case actionTypes.CITY_LOADED:
        return _.merge({}, state, {
          isLoading: false,
          forecasts: {
            [state.selectedCityId]: action.data
          }
        });

      case actionTypes.CITY_CHANGED:
        return Object.assign({}, state, {
          selectedCityId: action.data
        });

      case actionTypes.CITY_LOAD_FAILED:
        return Object.assign({}, state, {
          hasError: true,
          isLoading: false,
          error: action.error
        })

      default:
        return state;
    }
  }
}


text:
'use strict';

exports.up = function(knex) {
  return knex.schema.createTable('users', (table) => {
    table.increments();
    table.string('name').notNullable().defaultTo('');
    table.string('email').notNullable().defaultTo('');
    table.string('meetup_username').notNullable().defaultTo('');
    table.string('replit_hash').notNullable().defaultTo('');
    table.string('replit_time').notNullable().defaultTo('');
    table.timestamps(true, true);
  });
};

exports.down = function(knex) {
  return knex.schema.dropTable('users');
};


text:
Tested with Python 2.7.11

## Required modules (tested ver.):
  * pyqt 4.11.4
  * numpy 1.10.4

## Usage
1. Launch from align_app.py
2. Choose run directory. If valid run directory is specified, map file will be auto-detected. Otherwise, manually specify map file.
3. Switch between Print and Wafer tabs to choose alignment type. Sample numbers are not required for wafer alignment. All other stage parameters are required.
4. Filter parameters are optional and auto-filled with defaults when a map file is loaded. Filters are applied in order:
  1. Filter codes & omit channels, use comma or space separated lists.
  2. Crop area by map coordinate limits.
  3. Skip samples, columns, rows. (at.% option WIP)
  4. Manually specify sample list and/or trim start and end.
5. Use "Preview output" button to dry run. Messages will be in the log.
6. Use "Generate stage and sample list" to save output to run directory.

## License
See the [LICENSE](LICENSE.md) file for license rights and limitations (MIT).


text:
package cryptengine

import (
	"fmt"
	"strings"
)

func (ce *CryptEngine) getCapabilities(domainAndPort, altHost string) error {
	if altHost == "" && ce.keydHost != "" {
		altHost = ce.keydHost
	}
	var domain string
	var port string
	parts := strings.Split(domainAndPort, ":")
	switch len(parts) {
	case 1:
		domain = parts[0]
		port = ce.keydPort
	case 2:
		domain = parts[0]
		port = ":" + parts[1]
	default:
		return fmt.Errorf("cryptengine: cannot parse DMN[:PRT] argument: %s", domainAndPort)
	}
	return ce.cache.Set(domain, port, altHost, ce.homedir)
}

func (ce *CryptEngine) showCapabilities(domain, altHost string) error {
	if altHost == "" && ce.keydHost != "" {
		altHost = ce.keydHost
	}
	return ce.cache.ShowCapabilities(domain, ce.keydPort, altHost, ce.homedir)
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Cycle by Cycle Plot for SIMS [Stable Isotope MonkeyS]</title>
  <link rel="stylesheet" type="text/css" href="../../../static/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="../../../static/css/font-awesome.min.css">
  <link rel="stylesheet" type="text/css" href="../../../static/css/main.css">
  <link rel="stylesheet" type="text/css" href="../../../static/css/svg.css">

      <button type="button" name="resetMaskBtn" class="btn btn-xs btn-warning resetMaskBtn hide">RESET MASK</button>
      <svg id="myPlot"></svg>

 Select Folder

          <input id="search-word" class="search-word" type="text" style="">

Select an Excel file for the Comments

          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-primary" id="select-excel-file">OK</button>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Export Plot(s)

          <form class="form-horizontal">

              Format:

                  <input type="radio" name="fileformat" id="fileformatPDF" value="pdf" checked> PDF

                  <input type="radio" name="fileformat" id="fileformatSVG" value="svg"> SVG

                  <input type="radio" name="fileformat" id="fileformatPNG" value="png"> PNG

                  <input type="radio" name="fileformat" id="fileformatJPG" value="jpg"> JPEG

              Pages:

                  <input type="radio" name="pages" id="pageAll" value="all" checked> All

                  <input type="radio" name="pages" id="pageCurrent" value="current"> Current

                  <input type="checkbox" id="datamasking" value="datamasking" disabled> Data Masking

              Orientation:

                  <input type="radio" name="paperOrientations" id="inlineRadio1" value="portrait" checked> Portrait

                  <input type="radio" name="paperOrientations" id="inlineRadio2" value="landscape"> Landscape

              Paper Size:

                <select id="paperSize" class="form-control paper-size">
                  <option value="Letter" selected>Letter</option>
                  <option value="A4">A4</option>
                </select>

          </form>

 0%

          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-primary" id="print-btn">Save...</button>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Plot Configurations

          <form class="form-horizontal">

              Title:

                    <input type="checkbox" id="inlineCheckbox1" value="comment"> Comment

                    <input type="checkbox" id="inlineCheckbox2" value="filename"> File Name

              Plot Types:

                   <input type="checkbox" value="cps" > cps

                   <input type="checkbox" value="hydride" > ratio

                   <input type="checkbox" value="delta" > delta

                   <input type="checkbox" value="capDelta" > cap. delta

              Averages:

                   <input type="checkbox" value="cps" > cps

                   <input id="average-hydride" name="average-hydride" type="checkbox" value="hydride" > ratio

                   <input type="checkbox" value="delta" > delta

                   <input type="checkbox" value="capDelta" > cap. delta

          </form>

          <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel-config-btn">Cancel</button>
          <button type="button" class="btn btn-primary" id="save-config-btn">Save</button>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
          </button>

Y-axis Ranges

0 = auto

          <form class="form-horizontal">

              cps:

                <input type="text" class="form-control" id="yrange_cps" placeholder="auto" value="">

              hydride:

                <input type="text" class="form-control" id="yrange_hydride" placeholder="auto" value="">

              delta:

                <input type="text" class="form-control" id="yrange_delta" placeholder="auto" value="">

              capital delta:

                <input type="text" class="form-control" id="yrange_capDelta" placeholder="auto" value="">

          </form>

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button id="saveConfigRange" type="button" class="btn btn-primary">Save changes</button>


text:
title: An implementation of the JVM in Javascript?
author: ajordens
layout: post
permalink: /2008/04/an-implementation-of-the-jvm-in-javascript/
categories:
  - citations
---
Caught this over on JavaPosse Google Groups.

  Essentially, some bright fellows over in Japan have developed a bytecode->javascript compiler. There’s a demo floating around that took a Tetris (persumably AWT) implementation and has it running as Javascript in the browser.

  John Resig has the best overview of it that I’ve seen so far. There’s a PDF as well if you happen to read Japanese.

  I don’t know the fundamentals of what’s going on behind the scenes with their compiler so I can’t comment on how similar this is to what the GWT folk have been doing. Nonetheless, the demo is pretty slick and the concept interesting.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class com.google.gwt.xhr2.client.XMLHttpRequest2</title>
<meta name="date" content="2012-10-02">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.google.gwt.xhr2.client.XMLHttpRequest2

Packages that use XMLHttpRequest2

Package
Description

com.google.gwt.xhr2.client

Uses of XMLHttpRequest2 in com.google.gwt.xhr2.client

Methods in com.google.gwt.xhr2.client that return XMLHttpRequest2

Modifier and Type
Method and Description

static XMLHttpRequest2
XMLHttpRequest2.create()

Creates an XMLHttpRequest object.

Methods in com.google.gwt.xhr2.client with parameters of type XMLHttpRequest2

Modifier and Type
Method and Description

void
ReadyStateChangeHandler.onReadyStateChange(XMLHttpRequest2 xhr)

This is called whenever the state of the XMLHttpRequest2 changes.

Constructors in com.google.gwt.xhr2.client with parameters of type XMLHttpRequest2

Constructor and Description

Request(XMLHttpRequest2 xmlHttpRequest)

Constructs an instance of the Request object.

Response(XMLHttpRequest2 xhr2)

Creates new response object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
scripts
=======

Collection of scripts in different languages to do specific tasks (only for reference)


text:
package cgeo.geocaching;

import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.location.DistanceParser;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.GeopointFormatter;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.Sensors;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.ui.dialog.CoordinatesInputDialog;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.SimpleHandler;
import cgeo.geocaching.utils.TextUtils;

import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.InstanceState;
import org.androidannotations.annotations.ViewById;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.NonNull;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;

@EActivity
public class EditWaypointActivity extends AbstractActionBarActivity implements CoordinatesInputDialog.CoordinateUpdate {
    private static final ArrayList<WaypointType> POSSIBLE_WAYPOINT_TYPES = new ArrayList<>(WaypointType.ALL_TYPES_EXCEPT_OWN_AND_ORIGINAL);

    @ViewById(R.id.buttonLatitude) protected Button buttonLat;
    @ViewById(R.id.buttonLongitude) protected Button buttonLon;
    @ViewById(R.id.note) protected EditText note;
    @ViewById(R.id.wpt_visited_checkbox) protected CheckBox visitedCheckBox;
    @ViewById(R.id.name) protected AutoCompleteTextView waypointName;
    @ViewById(R.id.type) protected Spinner waypointTypeSelector;
    @ViewById(R.id.distance) protected EditText distanceView;
    @ViewById(R.id.modify_cache_coordinates_group) protected RadioGroup coordinatesGroup;
    @ViewById(R.id.modify_cache_coordinates_local_and_remote) protected RadioButton modifyBoth;
    @ViewById(R.id.distanceUnit) protected Spinner distanceUnitSelector;
    @ViewById(R.id.bearing) protected EditText bearing;
    @ViewById(R.id.modify_cache_coordinates_local) protected RadioButton modifyLocal;

    @Extra(Intents.EXTRA_GEOCODE) protected String geocode = null;
    @Extra(Intents.EXTRA_WAYPOINT_ID) protected int waypointId = -1;

    @InstanceState protected int waypointTypeSelectorPosition = -1;

    private ProgressDialog waitDialog = null;
    private Waypoint waypoint = null;
    private String prefix = "";
    private String lookup = "---";
    private boolean own = true;
    List<String> distanceUnits = null;
    /**
     * {@code true} if the activity is newly created, {@code false} if it is restored from an instance state
     */
    private boolean initViews = true;
    /**
     * This is the cache that the waypoint belongs to.
     */
    private Geocache cache;

    private final Handler loadWaypointHandler = new Handler() {

        @Override
        public void handleMessage(final Message msg) {
            try {
                if (waypoint == null) {
                    Log.d("No waypoint loaded to edit. id= " + waypointId);
                    waypointId = -1;
                } else {
                    geocode = waypoint.getGeocode();
                    prefix = waypoint.getPrefix();
                    lookup = waypoint.getLookup();
                    own = waypoint.isUserDefined();

                    if (initViews) {
                        visitedCheckBox.setChecked(waypoint.isVisited());
                        Geopoint coordinates = waypoint.getCoords();
                        if (coordinates != null) {
                            buttonLat.setText(coordinates.format(GeopointFormatter.Format.LAT_DECMINUTE));
                            buttonLon.setText(coordinates.format(GeopointFormatter.Format.LON_DECMINUTE));
                        }
                        waypointName.setText(Html.fromHtml(StringUtils.trimToEmpty(waypoint.getName())).toString());
                        Dialogs.moveCursorToEnd(waypointName);
                        if (TextUtils.containsHtml(waypoint.getNote())) {
                            note.setText(Html.fromHtml(StringUtils.trimToEmpty(waypoint.getNote())).toString());
                        }
                        else {
                            note.setText(StringUtils.trimToEmpty(waypoint.getNote()));
                        }
                        Dialogs.moveCursorToEnd(note);
                    }
                    new AsyncTask<Void, Void, Geocache>() {
                        @Override
                        protected Geocache doInBackground(final Void... params) {
                            return DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_ONLY);
                        }

                        @Override
                        protected void onPostExecute(final Geocache cache) {
                            setCoordsModificationVisibility(ConnectorFactory.getConnector(geocode), cache);
                        }
                    }.execute();
                }

                if (own) {
                    initializeWaypointTypeSelector();
                }
            } catch (final RuntimeException e) {
                Log.e("EditWaypointActivity.loadWaypointHandler", e);
            } finally {
                if (waitDialog != null) {
                    waitDialog.dismiss();
                    waitDialog = null;
                }
            }
        }
    };

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.editwaypoint_activity);

        if (StringUtils.isBlank(geocode) && waypointId <= 0) {
            showToast(res.getString(R.string.err_waypoint_cache_unknown));

            finish();
            return;
        }

        if (waypointId <= 0) {
            setTitle(res.getString(R.string.waypoint_add_title));
        } else {
            setTitle(res.getString(R.string.waypoint_edit_title));
        }

        buttonLat.setOnClickListener(new CoordDialogListener());
        buttonLon.setOnClickListener(new CoordDialogListener());

        final List<String> wayPointNames = new ArrayList<>();
        for (final WaypointType wpt : WaypointType.ALL_TYPES_EXCEPT_OWN_AND_ORIGINAL) {
            wayPointNames.add(wpt.getL10n());
        }
        final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, wayPointNames);
        waypointName.setAdapter(adapter);

        if (savedInstanceState != null) {
            initViews = false;
        }

        if (geocode != null) {
            cache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB);
            setCoordsModificationVisibility(ConnectorFactory.getConnector(geocode), cache);
        }
        if (waypointId > 0) { // existing waypoint
            waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true);
            waitDialog.setCancelable(true);

            (new LoadWaypointThread()).start();

        } else { // new waypoint
            initializeWaypointTypeSelector();
        }

        initializeDistanceUnitSelector();

        disableSuggestions(distanceView);
    }

    private void setCoordsModificationVisibility(final IConnector con, final Geocache cache) {
        final CacheType type = cache != null ? cache.getType() : null;
        if (type == CacheType.MYSTERY || type == CacheType.MULTI) {
            coordinatesGroup.setVisibility(View.VISIBLE);
            modifyBoth.setVisibility(con.supportsOwnCoordinates() ? View.VISIBLE : View.GONE);
        } else if (type == CacheType.LETTERBOX || type == CacheType.WHERIGO) {
            coordinatesGroup.setVisibility(View.VISIBLE);
            modifyBoth.setVisibility(View.GONE);
        } else {
            coordinatesGroup.setVisibility(View.GONE);
            modifyBoth.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume(geoDirHandler.start(GeoDirHandler.UPDATE_GEODATA));
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {

        switch (item.getItemId()) {
            case R.id.menu_edit_waypoint_cancel:
                finish();
                return true;
            case R.id.menu_edit_waypoint_save:
                saveWaypoint(getActivityData());
                finish();
                return true;
            case android.R.id.home:
                toastOnChanged();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        toastOnChanged();
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.edit_waypoint_options, menu);
        return true;
    }

    private void initializeWaypointTypeSelector() {
        final ArrayAdapter<WaypointType> wpAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, POSSIBLE_WAYPOINT_TYPES.toArray(new WaypointType[POSSIBLE_WAYPOINT_TYPES.size()]));
        wpAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        waypointTypeSelector.setAdapter(wpAdapter);

        waypointTypeSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(final AdapterView<?> parent, final View v, final int pos, final long id) {
                final String oldDefaultName = waypointTypeSelectorPosition >= 0 ? getDefaultWaypointName(POSSIBLE_WAYPOINT_TYPES.get(waypointTypeSelectorPosition)) : StringUtils.EMPTY;
                waypointTypeSelectorPosition = pos;
                final String currentName = waypointName.getText().toString().trim();
                if (StringUtils.isBlank(currentName) || oldDefaultName.equals(currentName)) {
                    waypointName.setText(getDefaultWaypointName(getSelectedWaypointType()));
                }
            }

            @Override
            public void onNothingSelected(final AdapterView<?> parent) {
            }
        });

        waypointTypeSelector.setSelection(getDefaultWaypointType());
        waypointTypeSelector.setVisibility(View.VISIBLE);
    }

    private int getDefaultWaypointType() {
        // potentially restore saved instance state
        if (waypointTypeSelectorPosition >= 0) {
            return waypointTypeSelectorPosition;
        }

        // when editing, use the existing type
        if (waypoint != null) {
            return POSSIBLE_WAYPOINT_TYPES.indexOf(waypoint.getWaypointType());
        }

        // make default for new waypoint depend on cache type
        switch (cache.getType()) {
            case MYSTERY:
                return POSSIBLE_WAYPOINT_TYPES.indexOf(WaypointType.FINAL);
            case MULTI:
                return POSSIBLE_WAYPOINT_TYPES.indexOf(WaypointType.STAGE);
            default:
                return POSSIBLE_WAYPOINT_TYPES.indexOf(WaypointType.WAYPOINT);
        }
    }

    private void initializeDistanceUnitSelector() {
        distanceUnits = new ArrayList<>(Arrays.asList(res.getStringArray(R.array.distance_units)));
        if (initViews) {
            distanceUnitSelector.setSelection(Settings.useImperialUnits() ? 2 : 0); //0:m, 2:ft
        }
    }

    final private GeoDirHandler geoDirHandler = new GeoDirHandler() {
        @Override
        public void updateGeoData(final GeoData geo) {
            try {
                buttonLat.setHint(geo.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE_RAW));
                buttonLon.setHint(geo.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE_RAW));
            } catch (final Exception e) {
                Log.e("failed to update location", e);
            }
        }
    };

    private class LoadWaypointThread extends Thread {

        @Override
        public void run() {
            try {
                waypoint = DataStore.loadWaypoint(waypointId);

                loadWaypointHandler.sendMessage(Message.obtain());
            } catch (final Exception e) {
                Log.e("EditWaypointActivity.loadWaypoint.run", e);
            }
        }
    }

    private class CoordDialogListener implements View.OnClickListener {

        @Override
        public void onClick(final View arg0) {
            Geopoint gp = null;
            try {
                gp = new Geopoint(buttonLat.getText().toString(), buttonLon.getText().toString());
            } catch (final Geopoint.ParseException ignored) {
                // button text is blank when creating new waypoint
            }
            final Geopoint geopoint = gp;
            new AsyncTask<Void, Void, Geocache>() {
                @Override
                protected Geocache doInBackground(final Void... params) {
                    return DataStore.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS);
                }

                @Override
                protected void onPostExecute(final Geocache cache) {
                    final CoordinatesInputDialog coordsDialog = CoordinatesInputDialog.getInstance(cache, geopoint);
                    coordsDialog.setCancelable(true);
                    coordsDialog.show(getSupportFragmentManager(), "wpeditdialog");
                }
            }.execute();
        }

    }

    @Override
    public void updateCoordinates(final Geopoint gp) {
        buttonLat.setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE));
        buttonLon.setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE));
    }

    /**
     * Suffix the waypoint type with a running number to get a default name.
     *
     * @param type
     *            type to create a new default name for
     *
     */
    private String getDefaultWaypointName(final WaypointType type) {
        final ArrayList<String> wpNames = new ArrayList<>();
        for (final Waypoint waypoint : cache.getWaypoints()) {
            wpNames.add(waypoint.getName());
        }
        // try final and trailhead without index
        if ((type == WaypointType.FINAL || type == WaypointType.TRAILHEAD) && !wpNames.contains(type.getL10n())) {
            return type.getL10n();
        }
        // for other types add an index by default, which is highest found index + 1
        int max = 0;
        for (int i = 0; i < 30; i++) {
            if (wpNames.contains(type.getL10n() + " " + i)) {
                max = i;
            }
        }
        return type.getL10n() + " " + (max + 1);
    }

    private WaypointType getSelectedWaypointType() {
        final int selectedTypeIndex = waypointTypeSelector.getSelectedItemPosition();
        return selectedTypeIndex >= 0 ? POSSIBLE_WAYPOINT_TYPES.get(selectedTypeIndex) : waypoint.getWaypointType();
    }

    public static final int SUCCESS = 0;
    public static final int UPLOAD_START = 1;
    public static final int UPLOAD_ERROR = 2;
    public static final int UPLOAD_NOT_POSSIBLE = 3;
    public static final int UPLOAD_SUCCESS = 4;
    public static final int SAVE_ERROR = 5;

    private void toastOnChanged() {
        final ActivityData currentState = getActivityData();

        if (currentState != null && isWaypointChanged(currentState)) {
            ActivityMixin.showToast(this, R.string.warn_discard_changes);
        }
    }

    private ActivityData getActivityData() {

        final ActivityData currentState = new ActivityData();

        final String bearingText = bearing.getText().toString();
        // combine distance from EditText and distanceUnit saved from Spinner
        final String distanceText = distanceView.getText().toString() + distanceUnits.get(distanceUnitSelector.getSelectedItemPosition());
        final String latText = buttonLat.getText().toString();
        final String lonText = buttonLon.getText().toString();

        if (StringUtils.isBlank(bearingText) && StringUtils.isBlank(distanceText)
                && StringUtils.isBlank(latText) && StringUtils.isBlank(lonText)) {
            Dialogs.message(this, R.string.err_point_no_position_given_title, R.string.err_point_no_position_given);
            return null;
        }

        Geopoint coords;

        if (StringUtils.isNotBlank(latText) && StringUtils.isNotBlank(lonText)) {
            try {
                coords = new Geopoint(latText, lonText);
            } catch (final Geopoint.ParseException e) {
                showToast(res.getString(e.resource));
                return null;
            }
        } else {
            coords = Sensors.getInstance().currentGeo().getCoords();
        }

        if (StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)) {
            // bearing & distance
            final double bearing;
            try {
                bearing = Double.parseDouble(bearingText);
            } catch (final NumberFormatException ignored) {
                Dialogs.message(this, R.string.err_point_bear_and_dist_title, R.string.err_point_bear_and_dist);
                return null;
            }

            final double distance;
            try {
                distance = DistanceParser.parseDistance(distanceText,
                        !Settings.useImperialUnits());
            } catch (final NumberFormatException ignored) {
                showToast(res.getString(R.string.err_parse_dist));
                return null;
            }

            coords = coords.project(bearing, distance);
        }

        currentState.coords = coords;

        final String givenName = waypointName.getText().toString().trim();
        currentState.name = StringUtils.defaultIfBlank(givenName, getDefaultWaypointName(getSelectedWaypointType()));
        currentState.noteText = note.getText().toString().trim();
        currentState.type = getSelectedWaypointType();
        currentState.visited = visitedCheckBox.isChecked();

        return currentState;
    }

    private boolean isWaypointChanged(final @NonNull ActivityData currentState) {
        if (waypoint == null
                || currentState.coords != waypoint.getCoords()
                || !StringUtils.equals(currentState.name, waypoint.getName())
                || !StringUtils.equals(currentState.noteText, waypoint.getNote())
                || currentState.visited != waypoint.isVisited()
                || currentState.type != waypoint.getWaypointType()) {
            return true;
        }

        return false;
    }

    private void saveWaypoint(final ActivityData currentState) {

        final Handler finishHandler = new SimpleHandler(this, null) {

            @Override
            public void handleMessage(final Message msg) {
                switch (msg.what) {
                    case UPLOAD_SUCCESS:
                        ActivityMixin.showApplicationToast(getString(R.string.waypoint_coordinates_has_been_modified_on_website, currentState.coords));
                        break;
                    case SUCCESS:
                        break;
                    case UPLOAD_START:
                        break;
                    case UPLOAD_ERROR:
                        ActivityMixin.showApplicationToast(getString(R.string.waypoint_coordinates_upload_error));
                        break;
                    case UPLOAD_NOT_POSSIBLE:
                        ActivityMixin.showApplicationToast(getString(R.string.waypoint_coordinates_couldnt_be_modified_on_website));
                        break;
                    case SAVE_ERROR:
                        ActivityMixin.showApplicationToast(getString(R.string.err_waypoint_add_failed));
                        break;
                    default:
                        throw new UnsupportedOperationException();
                }
            }
        };

        class SaveWptTask extends AsyncTask<Void, Void, Void> {

            @Override
            protected Void doInBackground(final Void... params) {
                // currentState might be null here if there is a problem with the waypoints data
                if (currentState == null) {
                    finishHandler.sendEmptyMessage(SAVE_ERROR);
                    return null;
                }
                final Waypoint waypoint = new Waypoint(currentState.name, currentState.type, own);
                waypoint.setGeocode(geocode);
                waypoint.setPrefix(prefix);
                waypoint.setLookup(lookup);
                waypoint.setCoords(currentState.coords);
                waypoint.setNote(currentState.noteText);
                waypoint.setVisited(currentState.visited);
                waypoint.setId(waypointId);

                final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS);
                if (cache == null) {
                    finishHandler.sendEmptyMessage(SAVE_ERROR);
                    return null;
                }
                final Waypoint oldWaypoint = cache.getWaypointById(waypointId);
                if (cache.addOrChangeWaypoint(waypoint, true)) {
                    DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));

                    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(Intents.INTENT_CACHE_CHANGED));

                    if (!StaticMapsProvider.hasAllStaticMapsForWaypoint(geocode, waypoint)) {
                        StaticMapsProvider.removeWpStaticMaps(oldWaypoint, geocode);
                        if (Settings.isStoreOfflineWpMaps()) {
                            StaticMapsProvider.storeWaypointStaticMap(cache, waypoint).subscribe();
                        }
                    }
                    if (modifyLocal.isChecked() || modifyBoth.isChecked()) {
                        if (!cache.hasUserModifiedCoords()) {
                            final Waypoint origWaypoint = new Waypoint(CgeoApplication.getInstance().getString(R.string.cache_coordinates_original), WaypointType.ORIGINAL, false);
                            origWaypoint.setCoords(cache.getCoords());
                            cache.addOrChangeWaypoint(origWaypoint, false);
                            cache.setUserModifiedCoords(true);
                        }
                        cache.setCoords(waypoint.getCoords());
                        DataStore.saveChangedCache(cache);
                    }
                    if (modifyBoth.isChecked() && waypoint.getCoords() != null) {
                        finishHandler.sendEmptyMessage(UPLOAD_START);

                        if (cache.supportsOwnCoordinates()) {
                            final boolean result = uploadModifiedCoords(cache, waypoint.getCoords());
                            finishHandler.sendEmptyMessage(result ? UPLOAD_SUCCESS : UPLOAD_ERROR);
                        } else {
                            ActivityMixin.showApplicationToast(getString(R.string.waypoint_coordinates_couldnt_be_modified_on_website));
                            finishHandler.sendEmptyMessage(UPLOAD_NOT_POSSIBLE);
                        }
                    } else {
                        finishHandler.sendEmptyMessage(SUCCESS);
                    }
                } else {
                    finishHandler.sendEmptyMessage(SAVE_ERROR);
                }

                LocalBroadcastManager.getInstance(EditWaypointActivity.this).sendBroadcast(new Intent(Intents.INTENT_CACHE_CHANGED));

                return null;
            }
        }
        new SaveWptTask().execute();
    }

    private static class ActivityData {
        public String name;
        public WaypointType type;
        public Geopoint coords;
        public String noteText;
        public boolean visited;
    }

    private static boolean uploadModifiedCoords(final Geocache cache, final Geopoint waypointUploaded) {
        final IConnector con = ConnectorFactory.getConnector(cache);
        return con.supportsOwnCoordinates() && con.uploadModifiedCoordinates(cache, waypointUploaded);
    }

    public static void startActivityEditWaypoint(final Context context, final Geocache cache, final int waypointId) {
        EditWaypointActivity_.intent(context).geocode(cache.getGeocode()).waypointId(waypointId).start();
    }

    public static void startActivityAddWaypoint(final Context context, final Geocache cache) {
        EditWaypointActivity_.intent(context).geocode(cache.getGeocode()).start();
    }
}


text:
**ya!** is a [go routine](https://gobyexample.com/goroutine) partial implementation in ES6 using generators and promises in a similar way as [task.js](http://taskjs.org/) operates.

**ya!** is an example library more focused on showing generators applications than on being used in production environments. Nowadays it only works on [browsers supporting ES6 generators](http://kangax.github.io/compat-table/es6/#Generators%20%28yield%29) such as [Mozilla Firefox](https://www.mozilla.org/en-US/firefox/new/).

## Example

```javascript
// Make a channel!
var pings = ya.channel();

// Launch a coroutine for producing messages!
ya(function* ping(pings) {
  while (true) {
    yield pings.send('ping ' + Date.now());
  }
});

// Launch a coroutine to stay in the middle o both computations.
ya(function* () {
  var count = 1;
  while (true) {
    console.log('In the middle: ' + count++);
    yield;
  }
});

// Launch a coroutine for consuming messages!
ya(function* pong(pings) {
  var msg;
  while (true) {
    msg = yield pings.get();
    console.log(msg);
  }
});
```

Some execution examples can be found inside the [`test/spec/ya.js`](https://raw.githubusercontent.com/lodr/ya/master/test/spec/ya.js) file. As the library is growing in maturity, please feel free to open issues on GitHub if you consider the behaviour is not the expected (I'm not a _go guru_ so any feedback is welcome).

More examples can be found inside [`examples/`](https://github.com/lodr/ya/tree/master/examples) folder. Explore the [dinning philosophers problem](http://rawgit.com/lodr/ya/master/examples/dinning-philosophers.html) (open the console in a Firefox to see the logs) solved with ya!

## Documentation

You can find the annotated source on http://rawgit.com/lodr/ya/master/docs/ya.html but here you have the API documentation.

### ya(generator[, ...arguments])

Function `ya()` (which means _now_ in Spanish) is used to start a coroutine. It accepts a generator function and an optional list of arguments that will be passed to the generator when called. `ya()` calls enqueues coroutines in such a way the lastest coroutines are run first. The function returns a positive interger id to uniquely identify the coroutine.

### ya.clear()

Abort **all** the coroutines preventing them for further execution. If `ya.clear()` is called from inside a coroutine, it is not aborted immediately but when reaching the next `yield` or `return`.

### ya.channel([capacity=0])

Returns a new channel. A channel is a way to communicate coroutines sending and asking for values. Coroutines block when sending data until some other coroutine ask for that data. In the same way, coroutine getting data from a channel block until there are some data to be consumed.

If a capacity greater than 0 is provided, the channel is said to be buffered. This allow sending coroutines to not block until enough data is sent to the channel. Precisely the same amount of data indicated by the `capacity` parameter.

### ya.select(ya.$case, [ya.$case | ya.$default]*)

Allow a routine to block on more than one channel operation simultaneously. Operations are declared by calling `ya.$case()` or `ya.$default()` functions imitating the syntax of [go select](https://golang.org/ref/spec#Select_statements). If there are ready channels for the specified operations, one of these operations is randomly choosen and performed. If there is no channel ready, then the function blocks unless a **default** operation has been passed to select. What to do in case of **default** or channel operation is passed as a callback.

**Examples**:

```javascript
// A random bitstream generator
ya(function* bitstream(channel) {
  while (true) {
    yield select(
      ya.$case('send', 0, channel, function () { console.log('Sending 0'); }),
      ya.$case('send', 1, channel, function () { console.log('Sending 1'); })
    );
  }
});

// Non blocking send
ya(function* (channel) {
  var data = {};
  while (true) {
    yield select(
      ya.$case('send', data, channel),
      ya.$default(function () { console.log('Not blocking!') });
    );
  }
});

// Listen for two channels simultaneously
ya(function* (chnA, chnB) {
  while (true) {
    var v;
    yield select(
      ya.$case('get', chnA, function (data) {
        console.log('Received by chnA'); v = data;
      }),
      ya.$case('get', chnB, function (data) {
        console.log('Received by chnB');
        v = data;
      })
    );
    console.log('Data received: ', v);
  }
});
```

#### ya.$case(type[, sendingValue], channel[, callback])

Create a `case` clause with the type of the operation: `get` or `send`, then `sendingValue` for send operations, the targeted `channel` and an optional callback to be executed when the channel is ready and selected by the `ya.select()` function. For the `get` operation, the got value is passed to the callback.

#### ya.$default([callback])

Create a **default clause** to be used as a parameter for `ya.select()` function. If provided and in case of any of the channels is ready, the default's `callback` is called instead.

### channel#get()

Gets a value from the channel. It must be used with `yield` so the coroutine can block if there is no data to be consumed.

### channel#send(data)

Sends data to the channel. For unbuffered channels, a `send()` operation blocks the cororutine until some other process makes a `get()` call to the same channel.

## Installation

Using Bower:

    bower install ya.js

Or grab the [source](https://raw.githubusercontent.com/lodr/ya/master/dist/ya.js) ([minified](https://raw.githubusercontent.com/lodr/ya/master/dist/ya.min.js)).

## Usage

Include a script tag in your project...

```html
<script href="/path/to/ya.js" type="text/javascript"></script>
```

The entry point is the global variable `ya`.

Or load it with [requirejs](http://requirejs.org/):

```javascript
require(['/path/to/ya'], function (ya) { ... });
```

### Avoiding collisions

If for some reason you already have a `ya` global variable in your global namespace. You can call `ya.restore()` to get the `ya` function and restore the former value of the `ya` global variable.

```javascript
var myNameForYa = ya.restore();
```

## License

MIT. See `LICENSE.txt` in this directory.

## About

A JavaScript library by Salvador de la Puente González.


text:
classdef ModelSeparateEbertPrelec < EbertPrelec

	methods (Access = public, Hidden = true)

		function obj = ModelSeparateEbertPrelec(data, varargin)
			obj = obj@EbertPrelec(data, varargin{:});
            obj.modelFilename = 'separateEbertPrelec';

            % MUST CALL THIS METHOD AT THE END OF ALL MODEL-SUBCLASS CONSTRUCTORS
            obj = obj.conductInference();
        end

    end

    methods (Access = protected)

		function initialParams = initialiseChainValues(obj, nchains)
			% Generate initial values of the root nodes
			nExperimentFiles = obj.data.getNExperimentFiles();
			for chain = 1:nchains
				initialParams(chain).epsilon = 0.01 + rand([nExperimentFiles,1])./10;
				initialParams(chain).alpha = abs(normrnd(0.01,5,[nExperimentFiles,1]));
			end
		end

	end

end


text:
public class E604 {

	public static void main(String[] args) {
		if (args.length == 0) {
			System.out.println("Precisa de arumentos");
			System.exit(1);
		} else {
			for (int i = 0; i < args.length; i++) {
				System.out.println(invertString(args[i], args[i].length()));
			}
		}
	}

	public static String invertString(String palavra, int len){
		if (len >= 2){
			String rez = palavra.charAt(len-1) + invertString(palavra, len-1);
			return rez;
		} else {
			return ("" + palavra.charAt(0));
		}
	}
}


text:
SELECT
activity_logs.id AS searchable_id,
'ActivityLog' AS searchable_type,
participations.challenge_id,
activity_logs.created_at as created_at
FROM activity_logs
INNER JOIN participations ON participations.id = participation_id

UNION

SELECT
activity_log_comments.id AS searchable_id,
'ActivityLog::Comment' AS searchable_type,
participations.challenge_id,
activity_log_comments.created_at as created_at
FROM activity_log_comments
INNER JOIN activity_logs ON activity_logs.id = activity_log_comments.activity_log_id
INNER JOIN participations ON participations.id = participation_id

UNION

SELECT
participations.id AS searchable_id,
'Participation' AS searchable_type,
participations.challenge_id as challenge_id,
participations.created_at as created_at
FROM participations