text:
package com.mauriciotogneri.designpatterns.concurrency.doublecheckedlocking;

public class DatabaseConnection
{
    private static volatile DatabaseConnection helper;

    private DatabaseConnection()
    {
        System.out.println("Initializing database...");
    }

    public static DatabaseConnection getInstance()
    {
        DatabaseConnection result = DatabaseConnection.helper;

        if (result == null)
        {
            synchronized (DatabaseConnection.class)
            {
                result = DatabaseConnection.helper;

                if (result == null)
                {
                    DatabaseConnection.helper = result = new DatabaseConnection();
                }
            }
        }

        return result;
    }

    public void execute(String query)
    {
        System.out.println("Executing query: " + query);
    }
}


text:
A plugin for the Pelican_ static website generator that
embeds a BibTeX publication list in a page or article
using a ``publications`` restructured text directive.

Usage::

    .. publications:: path/to/publications.bib
        :template: path/to/publications.html
        :sort: date

By default pelican_publications uses a ``publications`` template
in the Pelican theme. This can be overridden by setting
the template option as a path to a Jinja2 template.
The template is passed one parameter, ``publications``, which is
a list of BibTeX entries.
These BibTeX entries are simple dictionaries
in the format used by the bibtexparser_ Python package, with a few
customisations such as converting page ranges to use an html en dash
and splitting the author field into a list of authors.

Possible sort options are:

date
    Sort by publication date (this is the default).

key
    Sort by BibTeX key.

name
    Sort by author names.

.. _Pelican: http://docs.getpelican.com
.. _bibtexparser: https://bibtexparser.readthedocs.org

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sber. Akad. Wiss. Wien, Math. -naturw. Kl. , Abt. 1 123: 108 (1914)

#### Original name
Lasiosphaeria depilata Fuckel, 1874

### Remarks
null


text:
H2O - an optimized HTTP server with support for HTTP/1.x and HTTP/2
===

[![Build Status](https://travis-ci.org/h2o/h2o.svg?branch=master)](https://travis-ci.org/h2o/h2o)

Copyright (c) 2014,2015 [DeNA Co., Ltd.](http://dena.com/), [Kazuho Oku](https://github.com/kazuho/), [Tatsuhiko Kubo](https://github.com/cubicdaiya/), [Domingo Alvarez Duarte](https://github.com/mingodad/), [Nick Desaulniers](https://github.com/nickdesaulniers/), [Marc Hörsken](https://github.com/mback2k), [Masahiro Nagano](https://github.com/kazeburo/), Jeff Marrison, [Daisuke Maki](https://github.com/lestrrat/), [Laurentiu Nicola](https://github.com/GrayShade/), [Justin Zhu](https://github.com/zlm2012/), [Tatsuhiro Tsujikawa](https://github.com/tatsuhiro-t), [Ryosuke Matsumoto](https://github.com/matsumoto-r)

H2O is a new generation HTTP server.
Not only is it very fast, it also provides much quicker response to end-users when compared to older generations of HTTP servers.

Written in C and licensed under [the MIT License](http://opensource.org/licenses/MIT), it can also be used as a library.

For more information, please refer to the documentation at [h2o.examp1e.net](https://h2o.examp1e.net).


text:
include(Compiler/XL)
__compiler_xl(Fortran)

set(CMAKE_Fortran_SUBMODULE_SEP "_")
set(CMAKE_Fortran_SUBMODULE_EXT ".smod")

set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-qfixed") # [=<right_margin>]
set(CMAKE_Fortran_FORMAT_FREE_FLAG "-qfree") # [=f90|ibm]

set(CMAKE_Fortran_MODDIR_FLAG "-qmoddir=")

set(CMAKE_Fortran_DEFINE_FLAG "-WF,-D")

# -qthreaded     = Ensures that all optimizations will be thread-safe
# -qhalt=e       = Halt on error messages (rather than just severe errors)
string(APPEND CMAKE_Fortran_FLAGS_INIT " -qthreaded -qhalt=e")

# xlf: 1501-214 (W) command option E reserved for future use - ignored
set(CMAKE_Fortran_CREATE_PREPROCESSED_SOURCE)
set(CMAKE_Fortran_CREATE_ASSEMBLY_SOURCE)


text:
int empty_holder_for_reserve_place_for_function(int x) {

    //SSL_get0_next_proto_negotiated(NULL, NULL, NULL);

    return x*x;
}


text:
class Categories::SubscriptionsController < ApplicationController
  respond_to :html
  before_filter :authenticate_user!

  def create
    parent.users << current_user

    flash[:notice] = I18n.t('explore.index.success_follow', name: parent.name_pt)
    redirect_to explore_path(anchor: "by_category_id/#{parent.id}")
  end

  def destroy
    parent.users.delete(current_user)

    flash[:notice] = I18n.t('explore.index.success_unfollow', name: parent.name_pt)
    redirect_to explore_path(anchor: "by_category_id/#{parent.id}")
  end

  protected

  def parent
    @category ||= Category.find params[:id]
  end
end


text:
namespace lldb_private {

template <typename T> std::unique_ptr<T> clone(const std::unique_ptr<T> &src) {
  if (src)
    return std::make_unique<T>(*src);
  return nullptr;
}

template <typename T> std::shared_ptr<T> clone(const std::shared_ptr<T> &src) {
  if (src)
    return std::make_shared<T>(*src);
  return nullptr;
}

} // namespace lldb_private
#endif


text:
package com.senacor.ddt.objectmatrix.beanfiller.strategy.propertyutils;

import java.lang.reflect.Array;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.senacor.ddt.objectmatrix.beanfiller.BadIndexException;
import com.senacor.ddt.objectmatrix.beanfiller.BeanAccessStrategy;
import com.senacor.ddt.objectmatrix.beanfiller.BeanFiller;
import com.senacor.ddt.objectmatrix.beanfiller.NoConcreteClassException;
import com.senacor.ddt.objectmatrix.beanfiller.PropertyAccessException;
import com.senacor.ddt.typetransformer.Transformer;
import com.senacor.ddt.util.ParamChecker;

public class JavaBeanAccessStrategy implements BeanAccessStrategy {
  private static final Log log = LogFactory.getLog(JavaBeanAccessStrategy.class);

  private Transformer transformer;

  private final Map wrappedObjects = new IdentityHashMap();

  public JavaBeanAccessStrategy() {
    // nothing to be done
  }

  public Class getPropertyType(final Object rawBean, final String propertyName, final Properties annotation) {
    final BeanWrapper bean = wrap(rawBean, annotation);

    return bean.getPropertyType(propertyName, annotation);
  }

  private BeanWrapper wrap(final Object rawBean, final Properties annotation) {
    if (this.wrappedObjects.containsKey(rawBean)) {
      return (BeanWrapper) this.wrappedObjects.get(rawBean);
    } else if (rawBean instanceof BeanWrapper) {
      return (BeanWrapper) rawBean;
    } else if (rawBean instanceof ObjectHolder) {
      return wrap(((ObjectHolder) rawBean).getWrapped(), annotation);
    } else {
      final BeanWrapper wrapped = createWrapper(rawBean.getClass(), rawBean, null, null, annotation);
      return wrapped;
    }
  }

  public Object instantiateAndSet(final Object rawBean, final String propertyName, final Class typeToInstantiate,
      final Properties annotation) {
    final BeanWrapper bean = wrap(rawBean, annotation);
    try {
      Class type = bean.resolveTypeForInstantiation(propertyName, typeToInstantiate, annotation);
      type = getConcreteType(type);
      Object value;
      if (mustBeWrapped(type)) {
        value = createWrapper(type, null, bean, propertyName, annotation);
      } else {
        value = instantiate(type);
      }
      writeProperty(bean, propertyName, value, annotation);
      return value;
    } catch (final Exception e) {
      throw new PropertyAccessException(bean.getClass(), propertyName, e);
    }
  }

  public Object instantiate(final Class type) throws PropertyAccessException {
    ParamChecker.notNull("type", type);
    final Object result;
    try {
      if (type.isArray()) {
        result = Array.newInstance(type.getComponentType(), 1);
      } else {
        result = type.newInstance();
      }
    } catch (final Exception e) {
      throw new CannotInstantiateException(type, e);
    }
    return result;
  }

  private BeanWrapper createWrapper(final Class type, final Object toBeWrapped, final Object parentBean,
      final String propertyNameInParent, final Properties annotation) {
    final BeanWrapper wrapper;
    try {
      if (Map.class.isAssignableFrom(type)) {
        wrapper = new MapWrapper(type, toBeWrapped, annotation, this.transformer);
      } else if (Collection.class.isAssignableFrom(type)) {
        if (List.class.isAssignableFrom(type)) {
          wrapper =
              new ListWrapper(type, toBeWrapped, parseMinimumSizeForIndexedProperty(annotation), annotation,
                  this.transformer);
        } else {
          // use generic collection wrapper for all collections that are not lists
          wrapper = new CollectionWrapper(type, toBeWrapped, annotation, this.transformer);
        }
      } else if (type.isArray()) {
        wrapper =
            new ArrayWrapper(type, toBeWrapped, parseMinimumSizeForIndexedProperty(annotation), parentBean,
                propertyNameInParent, this, this.transformer, annotation);
      } else {
        wrapper = new JavaBeanWrapper(toBeWrapped);
      }
    } catch (final Exception e) {
      throw new PropertyAccessException(parentBean.getClass(), propertyNameInParent, e);
    }
    if (toBeWrapped != null) {
      this.wrappedObjects.put(toBeWrapped, wrapper);
    }
    return wrapper;
  }

  private int parseMinimumSizeForIndexedProperty(final Properties annotations) {
    try {
      return Integer.parseInt(annotations.getProperty(BeanFiller.AnnotationKeys.LENGTH, "0"));
    } catch (final NumberFormatException e) {
      throw new BadIndexException("can't parse index", e);
    }
  }

  private static final Set /* <Class> */WRAPPED_TYPES = new HashSet() {
    {
      add(List.class);
      add(Set.class);
      add(Collection.class);
      add(Map.class);
    }
  };

  private boolean mustBeWrapped(final Class type) {
    if (type.isArray()) {
      return true;
    } else {
      final Iterator iterator = WRAPPED_TYPES.iterator();
      while (iterator.hasNext()) {
        final Class wrappedType = (Class) iterator.next();
        if (wrappedType.isAssignableFrom(type)) {
          return true;
        }
      }
    }
    return false;
  }

  public Object writeProperty(final Object rawBean, final String propertyName, final Object propertyValue,
      final Properties annotation) {
    final BeanWrapper bean = wrap(rawBean, annotation);
    final Object actualPropertyValue;
    {
      if (propertyValue instanceof BeanWrapper) {
        actualPropertyValue = ((BeanWrapper) propertyValue).getWrapped();
      } else {
        actualPropertyValue = propertyValue;
      }
    }
    try {
      (bean).write(propertyName, actualPropertyValue);
    } catch (final Exception e) {
      throw new PropertyAccessException(bean.getClass(), propertyName, e);
    }

    return propertyValue;
  }

  public Object readProperty(final Object rawBean, final String propertyName, final Properties annotation) {
    final BeanWrapper bean = wrap(rawBean, annotation);
    try {
      final Object property = (bean).read(propertyName);
      if ((property != null) && mustBeWrapped(property.getClass())) {
        return createWrapper(property.getClass(), property, bean, propertyName, annotation);
      } else {
        return property;
      }
    } catch (final Exception e) {
      throw new PropertyAccessException(bean.getClass(), propertyName, e);
    }
  }

  public boolean doesObjectImplement(final Class typeToImplement, final Object objectToCheck) {
    if (objectToCheck instanceof BeanWrapper) {
      return doesObjectImplement(typeToImplement, ((BeanWrapper) objectToCheck).getWrapped());
    } else if (objectToCheck != null) {
      return typeToImplement.isAssignableFrom(objectToCheck.getClass());
    } else {
      return false;
    }
  }

  public void setTransformer(final Transformer transformer) {
    ParamChecker.notNull("transformer", transformer);
    this.transformer = transformer;
  }

  public ObjectHolder createHolder(final Object bean, final Properties annotation) {
    if (mustBeWrapped(bean.getClass())) {
      return createWrapper(bean.getClass(), bean, null, null, annotation);
    } else {
      return new ObjectHolder() {
        public Object getWrapped() {
          return bean;
        }
      };
    }
  }

  /**
   * @see #getConcreteType(Class)
   */
  private final Map abstractToConcrete = new HashMap() {
    {
      put(Collection.class, List.class);
      put(List.class, ArrayList.class);
      put(Set.class, HashSet.class);
      put(Map.class, HashMap.class);
      put(Number.class, Integer.class);
      put(Calendar.class, GregorianCalendar.class);
    }
  };

  public Class getConcreteType(final Class type) {
    Class result = type;
    while ((result != null) && (!result.isPrimitive())
        && (result.isInterface() || Modifier.isAbstract(result.getModifiers())) && !result.isArray()) {
      result = (Class) this.abstractToConcrete.get(result);
    }
    if (result == null) {
      throw new NoConcreteClassException(type);
    } else {
      return result;
    }
  }
}


text:
package v1alpha2

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// NewVolume creates a reference of a Volumeattach CRD object
func NewVolume(name, namespace, node, podNamespace, podName, clusterName, mountDir string, readOnly bool) *Volume {
	volumeAttachmentObj := &Volume{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: namespace,
		},
		Attachments: []Attachment{
			{
				Node:         node,
				PodNamespace: podNamespace,
				PodName:      podName,
				ClusterName:  clusterName,
				MountDir:     mountDir,
				ReadOnly:     readOnly,
			},
		},
	}

	return volumeAttachmentObj
}


text:
package com.google.jenkins.plugins.stacksmith;

import java.io.IOException;
import java.io.PrintStream;
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.logging.Logger;

import javax.annotation.Nullable;

import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * Handles interaction with the Bitnami Stacksmith API.
 */
@ThreadSafe
public class BitnamiApiManager {
  /**
   * The base URL for all API requests.
   */
  public static final String API_BASE_URL
      = "https://stacksmith.bitnami.com/api/v1/";
  /**
   * The URL for the stack API.
   */
  public static final String STACKS_URL = API_BASE_URL + "stacks";
  private static final Logger LOGGER = Logger.getLogger(
      BitnamiApiManager.class.getName());
  private static final CombinedLogger COMBINED_LOGGER = new CombinedLogger(
      LOGGER);
  private static final BitnamiApiManager INSTANCE = new BitnamiApiManager(
      HttpClients.createDefault());

  protected final CloseableHttpClient httpClient;

  @VisibleForTesting
  BitnamiApiManager(CloseableHttpClient httpClient) {
    this.httpClient = Preconditions.checkNotNull(httpClient);
  }

  /**
   * @return the default instance of {@link BitnamiApiManager}.
   */
  public static BitnamiApiManager get() {
    return INSTANCE;
  }

  /**
   * Executes the given request, catching common exceptions.
   * @return the response entity, if any, as a {@link String} - or {@code null}
   * if an error occurs.
   */
  protected String wrappedExecute(HttpUriRequest request,
      PrintStream buildLogger) {
    if (request == null) {
      COMBINED_LOGGER.logWarning(buildLogger,
          "Cannot execute a null HTTP request.");
      return null;
    }

    CloseableHttpResponse response = null;
    String result = null;
    try {
      LOGGER.finer("Executing HTTP request: " + request);
      response = httpClient.execute(request);
      if (response == null) {
        COMBINED_LOGGER.logWarning(buildLogger,
            "Null response from Stacksmith API.");
        return null;
      }
      if (response.getStatusLine() != null) {
        LOGGER.finer("HTTP response status: " + response.getStatusLine());
      }
      result = EntityUtils.toString(response.getEntity());
      LOGGER.finest("HTTP response entity: "
          + (result == null ? "null" : result));
    } catch (IOException e) {
      COMBINED_LOGGER.logWarning(buildLogger,
          "IOException when contacting Stackmith: " + e);
      return null;
    } finally {
      try {
        if (response != null) {
          response.close();
        } else {
          // This has already been logged above; no need to log it twice.
          return null;
        }
      } catch (IOException e) {
        COMBINED_LOGGER.logWarning(buildLogger,
            "IOException when closing HTTP resposne: " + e);
        return null;
      }
    }
    return result;
  }

  /**
   * Queries the Stacksmith discovery API to get the set of valid entities
   * of the given type.
   * @return the set of entities, or {@code null} if an error occurs.
   */
  protected NavigableSet<VersionedEntity> fetchEntities(VersionedEntityType category) {
    if (category == null) {
      LOGGER.warning("Stack entity type is null, can't fetch entity.");
      return null;
    }
    NavigableSet<VersionedEntity> entities = null;
    HttpGet httpGet = new HttpGet(category.getListUrl());
    String result = wrappedExecute(httpGet, null);
    if (result == null) {
      // This is at FINE rather than WARNING because we expect wrappedExecute
      // to log a warning for any major error.
      LOGGER.fine("No JSON result from querying the Discovery API.");
      return null;
    }

    try {
      JSONObject json = JSONObject.fromObject(result);
      entities = parseEntities(json);
    } catch (JSONException e) {
      LOGGER.warning("JSONException while parsing entities: " + e);
      return null;
    }
    return entities;
  }

  /**
   * Queries the Stacksmith discovery API to get the set of valid
   * operating systems that can be used in a Stack.
   * @return the set of operating systems, or {@code null} if an error occurs.
   */
  public NavigableSet<VersionedEntity> fetchOperatingSystems() {
    return fetchEntities(VersionedEntityType.OPERATING_SYSTEM);
  }

  /**
   * Queries the Stacksmith discovery API to get the set of valid components
   * that can be used in a Stack.
   * @return the set of components, or {@code null} if an error occurs.
   */
  public NavigableSet<VersionedEntity> fetchComponents() {
    return fetchEntities(VersionedEntityType.COMPONENT);
  }

  /**
   * Queries the Stacksmith discovery API to get the set of dependencies associated
   * with a given entity.
   * @param id the {@link String} ID of the entity to get data for.
   * @return the set of dependency IDs, or {@code null} if an error occurs.
   */
  public NavigableSet<String> fetchDependenciesForEntity(String id) {
    if (id == null) {
      LOGGER.warning("Cannot fetch dependencies for a null entity ID");
      return null;
    }
    NavigableSet<String> dependencies = null;
    HttpGet httpGet = new HttpGet(makeDependenciesForEntityUrl(id));
    String result = wrappedExecute(httpGet, null);
    if (result == null) {
      LOGGER.fine("No JSON result.");
      return null;
    }

    try {
      JSONObject json = JSONObject.fromObject(result);
      dependencies = parseDependencyIds(json);
    } catch (JSONException e) {
      LOGGER.warning("JSONException while parsing dependencies: " + e);
      return null;
    }
    return dependencies;
  }

  /**
   * Queries the Stacksmith discovery API to get the set of flavors associated
   * with a given entity.
   * @param id the {@link String} ID of the entity to get data for.
   * @return the set of flavor IDs, or {@code null} if an error occurs.
   */
  public NavigableSet<String> fetchFlavorsForEntity(String id) {
    if (id == null) {
      LOGGER.warning("Cannot fetch flavors for a null entity ID");
      return null;
    }
    NavigableSet<String> flavors = null;
    HttpGet httpGet = new HttpGet(makeFlavorsForEntityUrl(id));
    String result = wrappedExecute(httpGet, null);
    if (result == null) {
      LOGGER.fine("No JSON result.");
      return null;
    }

    try {
      JSONObject json = JSONObject.fromObject(result);
      flavors = parseFlavorIds(json);
    } catch (JSONException e) {
      LOGGER.warning("JSONException while parsing flavors: " + e);
      return null;
    }
    return flavors;
  }

  /**
   * Queries Stacksmith to get the Dockerfile corresponding to a given stack
   * reference.
   * @return the contents of the Dockerfile, or {@code null} if an error occurs.
   */
  public String fetchDockerfile(StackReference stack,
      @Nullable PrintStream buildLogger) {
    if (stack == null) {
      COMBINED_LOGGER.logWarning(buildLogger,
          "Null stack reference in fetchDockerFile.");
      return null;
    }

    HttpGet httpGet = new HttpGet(stack.getDockerfileUrl());
    String result = wrappedExecute(httpGet, buildLogger);
    if (result != null) {
      COMBINED_LOGGER.logFine(buildLogger,
          "Dockerfile received from Stacksmith API.");
    }
    return result;
  }

  /**
   * Sends a query to the Stacksmith API requesting a new stack to be created
   * using the specified components and OS.
   * @param components the components to use in the stack.
   * @param os the operating system, if any, to include in the stack.
   * @param flavor the flavor, if any, to include in the stack.
   * @param buildLogger a stream to use for logging.
   * @return the resulting stack reference, or {@code null} if an error occurs.
   */
  public StackReference makeStack(Iterable<VersionedEntityRequirement> components,
      @Nullable VersionedEntityRequirement os,
      @Nullable String flavor,
      @Nullable PrintStream buildLogger) {
    HttpPost httpPost = new HttpPost(STACKS_URL);
    JSONObject requirements = new JSONObject();

    if (components != null) {
      JSONArray componentsJSON = new JSONArray();
      boolean nonemptyComponents = false;
      for (VersionedEntityRequirement component : components) {
        if (!component.isNone()) {
          componentsJSON.add(component.toJSON());
          nonemptyComponents = true;
        }
      }
      if (nonemptyComponents) {
        requirements.element("components", componentsJSON);
      }
    }

    if (os != null && !os.isNone()) {
      requirements.element("os", os.toJSON());
    }

    if (!Strings.isNullOrEmpty(flavor)) {
      requirements.element("flavor", flavor);
    }

    httpPost.setEntity(new StringEntity(requirements.toString(),
        ContentType.APPLICATION_JSON));
    String result = wrappedExecute(httpPost, buildLogger);

    try {
      JSONObject json = JSONObject.fromObject(result);
      return StackReference.builder()
          .setId(json.getString("id"))
          .setStackUrl(json.getString("stack_url"))
          .build();
    } catch (JSONException e) {
      COMBINED_LOGGER.logWarning(buildLogger, "JSONException: " + e);
      return null;
    }
  }

  /**
   * Creates the Stacksmith API URL for Dependency discovery for a given entity.
   */
  protected static String makeDependenciesForEntityUrl(String entityId) {
    return API_BASE_URL + "components/" + entityId + "/dependencies";
  }

  /**
   * Creates the Stacksmith API URL for Flavor discovery for a given entity.
   */
  protected static String makeFlavorsForEntityUrl(String entityId) {
    return API_BASE_URL + "components/" + entityId + "/flavors";
  }

  /**
   * Attempts to parse the input into a set of {@link VersionedEntity} objects.
   * @return the parsed set, or {@code null} if the input JSON is invalid.
   */
  protected static NavigableSet<VersionedEntity> parseEntities(JSONObject json) {
    if (json == null) {
      LOGGER.warning("Cannot parse entities from null JSON.");
      return null;
    }

    NavigableSet<VersionedEntity> result = new TreeSet<>();
    try {
      JSONArray items = json.getJSONArray("items");
      for (int i = 0; i < items.size(); i++) {
        VersionedEntity.Builder builder = VersionedEntity.builder();
        JSONObject item = items.getJSONObject(i);
        builder.setId(item.getString("id"));
        builder.setName(item.getString("name"));
        builder.setCategory(VersionedEntityType.fromApiString(
            item.getString("category")));
        JSONArray versions = item.getJSONArray("versions");
        for (int j = 0; j < versions.size(); j++) {
          JSONObject versionObject = versions.getJSONObject(j);
          builder.addVersion(new BranchedVersion(
              versionObject.getString("version"),
              versionObject.getString("branch")));
        }
        result.add(builder.build());
      }
      return result;
    } catch (JSONException e) {
      LOGGER.warning("JSONException while parsing entities: " + e);
      return null;
    }
  }

  /**
   * Attempts to parse the input into a set of ID strings per the expected format
   * of an API response to the list-dependencies query.
   * @return the parsed set, or {@code null} if the input JSON is invalid.
   */
  @VisibleForTesting
  static NavigableSet<String> parseDependencyIds(JSONObject json) {
    if (json == null) {
      LOGGER.warning("Cannot parse dependency IDs from null JSON.");
      return null;
    }

    NavigableSet<String> result = new TreeSet<>();
    try {
      JSONArray items = json.getJSONArray("items");
      for (int i = 0; i < items.size(); i++) {
        result.add(items.getString(i));
      }
      return result;
    } catch (JSONException e) {
      LOGGER.warning("JSONException while parsing dependency IDs: " + e);
      return null;
    }
  }

  /**
   * Attempts to parse the input into a set of ID strings per the expected format
   * of an API response to the list-flavors query.
   * @return the parsed set, or {@code null} if the input JSON is invalid.
   */
  @VisibleForTesting
  static NavigableSet<String> parseFlavorIds(JSONObject json) {
    if (json == null) {
      LOGGER.warning("Cannot parse dependency IDs from null JSON.");
      return null;
    }

    NavigableSet<String> result = new TreeSet<>();
    try {
      JSONArray items = json.getJSONArray("items");
      for (int i = 0; i < items.size(); i++) {
        JSONObject item = items.getJSONObject(i);
        result.add(item.getString("id"));
      }
      return result;
    } catch (JSONException e) {
      LOGGER.warning("JSONException while parsing flavor IDs: " + e);
      return null;
    }
  }
}


text:
Generates icosphere meshes of varying levels of complexity – implementation
sourced from [this article](http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html).

* [demo with face normals](http://hughsk.io/icosphere)
* [demo with vertex normals](http://hughsk.io/icosphere?smooth)

[![icosphere](http://imgur.com/7PwoXuz.png)](http://hughsk.io/icosphere)

## Usage

[![NPM](https://nodei.co/npm/icosphere.png)](https://nodei.co/npm/icosphere/)

### mesh = icosphere(subdivisions)

Creates a new icosphere mesh object. You'll want to keep `subdivisions` within
the range of 0 and 5 or it starts to get really costly. The mesh object has
the following properties:

* `cells`: an indexed list of each triangle's positions.
* `positions`: a list of positions for each vertex.

### See Also

* [Creating an icosphere mesh in code](http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html)
* [gl-simplicial-complex](https://github.com/mikolalysenko/gl-simplicial-complex)
* [conway-hart](https://github.com/mikolalysenko/conway-hart)
* [mesh-viewer](https://github.com/mikolalysenko/mesh-viewer)
* [TrimeshJS](https://github.com/mikolalysenko/TrimeshJS)
* [unindex-mesh](https://github.com/hughsk/unindex-mesh)

## License

MIT. See [LICENSE.md](http://github.com/hughsk/icosphere/blob/master/LICENSE.md) for details.


text:
#include <stdlib.h>
#include <stdbool.h>

#include <lua.h>
#include <lauxlib.h>
#include "compat-5.3.h"

#include <dbus/dbus.h>

#include "ldbus.h"
#include "message.h"
#include "pending_call.h"
#include "timeout.h"
#include "watch.h"
#include "error.h"
#include "connection.h"

static const char *const DispatchStatus_lst [] = {
	"data_remains", /* DBUS_DISPATCH_DATA_REMAINS == 0 */
	"complete",     /* DBUS_DISPATCH_COMPLETE     == 1 */
	"need_memory",  /* DBUS_DISPATCH_NEED_MEMORY  == 2 */
	NULL
};

static int ldbus_connection_open(lua_State *L) {
	const char *address = luaL_checkstring(L, 1);

	DBusError *error = new_DBusError(L);
	DBusConnection *connection = dbus_connection_open(address, error);

	if (dbus_error_is_set(error)) {
		lua_pushnil(L);
		lua_pushstring(L, error->message);
		return 2;
	} else {
		push_DBusConnection(L, connection, FALSE);
		return 1;
	}
}

static int ldbus_connection_gc(lua_State *L) {
	lDBusConnection *udata = check_lDBusConnection(L, 1);

	if (udata->close) {
		/* You must close a connection prior to releasing the last reference to the connection.
		   If you dbus_connection_unref() for the last time without closing the connection,
		   the results are undefined
		*/
		dbus_connection_close(udata->connection);
	}

	dbus_connection_unref(udata->connection);

	return 0;
}

static int ldbus_connection_get_is_connected(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	lua_pushboolean(L, dbus_connection_get_is_connected(connection));

	return 1;
}

static int ldbus_connection_get_is_authenticated(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	lua_pushboolean(L, dbus_connection_get_is_authenticated(connection));

	return 1;
}

static int ldbus_connection_get_is_anonymous(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	lua_pushboolean(L, dbus_connection_get_is_anonymous(connection));

	return 1;
}

static int ldbus_connection_get_server_id(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	char *result = dbus_connection_get_server_id(connection);
	if (result == NULL) {
		lua_pushnil(L);
	} else {
		lua_pushstring(L, result);
	}

	return 1;
}

static int ldbus_connection_send(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	DBusMessage *message = check_DBusMessage(L, 2);

	unsigned int serial;
	lua_pushboolean(L, dbus_connection_send(connection, message, &serial));
	lua_pushinteger(L, serial);

	return 2;
}

static int ldbus_connection_send_with_reply(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	DBusMessage *message = check_DBusMessage(L, 2);
	int timeout_milliseconds = lua_isnoneornil(L, 3) ? (-1) : (luaL_checknumber(L, 3) * 1000);

	DBusPendingCall *pending;
	if (!dbus_connection_send_with_reply(connection, message, &pending, timeout_milliseconds)) {
		return luaL_error(L, LDBUS_NO_MEMORY);
	}

	push_DBusPendingCall(L, pending);
	return 1;
}

static int ldbus_connection_send_with_reply_and_block(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	DBusMessage *message = check_DBusMessage(L, 2);
	int timeout_milliseconds = lua_isnoneornil(L, 3) ? (-1) : (luaL_checknumber(L, 3) * 1000);
	DBusMessage *reply;
	DBusError error;
	dbus_error_init(&error);
	reply = dbus_connection_send_with_reply_and_block(connection, message, timeout_milliseconds, &error);
	if (dbus_error_is_set(&error)) {
		lua_pushnil(L);
		lua_pushstring(L, error.message);
		dbus_error_free(&error);
		return 2;
	} else {
		push_DBusMessage(L, reply);
		return 1;
	}
}

static int ldbus_connection_flush(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	dbus_connection_flush(connection);

	return 0;
}

static int ldbus_connection_read_write_dispatch(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	int timeout_milliseconds = luaL_optinteger(L, 2, -1);

	lua_pushboolean(L, dbus_connection_read_write_dispatch(connection, timeout_milliseconds));

	return 1;
}

static int ldbus_connection_read_write(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	int timeout_milliseconds = luaL_optinteger(L, 2, -1);

	lua_pushboolean(L, dbus_connection_read_write(connection, timeout_milliseconds));

	return 1;
}

static int ldbus_connection_pop_message(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	DBusMessage *message = dbus_connection_pop_message(connection);

	if (message == NULL) {
		lua_pushnil(L);
	} else {
		push_DBusMessage(L, message);
	}
	return 1;
}

static int ldbus_connection_get_dispatch_status(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	lua_pushstring(L, DispatchStatus_lst [ dbus_connection_get_dispatch_status(connection) ]);
	return 1;
}

static int ldbus_connection_dispatch(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	lua_pushstring(L, DispatchStatus_lst [ dbus_connection_dispatch(connection) ]);
	return 1;
}

static int ldbus_connection_set_watch_functions(lua_State *L) {
	lua_State **data;
	DBusConnection *connection = check_DBusConnection(L, 1);
	int has_toggle = lua_isnil(L, 4);

	/* make sure ldbus.watch has been loaded */
	luaL_requiref(L, "ldbus.watch", luaopen_ldbus_watch, FALSE);
	lua_pop(L, 1);

	data = lua_newuserdata(L, sizeof(lua_State*));
	*data = L;
	lua_createtable(L, 4, 0);
	lua_pushvalue(L, 2);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_ADD);
	lua_pushvalue(L, 3);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_REMOVE);
	if (has_toggle) {
		lua_pushvalue(L, 4);
		lua_rawseti(L, -2, DBUS_LUA_FUNC_TOGGLE);
	}
	lua_pushthread(L);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_THREAD);
	lua_setuservalue(L, -2);
	lua_rawsetp(L, LUA_REGISTRYINDEX, data);
	if (!dbus_connection_set_watch_functions(connection,
			ldbus_watch_add_function, ldbus_watch_remove_function,
			has_toggle ? NULL : ldbus_watch_toggled_function,
			(void *)data, ldbus_watch_free_data_function)) {
		ldbus_watch_free_data_function(data);
		return luaL_error(L, LDBUS_NO_MEMORY);
	};
	lua_pushboolean(L, TRUE);
	return 1;
}

static int ldbus_connection_set_timeout_functions(lua_State *L) {
	lua_State **data;
	DBusConnection *connection = check_DBusConnection(L, 1);

	/* make sure ldbus.watch has been loaded */
	luaL_requiref(L, "ldbus.timeout", lua_open_ldbus_timeout, FALSE);
	lua_pop(L, 1);

	data = lua_newuserdata(L, sizeof(lua_State*));
	*data = L;
	lua_createtable(L, 4, 0);
	lua_pushvalue(L, 2);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_ADD);
	lua_pushvalue(L, 3);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_REMOVE);
	lua_pushvalue(L, 4);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_TOGGLE);
	lua_pushthread(L);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_THREAD);
	lua_setuservalue(L, -2);
	lua_rawsetp(L, LUA_REGISTRYINDEX, data);

	if (!dbus_connection_set_timeout_functions(connection,
			ldbus_timeout_add_function, ldbus_timeout_remove_function, ldbus_timeout_toggled_function,
			(void *)data, ldbus_timeout_free_data_function)) {
		ldbus_timeout_free_data_function(data);
		return luaL_error(L, LDBUS_NO_MEMORY);
	};
	lua_pushboolean(L, TRUE);
	return 1;
}

static void free_data_function(void *data) {
	lua_State *L = *(lua_State**)data;
	lua_pushnil(L);
	lua_rawsetp(L, LUA_REGISTRYINDEX, data);
}

static void wakeup_main_function(void *data) {
	lua_State *L = *(lua_State**)data;
	int top = lua_gettop(L);
	lua_rawgetp(L, LUA_REGISTRYINDEX, data);
	lua_getuservalue(L, -1);
	lua_remove(L, top + 1); /* remove userdata */
	lua_rawgeti(L, -1, DBUS_LUA_FUNC_FUNC);
	lua_remove(L, top + 1); /* remove uservalue table */
	if (lua_pcall(L, 0, 0, 0) != LUA_OK) {
		/* unhandled error */
		lua_pop(L, 1);
	}
}

static int ldbus_connection_set_wakeup_main_function(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	lua_State **data;
	luaL_checktype(L, 2, LUA_TFUNCTION);
	data = lua_newuserdata(L, sizeof(lua_State*));
	*data = L;
	lua_createtable(L, 2, 0);
	lua_pushvalue(L, 2);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_FUNC);
	lua_pushthread(L);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_THREAD);
	lua_setuservalue(L, -2);
	lua_rawsetp(L, LUA_REGISTRYINDEX, data);
	dbus_connection_set_wakeup_main_function(connection, wakeup_main_function, data, free_data_function);
	lua_pushboolean(L, 1);
	return 1;
}

static void dispatch_status_function(DBusConnection *connection, DBusDispatchStatus new_status, void *data) {
	lua_State *L = *(lua_State**)data;
	int top = lua_gettop(L);
	UNUSED(connection);
	lua_rawgetp(L, LUA_REGISTRYINDEX, data);
	lua_getuservalue(L, -1);
	lua_remove(L, top + 1); /* remove userdata */
	lua_rawgeti(L, -1, DBUS_LUA_FUNC_FUNC);
	lua_remove(L, top + 1); /* remove uservalue table */
	lua_pushstring(L, DispatchStatus_lst[new_status]); /* XXX: could fail */
	if (lua_pcall(L, 1, 0, 0) != LUA_OK) {
		/* unhandled error */
		lua_pop(L, 1);
	}
}

static int ldbus_connection_set_dispatch_status_function(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	lua_State **data;
	luaL_checktype(L, 2, LUA_TFUNCTION);
	data = lua_newuserdata(L, sizeof(lua_State*));
	*data = L;
	lua_createtable(L, 2, 0);
	lua_pushvalue(L, 2);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_FUNC);
	lua_pushthread(L);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_THREAD);
	lua_setuservalue(L, -2);
	lua_rawsetp(L, LUA_REGISTRYINDEX, data);
	dbus_connection_set_dispatch_status_function(connection, dispatch_status_function, data, free_data_function);
	lua_pushboolean(L, 1);
	return 1;
}

static int ldbus_connection_set_max_message_size(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	long size = luaL_checkinteger(L, 2);

	dbus_connection_set_max_message_size(connection, size);

	return 0;
}

static int ldbus_connection_get_max_message_size(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	lua_pushinteger(L, dbus_connection_get_max_message_size(connection));

	return 1;
}

static int ldbus_connection_set_max_received_size(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	long size = luaL_checkinteger(L, 2);

	dbus_connection_set_max_received_size(connection, size);

	return 0;
}

static int ldbus_connection_get_max_received_size(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	lua_pushinteger(L, dbus_connection_get_max_received_size(connection));

	return 1;
}

static int ldbus_connection_get_outgoing_size(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	lua_pushinteger(L, dbus_connection_get_outgoing_size(connection));

	return 1;
}

static int ldbus_connection_has_messages_to_send(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);

	lua_pushboolean(L, dbus_connection_has_messages_to_send(connection));

	return 1;
}

static void unregister_function(DBusConnection *connection, void *data) {
	lua_State *L = *(lua_State**)data;
	UNUSED(connection);
	lua_pushnil(L);
	lua_rawsetp(L, LUA_REGISTRYINDEX, data);
}

static DBusHandlerResult message_function(DBusConnection *connection, DBusMessage *message, void *data) {
	lua_State *L = *(lua_State**)data;
	int top = lua_gettop(L);
	UNUSED(connection);
	if (!lua_checkstack(L, 2)) {
		return DBUS_HANDLER_RESULT_NEED_MEMORY;
	}
	lua_rawgetp(L, LUA_REGISTRYINDEX, data);
	lua_getuservalue(L, -1);
	lua_remove(L, top + 1); /* remove userdata */
	lua_rawgeti(L, -1, DBUS_LUA_FUNC_FUNC);
	lua_remove(L, top + 1); /* remove uservalue table */
	dbus_message_ref(message); /* Keep a reference for lua */
	push_DBusMessage(L, message); /* XXX: Could throw? */
	switch(lua_pcall(L, 1, 1, 0)) {
		case LUA_OK:
			if (lua_toboolean(L, -1)) {
				return DBUS_HANDLER_RESULT_HANDLED;
			} else {
				return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
			}
		case LUA_ERRMEM:
			lua_pop(L, 1);
			return DBUS_HANDLER_RESULT_NEED_MEMORY;
		default:
			lua_pop(L, 1);
			return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
	}
}

static const DBusObjectPathVTable VTable = {
	unregister_function,
	message_function,
	NULL, NULL, NULL, NULL
};

static int ldbus_connection_register_object_path(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	const char *path = luaL_checkstring(L, 2);
	lua_State **data;
	luaL_checktype(L, 3, LUA_TFUNCTION);
	data = lua_newuserdata(L, sizeof(lua_State*));
	*data = L;
	lua_createtable(L, 2, 0);
	lua_pushvalue(L, 3);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_FUNC);
	lua_pushthread(L);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_THREAD);
	lua_setuservalue(L, -2);
	lua_rawsetp(L, LUA_REGISTRYINDEX, data);
	if (!dbus_connection_register_object_path(connection, path, &VTable, data)) {
		unregister_function(connection, data);
		return luaL_error(L, "unknown error");
	}
	lua_pushboolean(L, 1);
	return 1;
}

static int ldbus_connection_register_fallback(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	const char *path = luaL_checkstring(L, 2);
	lua_State **data;
	luaL_checktype(L, 3, LUA_TFUNCTION);
	data = lua_newuserdata(L, sizeof(lua_State*));
	*data = L;
	lua_createtable(L, 2, 0);
	lua_pushvalue(L, 3);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_FUNC);
	lua_pushthread(L);
	lua_rawseti(L, -2, DBUS_LUA_FUNC_THREAD);
	lua_setuservalue(L, -2);
	lua_rawsetp(L, LUA_REGISTRYINDEX, data);
	if (!dbus_connection_register_fallback(connection, path, &VTable, data)) {
		unregister_function(connection, data);
		return luaL_error(L, "unknown error");
	}
	lua_pushboolean(L, 1);
	return 1;
}

static int ldbus_connection_unregister_object_path(lua_State *L) {
	DBusConnection *connection = check_DBusConnection(L, 1);
	const char *path = luaL_checkstring(L, 2);
	if (!dbus_connection_unregister_object_path(connection, path)) {
		return luaL_error(L, LDBUS_NO_MEMORY);
	}
	lua_pushboolean(L, 1);
	return 1;
}

static luaL_Reg const methods [] = {
	{ "get_is_connected",             ldbus_connection_get_is_connected },
	{ "get_is_authenticated",         ldbus_connection_get_is_authenticated },
	{ "get_is_anonymous",             ldbus_connection_get_is_anonymous },
	{ "get_server_id",                ldbus_connection_get_server_id },
	{ "send",                         ldbus_connection_send },
	{ "send_with_reply",              ldbus_connection_send_with_reply },
	{ "send_with_reply_and_block",    ldbus_connection_send_with_reply_and_block },
	{ "flush",                        ldbus_connection_flush },
	{ "read_write_dispatch",          ldbus_connection_read_write_dispatch},
	{ "read_write",                   ldbus_connection_read_write },
	{ "pop_message",                  ldbus_connection_pop_message },
	{ "get_dispatch_status",          ldbus_connection_get_dispatch_status },
	{ "dispatch",                     ldbus_connection_dispatch },
	{ "set_watch_functions",          ldbus_connection_set_watch_functions },
	{ "set_timeout_functions",        ldbus_connection_set_timeout_functions },
	{ "set_dispatch_status_function", ldbus_connection_set_dispatch_status_function },
	{ "set_wakeup_main_function",     ldbus_connection_set_wakeup_main_function },
	{ "set_max_message_size",         ldbus_connection_set_max_message_size },
	{ "get_max_message_size",         ldbus_connection_get_max_message_size },
	{ "set_max_received_size",        ldbus_connection_set_max_received_size },
	{ "get_max_received_size",        ldbus_connection_get_max_received_size },
	{ "get_outgoing_size",            ldbus_connection_get_outgoing_size },
	{ "has_messages_to_send",         ldbus_connection_has_messages_to_send },
	{ "register_object_path",         ldbus_connection_register_object_path },
	{ "register_fallback", 	          ldbus_connection_register_fallback },
	{ "unregister_object_path",       ldbus_connection_unregister_object_path },
	{ NULL, NULL }
};

LDBUS_INTERNAL void push_DBusConnection(lua_State *L, DBusConnection *connection, bool close) {
	lDBusConnection *udata = lua_newuserdata(L, sizeof(lDBusConnection));
	udata->connection = connection;
	udata->close = close;

	if (luaL_newmetatable(L, DBUS_CONNECTION_METATABLE)) {
		luaL_newlib(L, methods);
		lua_setfield(L, -2, "__index");

		lua_pushcfunction(L, ldbus_connection_gc) ;
		lua_setfield(L, -2, "__gc");

		lua_pushcfunction(L, tostring);
		lua_setfield(L, -2, "__tostring");

		lua_pushstring(L, "DBusConnection");
		lua_setfield(L, -2, "__udtype");
	}
	lua_setmetatable(L, -2);
}

static const struct luaL_Reg ldbus_connection [] = {
	{ "open", ldbus_connection_open },
	{ NULL, NULL }
};
int luaopen_ldbus_connection(lua_State *L) {
	luaL_newlib(L, ldbus_connection);
	return 1;
}


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef HTMLFrameSetElement_h
#define HTMLFrameSetElement_h

#include "mozilla/Attributes.h"
#include "nsIDOMHTMLFrameSetElement.h"
#include "nsGenericHTMLElement.h"

/**
 * The nsFramesetUnit enum is used to denote the type of each entry
 * in the row or column spec.
 */
enum nsFramesetUnit {
  eFramesetUnit_Fixed = 0,
  eFramesetUnit_Percent,
  eFramesetUnit_Relative
};

/**
 * The nsFramesetSpec struct is used to hold a single entry in the
 * row or column spec.
 */
struct nsFramesetSpec {
  nsFramesetUnit mUnit;
  nscoord        mValue;
};

/**
 * The maximum number of entries allowed in the frame set element row
 * or column spec.
 */
#define NS_MAX_FRAMESET_SPEC_COUNT 16000

//----------------------------------------------------------------------

namespace mozilla {
namespace dom {

class OnBeforeUnloadEventHandlerNonNull;

class HTMLFrameSetElement final : public nsGenericHTMLElement,
                                  public nsIDOMHTMLFrameSetElement
{
public:
  explicit HTMLFrameSetElement(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo)
    : nsGenericHTMLElement(aNodeInfo),
      mNumRows(0),
      mNumCols(0),
      mCurrentRowColHint(NS_STYLE_HINT_REFLOW)
  {
    SetHasWeirdParserInsertionMode();
  }

  NS_IMPL_FROMCONTENT_HTML_WITH_TAG(HTMLFrameSetElement, frameset)

  // nsISupports
  NS_DECL_ISUPPORTS_INHERITED

  // nsIDOMHTMLFrameSetElement
  NS_DECL_NSIDOMHTMLFRAMESETELEMENT

  void GetCols(DOMString& aCols)
  {
    GetHTMLAttr(nsGkAtoms::cols, aCols);
  }
  void SetCols(const nsAString& aCols, ErrorResult& aError)
  {
    SetHTMLAttr(nsGkAtoms::cols, aCols, aError);
  }
  void GetRows(DOMString& aRows)
  {
    GetHTMLAttr(nsGkAtoms::rows, aRows);
  }
  void SetRows(const nsAString& aRows, ErrorResult& aError)
  {
    SetHTMLAttr(nsGkAtoms::rows, aRows, aError);
  }

  virtual bool IsEventAttributeName(nsIAtom *aName) override;

  // Event listener stuff; we need to declare only the ones we need to
  // forward to window that don't come from nsIDOMHTMLFrameSetElement.
#define EVENT(name_, id_, type_, struct_) /* nothing; handled by the superclass */
#define WINDOW_EVENT_HELPER(name_, type_)                               \
  type_* GetOn##name_();                                                \
  void SetOn##name_(type_* handler);
#define WINDOW_EVENT(name_, id_, type_, struct_)                        \
  WINDOW_EVENT_HELPER(name_, EventHandlerNonNull)
#define BEFOREUNLOAD_EVENT(name_, id_, type_, struct_)                  \
  WINDOW_EVENT_HELPER(name_, OnBeforeUnloadEventHandlerNonNull)
#include "mozilla/EventNameList.h" // IWYU pragma: keep
#undef BEFOREUNLOAD_EVENT
#undef WINDOW_EVENT
#undef WINDOW_EVENT_HELPER
#undef EVENT

  // These override the SetAttr methods in nsGenericHTMLElement (need
  // both here to silence compiler warnings).
  nsresult SetAttr(int32_t aNameSpaceID, nsIAtom* aName,
                   const nsAString& aValue, bool aNotify)
  {
    return SetAttr(aNameSpaceID, aName, nullptr, aValue, aNotify);
  }
  virtual nsresult SetAttr(int32_t aNameSpaceID, nsIAtom* aName,
                           nsIAtom* aPrefix, const nsAString& aValue,
                           bool aNotify) override;

   /**
    * GetRowSpec is used to get the "rows" spec.
    * @param out int32_t aNumValues The number of row sizes specified.
    * @param out nsFramesetSpec* aSpecs The array of size specifications.
             This is _not_ owned by the caller, but by the nsFrameSetElement
             implementation.  DO NOT DELETE IT.
    */
  nsresult GetRowSpec(int32_t *aNumValues, const nsFramesetSpec** aSpecs);
   /**
    * GetColSpec is used to get the "cols" spec
    * @param out int32_t aNumValues The number of row sizes specified.
    * @param out nsFramesetSpec* aSpecs The array of size specifications.
             This is _not_ owned by the caller, but by the nsFrameSetElement
             implementation.  DO NOT DELETE IT.
    */
  nsresult GetColSpec(int32_t *aNumValues, const nsFramesetSpec** aSpecs);

  virtual bool ParseAttribute(int32_t aNamespaceID,
                                nsIAtom* aAttribute,
                                const nsAString& aValue,
                                nsAttrValue& aResult) override;
  virtual nsChangeHint GetAttributeChangeHint(const nsIAtom* aAttribute,
                                              int32_t aModType) const override;

  virtual nsresult Clone(mozilla::dom::NodeInfo *aNodeInfo, nsINode **aResult) const override;

protected:
  virtual ~HTMLFrameSetElement();

  virtual JSObject* WrapNode(JSContext *aCx, JS::Handle<JSObject*> aGivenProto) override;

private:
  nsresult ParseRowCol(const nsAString& aValue,
                       int32_t&         aNumSpecs,
                       nsFramesetSpec** aSpecs);

  /**
   * The number of size specs in our "rows" attr
   */
  int32_t          mNumRows;
  /**
   * The number of size specs in our "cols" attr
   */
  int32_t          mNumCols;
  /**
   * The style hint to return for the rows/cols attrs in
   * GetAttributeChangeHint
   */
  nsChangeHint      mCurrentRowColHint;
  /**
   * The parsed representation of the "rows" attribute
   */
  nsAutoArrayPtr<nsFramesetSpec>  mRowSpecs; // parsed, non-computed dimensions
  /**
   * The parsed representation of the "cols" attribute
   */
  nsAutoArrayPtr<nsFramesetSpec>  mColSpecs; // parsed, non-computed dimensions
};

} // namespace dom
} // namespace mozilla

#endif // HTMLFrameSetElement_h


text: include_recipe "php-fpm"


text:
/* worker_thread.c
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#define  THIS_IS_A_SUBROUTINE
#include "bx_data_structures.h"
#define DEBUG 0

/**************************************************************************
*   The Worker Thread
**************************************************************************/
// There are one or more Worker Threads per target.
// A Worker Thread will indicate that it is WAITING for something to do and
// place itself on the Worker Thread Data Structure  queue of its target.
// Eventually the target will wake up a Worker Thread which is indicated
// by a non-zero value in the bx_wd_released variable in the Worker Thread
// Data Structure  for this Worker Thread.
// Upon waking up, the Worker Thread will perform an INPUT or OUTPUT
// operation depending on its target's designation. The Worker Thread
// will have a buffer header structure that contains the location in the
// file to perform the operation, the number of bytes to transfer, and the
// I/O memory buffer.
// Upon completing the requested I/O operation, the Worker Thread will
// stuff its Buffer Header on to the "next buffer queue". In other words,
// if this Worker Thread is an INPUT Worker Thread then it just read data
// into its buffer.
// Therefore, upon completion of the read, this Worker Thread will stuff
// its Buffer Header on the Buffer Header Queue of the OUTPUT target and
// wake up the OUTPUT target if it is waiting for a buffer.
// Likewise, if this Worker Thread is an OUTPUT Worker Thread then it just
// wrote data from its buffer. Therefore, upon completion of the write, this
// Worker Thread will stuff its Buffer Header on the Buffer Header Queue
// of the INPUT target and wake up the INPUT target if it is waiting
// for a buffer.
//
// After putting its Buffer Header on the appropriate queue this Worker
// Thread will stuff itself back onto its Worker Thread Data Structure
// queue and wait for something to do.
//
// At some point the Worker Thread will wake up and find the "TERMINATE"
// flag set in its Worker Thread Data Structure . At this point the Worker
// Thread will break the loop and terminate.
void *
worker_thread_main(void *pin) {
    int 	status;
	struct bx_td 			*bx_tdp;
	struct bx_wd 			*bx_wdp;
	struct bx_buffer_queue 	*qp;
	struct bx_buffer_header	*bufhdrp;
	nclk_t					nclk;

	bx_wdp = (struct bx_wd *)pin;
	bx_tdp = bx_wdp->bx_wd_my_bx_tdp;
nclk_now(&nclk);
if (DEBUG) fprintf(stderr,"%llu: worker_thread_main: ENTER: bx_wdp=%p, bx_tdp=%p\n", (unsigned long long int)nclk,bx_wdp, bx_tdp);
	status = 0;

nclk_now(&nclk);
if (DEBUG) fprintf(stderr,"%llu worker_thread_main: my_worker_thread_number=%s - ENTER %d\n", (unsigned long long int)nclk,(bx_tdp->bx_td_flags & BX_TD_INPUT)?"INPUT":"OUTPUT", bx_wdp->bx_wd_my_worker_thread_number);

	while (1) {
		// Set flag to indicate that this worker_thread is WAITING
		bx_wdp->bx_wd_flags |= BX_WD_WAITING;
		// Enqueue this Worker Thread Data Structure  on the bx_wd_queue for this target
		bx_wd_enqueue(bx_wdp, bx_wdp->bx_wd_my_queue);
		// Wait for the target thread to release me
		pthread_mutex_lock(&bx_wdp->bx_wd_mutex);
nclk_now(&nclk);
if (DEBUG) fprintf(stderr,"%llu worker_thread_main: my_worker_thread_number=%s - got the bx_wd_mutex lock - waiting for something to do - time %d\n", (unsigned long long int)nclk,(bx_tdp->bx_td_flags & BX_TD_INPUT)?"INPUT":"OUTPUT", bx_wdp->bx_wd_my_worker_thread_number);
		bx_wdp->bx_wd_flags |= BX_WD_WAITING;
		while (1 != bx_wdp->bx_wd_released) {
         	pthread_cond_wait(&bx_wdp->bx_wd_conditional, &bx_wdp->bx_wd_mutex);
		}
		bx_wdp->bx_wd_flags &= ~BX_WD_WAITING;
		bx_wdp->bx_wd_released = 0;
		if (bx_wdp->bx_wd_flags & BX_WD_TERMINATE)
			break;

nclk_now(&nclk);
if (DEBUG) fprintf(stderr,"%llu worker_thread_main: my_worker_thread_number=%s - got the bx_wd_mutex lock - GOT something to do - time %d\n", (unsigned long long int)nclk,(bx_tdp->bx_td_flags & BX_TD_INPUT)?"INPUT":"OUTPUT", bx_wdp->bx_wd_my_worker_thread_number);

bx_wd_show(bx_wdp);
		bufhdrp = bx_wdp->bx_wd_bufhdrp;
		if (bx_tdp->bx_td_flags & BX_TD_INPUT) { // Read the input file
			status = pread(bx_wdp->bx_wd_fd, bufhdrp->bh_startp, bufhdrp->bh_transfer_size, bufhdrp->bh_file_offset);
			if (status < 0) {
				perror("Read error");
				bufhdrp->bh_valid_size = 0;
			} else {
				bufhdrp->bh_valid_size = status;
			}
nclk_now(&nclk);
if (DEBUG) fprintf(stderr,"%llu worker_thread_main: my_worker_thread_number=%s - read %d of %d bytes starting at offset %d - time %zd\n", (unsigned long long int)nclk,(bx_tdp->bx_td_flags & BX_TD_INPUT)?"INPUT":"OUTPUT", bx_wdp->bx_wd_my_worker_thread_number,status,bufhdrp->bh_transfer_size,bufhdrp->bh_file_offset);
			// Put this buffer on the output target queue
			qp = &bx_td[bx_wdp->bx_wd_next_buffer_queue].bx_td_buffer_queue;
			bh_enqueue(bx_wdp->bx_wd_bufhdrp, qp);
		} else { // Must be output
			status = pwrite(bx_wdp->bx_wd_fd, bufhdrp->bh_startp, bufhdrp->bh_transfer_size, bufhdrp->bh_file_offset);
			if (status < 0) {
				perror("Write error");
				bufhdrp->bh_valid_size = 0;
			} else {
				bufhdrp->bh_valid_size = status;
			}
nclk_now(&nclk);
if (DEBUG) fprintf(stderr,"%llu worker_thread_main: my_worker_thread_number=%s - wrote %d of %d bytes starting at offset %d - requeuing buffer %zd - time %p\n", (unsigned long long int)nclk,(bx_tdp->bx_td_flags & BX_TD_INPUT)?"INPUT":"OUTPUT", bx_wdp->bx_wd_my_worker_thread_number,status,bufhdrp->bh_transfer_size,bufhdrp->bh_file_offset, bufhdrp);
			// Put this buffer on the input target queue
			qp = &bx_td[bx_wdp->bx_wd_next_buffer_queue].bx_td_buffer_queue;
			bh_enqueue(bufhdrp, qp);
			bufqueue_show(qp);
		}
nclk_now(&nclk);
if (DEBUG) fprintf(stderr,"%llu worker_thread_main: my_worker_thread_number=%s - transferred %d bytes - time %d\n", (unsigned long long int)nclk,(bx_tdp->bx_td_flags & BX_TD_INPUT)?"INPUT":"OUTPUT", bx_wdp->bx_wd_my_worker_thread_number,status);
if (DEBUG) fprintf(stderr,"%llu worker_thread_main: my_worker_thread_number=%s - releasing the bx_wd_mutex lock %d\n", (unsigned long long int)nclk,(bx_tdp->bx_td_flags & BX_TD_INPUT)?"INPUT":"OUTPUT", bx_wdp->bx_wd_my_worker_thread_number);
		pthread_mutex_unlock(&bx_wdp->bx_wd_mutex);
	}
if (DEBUG) fprintf(stderr,"%llu worker_thread_main: my_worker_thread_number=%s %d - Exit \n", (unsigned long long int)nclk,(bx_tdp->bx_td_flags & BX_TD_INPUT)?"INPUT":"OUTPUT", bx_wdp->bx_wd_my_worker_thread_number);
   	return 0;
} // End of worker_thread_main()


text:
#ifndef VIENNASHE_MATERIALS_EXCEPTION_HPP
#define VIENNASHE_MATERIALS_EXCEPTION_HPP

// std
#include <stdexcept>
#include <string>

/** @file viennashe/materials/exception.hpp
    @brief Contains all the exceptions used for accessing materials.
*/

namespace viennashe
{
  namespace materials
  {
    /** @brief Exception for the case that an invalid material is in use */
    class invalid_material_exception: public std::runtime_error
    {
      public:
        invalid_material_exception(std::string const & str) : std::runtime_error(str) {}
    };

  } //namespace materials
} //namespace viennashe

#endif


text:
module Cleaners
  module CrackedDetailCleanable
    private

    def clear_cracked_details
      self.trial_fixed_notice_at = nil if trial_fixed_notice_at
      self.trial_fixed_at = nil if trial_fixed_at
      self.trial_cracked_at = nil if trial_cracked_at
      self.trial_cracked_at_third = nil if trial_cracked_at_third
    end
  end
end


text:
1.0.0
- Initial version.

1.1.0
  - Added the ability to import Shapefiles, Excel files, and csv files from a URL source.
  - Created the new geo_australia domain example.
  - Added a new column-level data lineage visualization.

1.2.0
  - Enhanced column-level data lineage visualization.
  - Added the ability to track schema changes.
  - Added the ability to maintain BigQuery table and column descriptions.
  - Updated example schema to include more table and column descriptions.


text:
/*
 * Usage of version updated for SageTV integration in the Studio:
 *
 * First get an instance of this class using:
 * Weather = tv_sage_weather_WeatherDotCom_getInstance()
 *
 * Then you can set the units/locationID using:
 * tv_sage_weather_WeatherDotCom_setUnits(Weather, "s")
 * tv_sage_weather_WeatherDotCom_setLocationID(Weather, "USCA0924")
 *
 * You can search for location IDs this way, its returns a java.util.Map of Names to LocationIDs:
 * tv_sage_weather_WeatherDotCom_searchLocations(Weather, "Chicago")
 *
 * To cause an update to occur (it respects caching, returns a boolean):
 * tv_sage_weather_WeatherDotCom_updateNow()
 *
 * To Get more info:
 * tv_sage_weather_WeatherDotCom_getLocationID(Weather)
 * tv_sage_weather_WeatherDotCom_getUnits(Weather)
 * tv_sage_weather_WeatherDotCom_getLastError(Weather)
 * tv_sage_weather_WeatherDotCom_getLocationProperties(Weather) returns a Map
 * tv_sage_weather_WeatherDotCom_getCurrentConditionProperties(Weather) returns a Map
 * tv_sage_weather_WeatherDotCom_getForecastProperties(Weather) returns a Map
 * tv_sage_weather_WeatherDotCom_getSponsorProperties(Weather) returns a Map
 * tv_sage_weather_WeatherDotCom_getLocationInfo(Weather, String property) returns a String
 * tv_sage_weather_WeatherDotCom_getCurrentCondition(Weather, String property) returns a String
 * tv_sage_weather_WeatherDotCom_getForecastCondition(Weather, String property) returns a String
 * tv_sage_weather_WeatherDotCom_getSponsorLinks(Weather, String property) returns a String
 * tv_sage_weather_WeatherDotCom_getLastUpdateTime(Weather)
 * tv_sage_weather_WeatherDotCom_isCurrentlyUpdating(Weather)
 */
package tv.sage.weather;

import java.net.*;
import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;

public class WeatherDotCom
{
  // variables for replacing weatherroom with weather.com if specified
  public static String weathercom_url = "http://xoap.weather.com/weather/local/";

  // arguments for get (excluding units and days)
  public static String partner_id="1010850608";
  public static String licence_key="c52f908e1cce80a5";

  // cache duration: 60 minutes
  public static long cache_duration=60*60*1000; //milliseconds

  private static WeatherDotCom myInstance;
  private static final Object chosenOneLock = new Object();

  public static WeatherDotCom getInstance() {
    if (myInstance == null) {
      synchronized (chosenOneLock) {
        if (myInstance == null) {
          myInstance = new WeatherDotCom();
        }
      }
    }
    return myInstance;
  }
  protected WeatherDotCom()
  {
    loadWeatherDataFromCache();
  }
  /*XXX
	public static String getElementText(Element elem)
	{
	    NodeList children = elem.getChildNodes();
	    for (int child = 0; child < children.getLength(); child++)
		{
			if (children.item(child).getNodeType() == Node.TEXT_NODE)
			{
//			    System.out.println("value" +children.item(child).getNodeValue());
			    return children.item(child).getNodeValue();
		    }
	    }
		return "";
	}
   */
  public java.util.Map searchLocations(String query)
  {
    try
    {
      String searchURLString = "http://xoap.weather.com/search/search?where=" +
          java.net.URLEncoder.encode(query, "UTF-8");
      SearchHandler searchy = new SearchHandler();
      parseXmlFile(searchURLString, false, searchy);
      if (searchy.getSearchResults() == null)
        System.out.println(lastError = "Weather.com returned empty doc");
      return searchy.getSearchResults();
      /*XXX
			Element searchRes = (Element)searchDoc.getElementsByTagName("search").item(0);

			// check for error result
			if (searchRes == null)
			{
				// probably an error doc
				if (searchDoc.getElementsByTagName("error").getLength() >= 1)
				{
//					output_error(output_filename,
//						"Failed to read from weather source",
//						"weather.com returned error status: " + getXML(doc.getDocumentElement(), "err", "error"));
					System.out.println(lastError = ("Weather.com returned error status " + getXML(searchDoc.getDocumentElement(), "err", "error")));
				}
				else
				{
//					output_error(output_filename,
//						"Failed to read from weather source",
//						"weather.com returned empty doc");
					System.out.println(lastError = "Weather.com returned empty doc");
				}
				return null;
			}
       */
      //			java.util.Map rv = new java.util.HashMap();
      /*XXX		    NodeList results = searchRes.getElementsByTagName("loc");
		    for (int i = 0; i < results.getLength(); i++)
		    {
				Element result = (Element)results.item(i);
				String locID = result.getAttribute("id");
				String locName = getElementText(result);
				rv.put(locID, locName);
		    }*/
      //			return rv;
    }
    catch (Exception e)
    {
      System.out.println(lastError = ("Error with weather parsing:" + e));
      return null;
    }
  }
  public void setUnits(String units)
  {
    if (units != null && !units.equals(myUnits))
    {
      // Blow away the cache
      lastLocUpdateTime = lastCCUpdateTime = lastFCUpdateTime = lastSponsorUpdateTime = 0;
    }

    myUnits = units;
  }
  public String getUnits()
  {
    return myUnits;
  }
  public String getLocationID()
  {
    return myLocId;
  }
  public void setLocationID(String locID)
  {
    if (locID != null && !locID.equals(myLocId))
    {
      // Blow away the cache
      lastLocUpdateTime = lastCCUpdateTime = lastFCUpdateTime = lastSponsorUpdateTime = 0;
    }

    myLocId = locID;
  }
  public String getLastError()
  {
    return lastError;
  }

  private String getWindInfo(String windSpeed, String speedUnits)
  {
    try
    {
      Integer.parseInt(windSpeed);
      return windSpeed + speedUnits;
    }
    catch (NumberFormatException e)
    {
      return windSpeed;
    }
  }

  // Returns true if an update occurred successfully; false otherwise
  public boolean updateNow()
  {
    if (updating) return true;
    if (myLocId == null || myLocId.length() == 0) return false;
    try
    {
      updating = true;
      lastError = "";
      boolean updateCC = (lastCCUpdateTime == 0) || (System.currentTimeMillis() - lastCCUpdateTime > 30*60*1000); // 30 minutes
      boolean updateLinks = (lastSponsorUpdateTime == 0) || (System.currentTimeMillis() - lastSponsorUpdateTime > 12*60*60*1000); // 12 hours
      boolean updateFC = (lastFCUpdateTime == 0) || (System.currentTimeMillis() - lastFCUpdateTime > 2*60*60*1000); // 2 hours
      if (!updateLinks && !updateCC && !updateFC)
      {
        return true; // nothing to update right now, use the cache
      }
      updateLinks = true; // TWC always requires this now for some reason
      String urlString = "http://xoap.weather.com/weather/local/" + myLocId +
          "?cc=*&prod=xoap&par=" + partner_id + "&key=" + licence_key + "&unit=" + myUnits;
      if (updateFC)
        urlString += "&dayf=10";
      if (updateLinks)
        urlString += "&link=xoap";
      parseXmlFile(urlString, false, new UpdateHandler());

      saveWeatherDataToCache();
    }
    catch (Exception e)
    {
      System.out.println(lastError = ("Error with weather parsing:" + e));
      e.printStackTrace();
      return false;
    }
    finally
    {
      updating = false;
    }
    return true;
  }
  private java.util.Map getPropertiesWithPrefix(String prefix)
  {
    java.util.Enumeration walker = props.propertyNames();
    java.util.Map rv = new java.util.HashMap();
    while (walker.hasMoreElements())
    {
      Object elem = walker.nextElement();
      if (elem != null && elem.toString().startsWith(prefix))
      {
        rv.put(elem.toString().substring(prefix.length()), props.getProperty(elem.toString()));
      }
    }
    return rv;
  }
  public java.util.Map getLocationProperties()
  {
    return getPropertiesWithPrefix("loc/");
  }
  public java.util.Map getCurrentConditionProperties()
  {
    return getPropertiesWithPrefix("cc/");
  }
  public java.util.Map getForecastProperties()
  {
    return getPropertiesWithPrefix("forecast/");
  }
  public java.util.Map getSponsorProperties()
  {
    return getPropertiesWithPrefix("sponsor/");
  }
  public String getLocationInfo(String propName)
  {
    return props.getProperty("loc/" + propName);
    //Object rv = locMap.get(propName);
    //return (rv == null) ? "" : rv.toString();
  }
  public String getCurrentCondition(String propName)
  {
    return props.getProperty("cc/" + propName);
    //Object rv = ccMap.get(propName);
    //return (rv == null) ? "" : rv.toString();
  }
  public String getForecastCondition(String propName)
  {
    return props.getProperty("forecast/" + propName);
    //Object rv = fcMap.get(propName);
    //return (rv == null) ? "" : rv.toString();
  }
  public String getSponsorLinks(String propName)
  {
    return props.getProperty("sponsor/" + propName);
    //Object rv = sponsorMap.get(propName);
    //return (rv == null) ? "" : rv.toString();
  }
  public long getLastUpdateTime()
  {
    return Math.max(lastLocUpdateTime, Math.max(lastCCUpdateTime, Math.max(lastFCUpdateTime, lastSponsorUpdateTime)));
  }
  public boolean isCurrentlyUpdating()
  {
    return updating;
  }

  private void saveWeatherDataToCache()
  {
    props.put("lastLocUpdateTime", Long.toString(lastLocUpdateTime));
    props.put("lastCCUpdateTime", Long.toString(lastCCUpdateTime));
    props.put("lastFCUpdateTime", Long.toString(lastFCUpdateTime));
    props.put("lastSponsorUpdateTime", Long.toString(lastSponsorUpdateTime));
    if (myLocId != null)
    {
      props.put("locID", myLocId);
    }
    if (myUnits != null)
    {
      props.put("units", myUnits);
    }
    java.io.File cacheFile = new java.io.File(("") + "weather_cache.properties");
    java.io.OutputStream out = null;
    try
    {
      out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(cacheFile));
      props.store(out, "SageTV Weather Data");
    }
    catch (Exception e)
    {
      System.out.println("Error caching weather data of:" + e);
    }
    finally
    {
      if (out != null)
      {
        try{out.close();}catch(Exception e){}
        out = null;
      }
    }
  }

  private void loadWeatherDataFromCache()
  {
    props = new java.util.Properties();
    java.io.File cacheFile = new java.io.File(("") + "weather_cache.properties");
    java.io.InputStream in = null;
    try
    {
      in = new java.io.BufferedInputStream(new java.io.FileInputStream(cacheFile));
      props.load(in);
    }
    catch (Exception e)
    {
      System.out.println("Error reading cached weather data of:" + e);
    }
    finally
    {
      if (in != null)
      {
        try{in.close();}catch(Exception e){}
        in = null;
      }
    }
    try
    {
      lastLocUpdateTime = Long.parseLong(props.getProperty("lastLocUpdateTime", "0"));
      lastFCUpdateTime = Long.parseLong(props.getProperty("lastFCUpdateTime", "0"));
      lastCCUpdateTime = Long.parseLong(props.getProperty("lastCCUpdateTime", "0"));
      lastSponsorUpdateTime = Long.parseLong(props.getProperty("lastSponsorUpdateTime", "0"));
    }catch (NumberFormatException e){}
    myLocId = props.getProperty("locID");
    myUnits = props.getProperty("units", "s");
  }

  private String myLocId;
  private String myUnits = "s";
  private java.util.Properties props = new java.util.Properties();

  private long lastLocUpdateTime;
  private long lastCCUpdateTime;
  private long lastFCUpdateTime;
  private long lastSponsorUpdateTime;
  private boolean updating;
  private String lastError;

  //This method gets the xml out of the document based on the tag and the parent
  //Caveat, it goes off the first match -- limit the matches using element selection
  /*XXX
    public static String getXML(Element doc, String tag, String parent) {
	String tmpstr = null;
	try {
	    NodeList tmpNodes = doc.getElementsByTagName(tag);

	    //get the first match
	    for (int i = 0; i < tmpNodes.getLength() && tmpstr==null; i++)
	    {
//		System.out.println(i);
		if ((((Element)(tmpNodes.item(i).getParentNode())).getTagName()).equals(parent))
		{
		    // check children for value
//		    System.out.println("got an  xml node  for "+parent+"/"+tag);
//		    System.out.println("Node: "+((Element)tmpNodes.item(i)).getTagName());
//		    System.out.println("Node text: "+tmpNodes.item(i).toString());

		    NodeList children=tmpNodes.item(i).getChildNodes();
		    for ( int child=0; child < children.getLength(); child++) {
			if ( children.item(child).getNodeType()==Node.TEXT_NODE ) {
//			    System.out.println("value" +children.item(child).getNodeValue());
			    tmpstr=children.item(child).getNodeValue();
			    break;
			}
		    }
		}
	    }

	}
	catch (Exception e) {
	    System.out.println("Failed to get xml value for "+parent+"/"+tag);
	    e.printStackTrace();
	}

	if (tmpstr ==null)
	    // found nothing, return blank
	    return "";

	// clean up string

	tmpstr.trim();

	//gets rid of the weird (A) character
	if (tmpstr.indexOf((char)194) != -1)
	{
	    tmpstr = tmpstr.substring(0, tmpstr.indexOf((char)194)) + tmpstr.substring(tmpstr.indexOf((char)194) + 1);
	}

	//trim didn't do its job
	if ((int)tmpstr.charAt(0) == 32)
	    tmpstr = tmpstr.substring(1);

	if ((int)tmpstr.charAt(tmpstr.length() -1) == 32)
	    tmpstr = tmpstr.substring(0, tmpstr.length() - 1);

	return tmpstr;
    }
   */

  // Source for sample: http://javaalmanac.com/egs/javax.xml.transform/WriteDom.html
  // Parses an XML file and returns a DOM document.
  // If validating is true, the contents is validated against the DTD
  // specified in the file.
  public void parseXmlFile(String xml_url, boolean validating, DefaultHandler hnd) throws Exception
  {
    System.out.println("downloading from:" + xml_url);
    java.io.InputStream in = null;
    try
    {
      java.net.URL u = new java.net.URL(xml_url);
      java.net.URLConnection con = u.openConnection();
      in = u.openStream();

      factory.setValidating(validating);
      // Create the builder and parse the file
      factory.newSAXParser().parse(in, hnd);
    }
    finally
    {
      if (in != null)
      {
        try
        {
          in.close();
        }
        catch (Exception e)
        {}
      }
    }
  }

  private SAXParserFactory factory = SAXParserFactory.newInstance();

  private class SearchHandler extends DefaultHandler
  {
    private String current_tag;
    private StringBuffer buff = new StringBuffer();
    private String currID;
    private java.util.Map rv;
    public java.util.Map getSearchResults()
    {
      return rv;
    }

    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
    {
      if ("search".equalsIgnoreCase(qName))
      {
        rv = new java.util.HashMap();
      }
      else if (rv != null && "loc".equalsIgnoreCase(qName) && attributes != null)
      {
        currID = attributes.getValue("id");
      }
      current_tag = qName;
    }
    public void characters(char[] ch, int start, int length)
    {
      String data = new String(ch,start,length);

      //Jump blank chunk
      if (data.trim().length() == 0)
        return;
      buff.append(data);
    }
    public void endElement(String uri, String localName, String qName)
    {
      String data = buff.toString().trim();

      if (qName.equals(current_tag))
        buff = new StringBuffer();
      if ("err".equalsIgnoreCase(qName))
      {
        System.out.println(lastError = ("Weather.com returned error status " + data));
      }
      else if ("loc".equalsIgnoreCase(qName) && rv != null && currID != null)
      {
        rv.put(currID, data);
      }
    }
  }

  private class UpdateHandler extends DefaultHandler
  {
    private String current_tag;
    private StringBuffer buff = new StringBuffer();
    private boolean inHead = false;
    private boolean inLoc = false;
    private boolean inCC = false;
    private boolean inBar = false;
    private boolean inWind = false;
    private boolean inUV = false;
    private boolean inMoon = false;
    private boolean inLinks = false;
    private boolean inDayFC = false;
    private boolean foundWeather;
    private String unit_temp = "";
    private String unit_dist = "";
    private String unit_speed = "";
    private String unit_press = "";
    private String wind_t = null;
    private String wind_s = null;
    private String bar_r = null;
    private String bar_d = null;
    private int numLinks = 0;
    private String link_l = null;
    private String link_t = null;
    private String currDateNum = null;
    private String currPart = null;

    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
    {
      if ("weather".equals(qName))
        foundWeather = true;
      else if ("head".equals(qName))
        inHead = true;
      else if ("loc".equals(qName))
        inLoc = true;
      else if ("cc".equals(qName))
        inCC = true;
      else if (inCC && "bar".equals(qName))
        inBar = true;
      else if (inCC && "uv".equals(qName))
        inUV = true;
      else if (inCC && "wind".equals(qName))
        inWind = true;
      else if (inCC && "moon".equals(qName))
        inMoon = true;
      else if ("lnks".equals(qName))
        inLinks = true;
      else if ("dayf".equals(qName))
        inDayFC = true;
      else if (inDayFC && "day".equals(qName))
      {
        currDateNum = attributes.getValue("d");
        props.put("forecast/date" + currDateNum, attributes.getValue("t") + " " + attributes.getValue("dt"));
      }
      else if (inDayFC && currDateNum != null && "part".equals(qName))
      {
        currPart = attributes.getValue("p");
      }
      else if (inDayFC && currDateNum != null && currPart != null && "wind".equals(qName))
        inWind = true;
      current_tag = qName;
    }
    public void characters(char[] ch, int start, int length)
    {
      String data = new String(ch,start,length);

      //Jump blank chunk
      if (data.trim().length() == 0)
        return;
      buff.append(data);
    }
    public void endElement(String uri, String localName, String qName)
    {
      String data = buff.toString().trim();

      if (qName.equals(current_tag))
        buff = new StringBuffer();
      if ("err".equals(qName))
        System.out.println(lastError = ("Weather.com returned error status " + data));
      else if ("head".equals(qName))
        inHead = false;
      else if (inHead)
      {
        if ("ut".equals(qName))
          unit_temp = "\u00b0" + data;
        else if ("ud".equals(qName))
          unit_dist = data;
        else if ("us".equals(qName))
          unit_speed = data;
        else if ("up".equals(qName))
          unit_press = data;
      }
      else if ("loc".equals(qName))
        inLoc = false;
      else if (inLoc)
      {
        if ("dnam".equals(qName))
          props.put("loc/curr_location", data);
        else if ("sunr".equals(qName))
          props.put("loc/curr_sunrise", data);
        else if ("suns".equals(qName))
          props.put("loc/curr_sunset", data);
      }
      else if ("cc".equals(qName))
      {
        inCC = false;
        lastCCUpdateTime = System.currentTimeMillis();
      }
      else if (inCC)
      {
        if ("wind".equals(qName))
          inWind = false;
        else if ("uv".equals(qName))
          inUV = false;
        else if ("bar".equals(qName))
          inBar = false;
        else if ("moon".equals(qName))
          inMoon = false;
        else if (inMoon)
        {

        }
        else if (inWind)
        {
          if ("t".equals(qName))
            wind_t = data;
          else if ("s".equals(qName))
            wind_s = getWindInfo(data, unit_speed);
          if (wind_t != null && wind_s != null)
          {
            props.put("cc/curr_wind", wind_t + " " + wind_s);
            wind_t = wind_s = null;
          }
        }
        else if (inUV)
        {
          if ("i".equals(qName))
            props.put("cc/curr_uv_index", data);
          else if ("t".equals(qName))
            props.put("cc/curr_uv_warning", data);
        }
        else if (inBar)
        {
          if ("r".equals(qName))
            bar_r = data + unit_press;
          else if ("d".equals(qName))
            bar_d = data;
          if (bar_r != null && bar_d != null)
            props.put("cc/curr_pressure", bar_r + " " + bar_d);
        }
        else if ("obst".equals(qName))
          props.put("cc/curr_recorded_at", data);
        else if ("lsup".equals(qName))
          props.put("cc/curr_updated", data);
        else if ("t".equals(qName))
          props.put("cc/curr_conditions", data);
        else if ("vis".equals(qName))
          props.put("cc/curr_visibility", data + unit_dist);
        else if ("tmp".equals(qName))
          props.put("cc/curr_temp", data + unit_temp);
        else if ("hmid".equals(qName))
          props.put("cc/curr_humidity", data + "%");
        else if ("dewp".equals(qName))
          props.put("cc/curr_dewpoint", data + unit_temp);
        else if ("flik".equals(qName))
        {
          props.put("cc/curr_heatindex", data + unit_temp);
          props.put("cc/curr_windchill", data + unit_temp);
        }
        else if ("icon".equals(qName))
          props.put("cc/curr_icon", data);
      }
      else if ("lnks".equals(qName))
      {
        inLinks = false;
        props.put("sponsor/num_links", Integer.toString(numLinks));
        lastSponsorUpdateTime = System.currentTimeMillis();
      }
      else if (inLinks)
      {
        if ("link".equals(qName))
        {
          if (link_l != null && link_t != null)
          {
            props.put("sponsor/linkurl" + numLinks, link_l + "&par=" + partner_id);
            props.put("sponsor/linktitle" + numLinks, link_t);
            numLinks++;
          }
          link_l = null;
          link_t = null;
        }
        else if ("l".equals(qName))
          link_l = data;
        else if ("t".equals(qName))
          link_t = data;
      }
      else if ("dayf".equals(qName))
      {
        inDayFC = false;
        lastFCUpdateTime = System.currentTimeMillis();
      }
      else if (inDayFC)
      {
        if ("day".equals(qName))
          currDateNum = null;
        else if (currDateNum != null)
        {
          if ("part".equals(qName))
            currPart = null;
          else if (currPart != null)
          {
            if ("wind".equals(qName))
              inWind = false;
            else if (inWind)
            {
              if ("t".equals(qName))
                wind_t = data;
              else if ("s".equals(qName))
                wind_s = getWindInfo(data, unit_speed);
              if (wind_t != null && wind_s != null)
              {
                props.put("forecast/wind" + currPart + currDateNum, wind_t + " " + wind_s);
                wind_t = wind_s = null;
              }
            }
            else if ("t".equals(qName))
              props.put("forecast/conditions" + currPart + currDateNum, data);
            else if ("ppcp".equals(qName))
              props.put("forecast/precip" + currPart + currDateNum, data + "%");
            else if ("hmid".equals(qName))
              props.put("forecast/humid" + currPart + currDateNum, data + "%");
            else if ("icon".equals(qName))
              props.put("forecast/icon" + currPart + currDateNum,data);
          }
          else if ("hi".equals(qName))
            props.put("forecast/hi" + currDateNum, data + unit_temp);
          else if ("low".equals(qName))
            props.put("forecast/low" + currDateNum, data + unit_temp);
          else if ("sunr".equals(qName))
            props.put("forecast/sunrise" + currDateNum, data);
          else if ("suns".equals(qName))
            props.put("forecast/sunset" + currDateNum, data);
        }
      }
    }

    public void endDocument() throws SAXException
    {
      if (!foundWeather)
        System.out.println(lastError = ("Weather.com returned empty doc"));
    }
  }

}