text:
#region License

#endregion

using System;
using Spring.Core;

namespace Spring.Objects
{
    ///
    /// Extension of <see cref="AttributeAccessorSupport"/>,
    /// holding attributes as <see cref="IObjectMetadataElement"/> objects in order
    /// to keep track of the definition source.
    ///
    [Serializable]
    public class ObjectMetadataAttributeAccessor : AttributeAccessorSupport, IObjectMetadataElement
    {
	    private object _source;

	    ///
	    /// Set the configuration source object for this metadata element.
	    ///
The exact type of the object will depend on the configuration mechanism used.

	    ///
	    public object Source
        {
            get { return _source; }
            set { _source = value; }
        }

	    ///
	    /// Add the given BeanMetadataAttribute to this accessor's set of attributes.
	    ///
	    /// <param name="attribute">The BeanMetadataAttribute object to register</param>
	    public void AddMetadataAttribute(ObjectMetadataAttribute attribute)
        {
		    base.SetAttribute(attribute.Name, attribute);
	    }

	    ///
	    /// Look up the given BeanMetadataAttribute in this accessor's set of attributes.
        ///
        /// <param name="name">the name of the attribute</param>
	    /// <returns>the corresponding BeanMetadataAttribute object,
	    /// or null if no such attribute defined
        /// </returns>
	    public ObjectMetadataAttribute GetMetadataAttribute(string name)
	    {
	        return (ObjectMetadataAttribute) base.GetAttribute(name);
	    }

        public override void SetAttribute(string name, object value)
        {
            base.SetAttribute(name, new ObjectMetadataAttribute(name, value));
        }

	    public override object GetAttribute(string name)
	    {
	        var attribute = (ObjectMetadataAttribute) base.GetAttribute(name);
		    return (attribute != null ? attribute.Value : null);
	    }

	    public override object RemoveAttribute(string name)
	    {
	        var attribute = (ObjectMetadataAttribute) base.RemoveAttribute(name);
		    return (attribute != null ? attribute.Value : null);
	    }

    }
}


text:
if Cfg.db[:type] && Cfg.db[:name]
  values = Cfg.db.values_at(:type, :user, :pass, :host, :name)
  connection_string = '%s://%s:%s@%s/%s' % values
  Sequel.connect connection_string
end

redpajama_set_name: RedPajamaGithub


text:
package cd.go.contrib.elasticagents.marathon.executors;

import cd.go.contrib.elasticagents.marathon.*;
import cd.go.contrib.elasticagents.marathon.requests.CreateAgentRequest;
import cd.go.contrib.elasticagents.marathon.requests.ShouldAssignWorkRequest;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.junit.Before;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ShouldAssignWorkRequestExecutorTest extends BaseTest {

    private AgentInstances<MarathonInstance> agentInstances;
    private MarathonInstance instance;
    private final String environment = "production";
    private Map<String, String> properties = new HashMap<>();

    @Before
    public void setUp() throws Exception {
        marathonClientFactory mf = mock(marathonClientFactory.class);
        when(mf.marathon(any(PluginSettings.class))).thenReturn(createClient());
        agentInstances = new MarathonAgentInstances(mf);
        properties.put("Memory", "2048MB");
        properties.put("CPUs", "2");
        properties.put("Command", "");
        properties.put("Environment", "production");
        properties.put("Image", "gocdcontrib/ubuntu-docker-elastic-agent");
        instance = agentInstances.create(new CreateAgentRequest(UUID.randomUUID().toString(), properties, environment), createSettings());
    }

    @Test
    public void shouldNotAssignWorkToMissingContainer() throws Exception {
        ShouldAssignWorkRequest request = new ShouldAssignWorkRequest(new Agent("differentName", null, null, null), environment, properties);
        GoPluginApiResponse response = new ShouldAssignWorkRequestExecutor(request, agentInstances, null).execute();
        assertThat(response.responseCode(), is(200));
        assertThat(response.responseBody(), is("false"));
    }

    @Test
    public void shouldAssignWorkToContainerWithMatchingEnvironmentNameAndProperties() throws Exception {
        ShouldAssignWorkRequest request = new ShouldAssignWorkRequest(new Agent(instance.name(), null, null, null), environment, properties);
        GoPluginApiResponse response = new ShouldAssignWorkRequestExecutor(request, agentInstances, null).execute();
        assertThat(response.responseCode(), is(200));
        assertThat(response.responseBody(), is("true"));
    }

    @Test
    public void shouldNotAssignWorkToContainerWithDifferentEnvironmentName() throws Exception {
        ShouldAssignWorkRequest request = new ShouldAssignWorkRequest(new Agent(instance.name(), null, null, null), "FooEnv", properties);
        GoPluginApiResponse response = new ShouldAssignWorkRequestExecutor(request, agentInstances, null).execute();
        assertThat(response.responseCode(), is(200));
        assertThat(response.responseBody(), is("false"));
    }

    @Test
    public void shouldNotAssignWorkToContainerWithDifferentProperties() throws Exception {
        ShouldAssignWorkRequest request = new ShouldAssignWorkRequest(new Agent(instance.name(), null, null, null), environment, null);
        GoPluginApiResponse response = new ShouldAssignWorkRequestExecutor(request, agentInstances, null).execute();
        assertThat(response.responseCode(), is(200));
        assertThat(response.responseBody(), is("false"));
    }
}


text:
package themplator.utils;

import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

@SuppressWarnings("restriction")
public class LogUtils {

	public static void log(XMLEvent ev) {
		String s = str(ev);
		if(s!=null){
			System.out.println(s);
		}

	}

	public static String str(XMLEvent ev) {
		if (ev.isStartElement()) {
			StartElement se = ev.asStartElement();
			return("<" + se.getName().getLocalPart() + ">");
		} else if (ev.isEndElement()) {
			EndElement se = ev.asEndElement();
			return("</" + se.getName().getLocalPart() + ">");
		} else if (ev.isStartDocument()) {
			return("begin");
		} else if (ev.isEndDocument()) {
			return("end");
		} else if (ev.isCharacters()) {
			return("text: '"+ev.asCharacters().getData()+"'");
		}
		return null;

	}
}


text:
Wit.ai speech recognition

## Install

> npm install witai-speech [--save]

## Usage

`````javascript

var witai_speech = require('witai-speech');

var ACCESS_TOKEN = "6SQV3DEGQWIXW3R2EDFUMPQCVGOEIBCR";

witai_speech.ASR({
  file: 'demo.wav',
  developer_key: ACCESS_TOKEN
  }, function (err, res) {
    console.log(err, res);
  });

`````


text:
<?php

/**
* MainController.php
* Sabena Aerospace
* Author : Moers Serge
* Date : 5 Apr 2017
*/

namespace ORG\BirdBundle\Controller;

use ORG\BirdBundle\Model\Filter\Filter;
use ORG\BirdBundle\Model\Filter\FilterInterface;
use ORG\BirdBundle\Model\Menu\MenuDisabledTwig;
use ORG\BirdBundle\Model\OrderBy\OrderBy;
use ORG\BirdBundle\Model\OrderBy\OrderByInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class MainController extends Controller
{

    protected $login;

    public function setContainer(ContainerInterface $container = null)
    {
        parent::setContainer($container);
        $user = $this->getUser();
        $this->login = array(
            'loginAs' => $user->getLastname().", ".$user->getFirstname(),
            'attributes' => $user->getAttributes(),
        );

        //$this->get('session')->set('_locale', $this->login['attributes']['language']);

    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
	public function indexAction(Request $request){

	    $menuDisabledTwig = new MenuDisabledTwig();

		return $this->render('ORGBirdBundle:Main:Main.html.twig',array(
		    'title' => 'main.title',
            'menudisabled' => $menuDisabledTwig,
            'loginas' => $this->login['loginAs'],
            'layout' => $this->login['attributes']['layout'],
        ));

	}

    /**
     * @param Request $request
     * @return JsonResponse
     */
	public function gridAuthorsAction(Request $request){

	    //Obtenir l'instance du logger
        $logger = $this->get('monolog.logger.bird');
        if($request->isXmlHttpRequest()) {
            $authorCriteriaFilter = array();
            //Si des critères ont été sauvés dans la session, ils sont chargés et seront utilisés.
            if($request->getSession()->has('author_criteria_filter') && $request->getSession()->get('author_criteria_filter')['enabled']){
                $authorCriteriaFilter = $request->getSession()->get('author_criteria_filter');
                $authorCriteriaFilter['enabled'] = false;
                //var_dump($authorCriteriaFilter);exit;
            }
            else{
                $authorCriteriaFilter['type'] = $request->get('type');
                $authorCriteriaFilter['letter'] = $request->get('letter');
                $authorCriteriaFilter['sort'] = $request->get('sort');
                $authorCriteriaFilter['order'] = $request->get('order');
                $authorCriteriaFilter['enabled'] = false;
            }
            //Sauvegarde les parametres de session
            $request->getSession()->set('author_criteria_filter',$authorCriteriaFilter);
            //Tri alphabetique sans demande de tri
            if ($authorCriteriaFilter['type'] === 'alph'
                && null !== $authorCriteriaFilter['letter']
                && null == $authorCriteriaFilter['sort']
                && null == $authorCriteriaFilter['order'])
            {
                $logger->info($authorCriteriaFilter['type'], array($authorCriteriaFilter['letter']));
                    return new JsonResponse($this->getData($authorCriteriaFilter,true));
            }
            //Nous sommes dans le cas d'une demande de tri des colonnes sans filtre
            elseif (null === $authorCriteriaFilter['type']
                    && null === $authorCriteriaFilter['letter']
                    && null !== $authorCriteriaFilter['sort']
                    && null !== $authorCriteriaFilter['order'])
            {
                    return new JsonResponse($this->getData($authorCriteriaFilter,false,true));
            }
            elseif (null !== $authorCriteriaFilter['type']
                && null !== $authorCriteriaFilter['letter']
                && null !== $authorCriteriaFilter['sort']
                && null !== $authorCriteriaFilter['order'])
            {
                return new JsonResponse($this->getData($authorCriteriaFilter,true,true));
            }
            else
            {
                return new JsonResponse($this->getData($authorCriteriaFilter, false, false));
            }

        }
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function gridCyclesAction(Request $request)
    {
        //Obtenir l'instance du logger
        $logger = $this->get('monolog.logger.bird');
        $repository = $this->getDoctrine()->getRepository('ORGBirdBundle:Cycle');
        if(null !== $request->get('id_author')){
            //creation d'un objet Filter en mode stricte
            $filter = new Filter();
            $filter->setFields(array('id'));
            $filter->setValue($request->get('id_author'));
            $filter->setAlias(FilterInterface::ALIAS_NO_ROOT);
            $filter->setStrict(true);
            $filter->setComparator(FilterInterface::COMPARATOR_EQ);
            //creation d'un object OrderBy pour le tri
            $order = new OrderBy();
            $order->clear();
            //dans le cas d'une demande de tri
            if(null !== $request->get('sort') && null !== $request->get('order')){
                $order->push($request->get('sort'), $request->get('order'));
            }
            else{
                $order->push('title', 'ASC');
            }
            $order->push('title', 'ASC');
            $order->setAlias(OrderByInterface::ALIAS_ONLY_ROOT);
            $logger->info($repository->getQueryBuilderFiltered($filter, $order)->getQuery()->getSQL());
            //var_dump($repository->getQueryBuilderFiltered($filter, $order)->getQuery()->getArrayResult());exit;
            return new JsonResponse($repository->getQueryBuilderFiltered($filter, $order)->getQuery()->getArrayResult());

        }
        //supprime l'erreur lors du chargement de la page
        //car le controller doit absolument retourner une reponse
        return new JsonResponse(array(false));
    }

    public function gridBooksAction(Request $request)
    {
        //Obtenir l'instance du logger
        $logger = $this->get('monolog.logger.bird');
        if(null !== $request->get('id_cycle')){
            $repository = $this->getDoctrine()->getRepository('ORGBirdBundle:Book');
            //creation d'un objet Filter en mode stricte
            $filter = new Filter();
            $filter->setFields(array('cycle'));
            $filter->setValue($request->get('id_cycle'));
            $filter->setAlias(FilterInterface::ALIAS_ONLY_ROOT);
            $filter->setStrict(true);
            $filter->setComparator(FilterInterface::COMPARATOR_EQ);
            //creation d'un object OrderBy pour le tri
            $order = new OrderBy();
            $order->clear();
            //dans le cas d'une demande de tri
            if(null !== $request->get('sort') && null !== $request->get('order')){
                $order->push($request->get('sort'), $request->get('order'));
            }
            else{
                $order->push('title', 'ASC');
                $order->push('volume', 'ASC');
            }
            $order->setAlias(OrderByInterface::ALIAS_ONLY_ROOT);
            $query = $repository->getQueryBuilderFiltered($filter, $order)->getQuery();
            $logger->info($query->getSQL());
            return new JsonResponse($query->getArrayResult());
        }
        //supprime l'erreur lors du chargement de la page
        //car le controller doit absolument retourner une reponse
        return new JsonResponse(array(false));
    }

    /**
     * Return un tableau de resultat filtrer et trier
     * @param Request $request
     * @param bool $flag_filter
     * @param bool $flag_order
     * @return mixed
     */
    private function getData(array $authorCriteriaFilter, $flag_filter = false, $flag_order = false){

        //init
        $filter = new Filter();
        $filter->setFields(array('lastname'));
        $orderBy = new OrderBy();
        //Init repository
        $repository = $this->getDoctrine()->getRepository('ORGBirdBundle:Author');
        //Si le flag filter est true, on doit faire un tri alphabetique
        if($flag_filter){
            //Lorsque la lettre est =plus grande que 1 caractere on charge le wildcard % à la place de la lettre
            $filter->setValue(strlen($authorCriteriaFilter['letter']) > 1 ? '%' : $authorCriteriaFilter['letter']);
            $filter->setType(FilterInterface::START_WITH);
        }
        else{
            $filter->setValue('%');
        }
        //Si le flag order est true cela signifique que l'on a une demande de tri
        if($flag_order){
            //Vide le tableau
            $orderBy->clear();
            //On charge le champ
            $orderBy->push($authorCriteriaFilter['sort'], $authorCriteriaFilter['order']);
        }
        else{
            $orderBy = new OrderBy();
            $orderBy->push('lastname', 'ASC');
            $orderBy->push('firstname', 'ASC');
        }
        return $repository->getQueryBuilderFiltered($filter,$orderBy)->getQuery()->getResult();

    }

}


text:
"""
  The LinearModel folder includes different types of ScikitLearn Linear Model-based ROMs
  that are available via RAVEN
"""


text:
package guepardoapps.library.toolset.controller;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import java.util.Locale;

import es.dmoral.toasty.Toasty;

import guepardoapps.library.toolset.common.Logger;

public class PermissionController {

    private static final String TAG = PermissionController.class.getSimpleName();
    protected Logger _logger;

    protected Context _context;

    public PermissionController(@NonNull Context context) {
        _logger = new Logger(TAG);
        _logger.Debug("Created new " + TAG + "...");

        _context = context;
    }

    public void CheckPermissions(
            int callbackId,
            @NonNull String... permissionsId) {
        _logger.Debug(String.format(Locale.GERMAN, "Call for permission %s with id %s", permissionsId, callbackId));

        boolean hasPermission = true;

        for (String permission : permissionsId) {
            hasPermission = hasPermission
                    && (ContextCompat.checkSelfPermission(_context, permission) == PackageManager.PERMISSION_GRANTED);
        }

        if (!hasPermission) {
            try {
                ActivityCompat.requestPermissions((Activity) _context, permissionsId, callbackId);
            } catch (Exception ex) {
                _logger.Error(ex.toString());
                Toasty.error(_context, "Failed to ask for permissions!", Toast.LENGTH_LONG).show();
            }
        }
    }
}


text:
{% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}

{{entry.title}}

 {{ entry.subhed|safe }}

Notes: {{ entry.descript|safe }}

Date logged: {{ entry.publishdate }}
Status: {{ entry.status }}

{% if entry.private == "Private" or entry.private=="private" %}
Private
{% endif %}

Edit this entry
{% elif entry.private != "Private" and entry.private!="private" %}

{{entry.title}}

 {{ entry.subhed|safe }}

Notes: {{ entry.descript|safe }}

Date logged: {{ entry.publishdate }}
Status: {{ entry.status }}

{% if entry.private == "Private" or entry.private=="private" %}
Private
{% endif %}
{% else %}
So sorry. You must be logged in to edit an entry. Try again.
{% endif %}

{% endblock %}


text:
package burst.web.errorhandle;

import burst.web.framework.RawContext;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Burst
 *         13-12-4 上午12:30
 */
public class ServerErrorHandler implements IErrorHandler {

    public static final ServerErrorHandler INSTANCE = new ServerErrorHandler();

    private ServerErrorHandler() { }

    @Override
    public void handle(Object errorContext, RawContext rawContext) {
        rawContext.getResponse().setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}


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

namespace com.tinylabproductions.TLPLib.Collection {
  public static class IListDefaultImpls {
    public static int indexOf<A, C>(C c, A item) where C : IList<A> {
      var comparer = EqualityComparer<A>.Default;
      for (var idx = 0; idx < c.Count; idx++)
        if (comparer.Equals(c[idx], item))
          return idx;
      return -1;
    }

    public static bool contains<A, C>(C c, A item) where C : IList<A> =>
      indexOf(c, item) != -1;

    public static bool remove<A, C>(ref C c, A item) where C : IList<A> {
      var comparer = EqualityComparer<A>.Default;
      for (var idx = 0; idx < c.Count; idx++)
        if (comparer.Equals(c[idx], item)) {
          c.RemoveAt(idx);
          return true;
        }
      return false;
    }

    public static void insert<A, C>(ref C c, int idx, A item) where C : IList<A> {
      if (idx > c.Count) throw new ArgumentOutOfRangeException(
        nameof(idx), idx, "index is greater than the list size"
      );
      if (idx < 0) throw new ArgumentOutOfRangeException(
        nameof(idx), idx, "index is lesser than 0"
      );

      if (idx == c.Count) c.Add(item);
      else {
        var lastIdx = c.Count - 1;
        c.Add(c[lastIdx]);
        for (var i = lastIdx; i > idx; i--) c[i] = c[i - 1];
        c[idx] = item;
      }
    }

    public static void copyTo<C, A>(
      C c, A[] array, int targetStartIndex, int srcCopyFrom = 0, int srcCopyCount = -1
    )
      where C : IList<A>
    {
      if (array == null)
        throw new ArgumentNullException(nameof(array), "array is null");
      if (targetStartIndex < 0)
        throw new ArgumentOutOfRangeException(
          nameof(targetStartIndex),
          $"array index ({targetStartIndex}) is < 0"
        );
      if (srcCopyFrom < 0)
        throw new ArgumentOutOfRangeException(
          nameof(srcCopyFrom),
          $"array index ({srcCopyFrom}) is < 0"
        );
      if (srcCopyFrom >= c.Count)
        throw new ArgumentOutOfRangeException(
          nameof(srcCopyFrom),
          $"array index ({srcCopyFrom}) is > collection count ({c.Count})"
        );
      if (srcCopyCount < 0) srcCopyCount = c.Count - srcCopyFrom;
      var targetEndIndex = targetStartIndex + srcCopyCount;
      if (array.Length < targetEndIndex) throw new ArgumentException(
        $"Target array is too small ({nameof(targetEndIndex)}={targetEndIndex}, " +
        $"array length={array.Length})"
      );

      for (
        int srcIdx = srcCopyFrom, targetIdx = targetStartIndex;
        targetIdx < targetEndIndex;
        srcIdx++, targetIdx++
      ) {
        array[targetIdx] = c[srcIdx];
      }
    }
  }
}


text:
<!-- This is a generated file. Please do not edit directly -->

# Maintainers
This file lists how this cookbook project is maintained. When making changes to the system, this
file tells you who needs to review your patch - you need a simple majority of maintainers
for the relevant subsystems to provide a :+1: on your pull request. Additionally, you need
to not receive a veto from a Lieutenant or the Project Lead.

Check out [How Cookbooks are Maintained](https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/CONTRIBUTING.MD)
for details on the process and how to become a maintainer or the project lead.

# Project Maintainer
* [Adam Edwards](https://github.com/adamedx)

# Maintainers
* [Adam Edwards](https://github.com/adamedx)
* [Kartik Null Cating-Subramanian](https://github.com/ksubrama)
* [Steven Murawski](https://github.com/smurawski)
* [Matt Wrock](https://github.com/mwrock)
* [Jay Mundrawala](https://github.com/jaym)
* [Claire McQuin](https://github.com/mcquin)
* [Salim Alam](https://github.com/chefsalim)
* [Sean OMeara](https://github.com/someara)
* [Tim Smith](https://github.com/tas50)
* [Jennifer Davis](https://github.com/sigje)
* [Trevor Hess](https://github.com/trevorghess)


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

<title>R.style</title>
<meta name="date" content="2015-04-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.ohtu.wearable.wearabledataservice

Class R.style

java.lang.Object

com.ohtu.wearable.wearabledataservice.R.style

Enclosing class:

R

public static final class R.style
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

static int
CardText

static int
CardTitle

static int
DismissOverlayText

static int
DotsPageIndicatorStyle

static int
TextAppearance_Wearable_Large

static int
TextAppearance_Wearable_Medium

static int
TextAppearance_Wearable_Small

static int
TextView_Large

static int
TextView_Large_Light

static int
TextView_Medium

static int
TextView_Medium_Light

static int
TextView_Small

static int
TextView_Small_Light

static int
Theme_Wearable

static int
Theme_Wearable_Modal

Constructor Summary

Constructors

Constructor and Description

style()

Method Summary

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

CardText

public static final int CardText

See Also:

Constant Field Values

CardTitle

public static final int CardTitle

See Also:

Constant Field Values

DismissOverlayText

public static final int DismissOverlayText

See Also:

Constant Field Values

DotsPageIndicatorStyle

public static final int DotsPageIndicatorStyle

See Also:

Constant Field Values

TextAppearance_Wearable_Large

public static final int TextAppearance_Wearable_Large

See Also:

Constant Field Values

TextAppearance_Wearable_Medium

public static final int TextAppearance_Wearable_Medium

See Also:

Constant Field Values

TextAppearance_Wearable_Small

public static final int TextAppearance_Wearable_Small

See Also:

Constant Field Values

TextView_Large

public static final int TextView_Large

See Also:

Constant Field Values

TextView_Large_Light

public static final int TextView_Large_Light

See Also:

Constant Field Values

TextView_Medium

public static final int TextView_Medium

See Also:

Constant Field Values

TextView_Medium_Light

public static final int TextView_Medium_Light

See Also:

Constant Field Values

TextView_Small

public static final int TextView_Small

See Also:

Constant Field Values

TextView_Small_Light

public static final int TextView_Small_Light

See Also:

Constant Field Values

Theme_Wearable

public static final int Theme_Wearable

See Also:

Constant Field Values

Theme_Wearable_Modal

public static final int Theme_Wearable_Modal

See Also:

Constant Field Values

Constructor Detail

style

public style()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

use Phinx\Migration\AbstractMigration;

class MakeUniqIndexOnTrackId extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('music_info');
        $table
            ->removeIndex('track_id')
            ->addIndex(['track_id'], ['unique' => true])
            ->update();

    }

    /**
     * Migrate Up.
     */
    public function up()
    {

    }

    /**
     * Migrate Down.
     */
    public function down()
    {

    }
}


text:
#include "Buffer.h"

namespace buffer_general_callback {
	std::shared_ptr<overload_resolution> overload;
	NAN_METHOD(callback) {
		if (overload == nullptr) {
			throw std::runtime_error("buffer_general_callback is empty");
		}
		return overload->execute("buffer", info);
	}
}

Nan::Persistent<FunctionTemplate> Buffer::constructor;

std::string Buffer::name;

void
Buffer::Init(Handle<Object> target, std::shared_ptr<overload_resolution> overload) {
	name = "ogl::Buffer";
	buffer_general_callback::overload = overload;
	Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(buffer_general_callback::callback);
	constructor.Reset(ctor);
	auto itpl = ctor->InstanceTemplate();
	itpl->SetInternalFieldCount(1);
	ctor->SetClassName(Nan::New(name).ToLocalChecked());
	ctor->Inherit(Nan::New(IOArray::constructor));

	overload->register_type<Buffer>(ctor, "buffer", name);

//	interface BufferStatic {
//		/** @brief The constructors.
//
//		Creates empty ogl::Buffer object, creates ogl::Buffer object from existed buffer ( abufId
//		parameter), allocates memory for ogl::Buffer object or copies from host/device memory.
//		*/
//		new () : Buffer;
//
//		/** @overload
//		@param arows Number of rows in a 2D array.
//		@param acols Number of columns in a 2D array.
//		@param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details.
//		@param abufId Buffer object name.
//		@param autoRelease Auto release mode (if true, release will be called in object's destructor).
//		*/
//		new (arows: _st.int, acols : _st.int, atype : _st.int, abufId : _st.uint, autoRelease ? : boolean /*= //false*/) : Buffer;
//
//		/** @overload
//		@param asize 2D array size.
//		@param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details.
//		@param abufId Buffer object name.
//		@param autoRelease Auto release mode (if true, release will be called in object's destructor).
//		*/
//		new (asize: _types.Size, atype : _st.int, abufId : _st.uint, autoRelease : boolean /*= false*/) : Buffer;
//
//		/** @overload
//		@param arows Number of rows in a 2D array.
//		@param acols Number of columns in a 2D array.
//		@param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details.
//		@param target Buffer usage. See cv::ogl::Buffer::Target .
//		@param autoRelease Auto release mode (if true, release will be called in object's destructor).
//		*/
//		new (arows: _st.int, acols : _st.int, atype : _st.int, target ? : BufferTarget  /*= ARRAY_BUFFER*/, //autoRelease ? : boolean/*= false*/) : Buffer;
//
//		/** @overload
//		@param asize 2D array size.
//		@param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details.
//		@param target Buffer usage. See cv::ogl::Buffer::Target .
//		@param autoRelease Auto release mode (if true, release will be called in object's destructor).
//		*/
//		new (asize: _types.Size, atype : _st.int, target ? : BufferTarget /*= ARRAY_BUFFER*/, autoRelease ? : //boolean /*= false*/) : Buffer;
//
//		/** @overload
//		@param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ).
//		@param target Buffer usage. See cv::ogl::Buffer::Target .
//		@param autoRelease Auto release mode (if true, release will be called in object's destructor).
//		*/
//		new (arr: _st.InputArray, target ? : BufferTarget /*= ARRAY_BUFFER*/, autoRelease ? : boolean /*= false*/) : //Buffer;
//
//	}
//
//	interface Buffer extends _st.IOArray
//	{
//		//public:
//		//    /** @brief The target defines how you intend to use the buffer object.
//		//    */
//
//		//
//		//
//		/** @brief Allocates memory for ogl::Buffer object.
//
//		@param arows Number of rows in a 2D array.
//		@param acols Number of columns in a 2D array.
//		@param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details.
//		@param target Buffer usage. See cv::ogl::Buffer::Target .
//		@param autoRelease Auto release mode (if true, release will be called in object's destructor).
//		*/
//		create(arows: _st.int, acols : _st.int, atype : _st.int, target ? : BufferTarget /*= //ARRAY_BUFFER*/,autoRelease ? : boolean /*= false*/) : void;
//
//	/** @overload
//	@param asize 2D array size.
//	@param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details.
//	@param target Buffer usage. See cv::ogl::Buffer::Target .
//	@param autoRelease Auto release mode (if true, release will be called in object's destructor).
//	*/
//	create(asize: _types.Size, atype : _st.int , target ? : BufferTarget /*= ARRAY_BUFFER*/, autoRelease ? : /boolean //*= false*/) : void;
//
//	/** @brief Decrements the reference counter and destroys the buffer object if needed.
//
//	The function will call setAutoRelease(true) .
//	*/
//	release() : void;
//
//	/** @brief Sets auto release mode.
//
//	The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was
//	bound to a window it could be released at any time (user can close a window). If object's destructor
//	is called after destruction of the context it will cause an error. Thus ogl::Buffer doesn't destroy
//	OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context).
//	This function can force ogl::Buffer destructor to destroy OpenGL object.
//	@param flag Auto release mode (if true, release will be called in object's destructor).
//	*/
//	setAutoRelease(flag : boolean) : void;
//
//	/** @brief Copies from host/device memory to OpenGL buffer.
//	@param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ).
//	@param target Buffer usage. See cv::ogl::Buffer::Target .
//	@param autoRelease Auto release mode (if true, release will be called in object's destructor).
//	*/
//	copyFrom(arr: _st.InputArray, target ? : BufferTarget /*= ARRAY_BUFFER*/, autoRelease ? : boolean /*= false*/) : //void;
//
//	/** @overload */
//	//copyFrom(arr: _st.InputArray, stream: cuda::Stream& , target?: BufferTarget /*= ARRAY_BUFFER*/, autoRelease? : //boolean /*= false*/): void;
//	//
//	/** @brief Copies from OpenGL buffer to host/device memory or another OpenGL buffer object.
//
//	@param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , std::vector or
//	ogl::Buffer ).
//	*/
//	copyTo(arr: _st.OutputArray) : void;
//
//	/** @overload */
//	//copyTo(arr: _st.OutputArray, stream: cuda::Stream): void;
//
//	/** @brief Creates a full copy of the buffer object and the underlying data.
//
//	@param target Buffer usage for destination buffer.
//	@param autoRelease Auto release mode for destination buffer.
//	*/
//	clone(target ? : BufferTarget /* = ARRAY_BUFFER*/, autoRelease ? : boolean/* = false*/) : Buffer;
//	//
//	//    /** @brief Binds OpenGL buffer to the specified buffer binding point.
//	//
//	//    @param target Binding point. See cv::ogl::Buffer::Target .
//	//     */
//	//    void bind(Target target) const;
//	//
//	//    /** @brief Unbind any buffers from the specified binding point.
//	//
//	//    @param target Binding point. See cv::ogl::Buffer::Target .
//	//     */
//	//    static void unbind(Target target);
//	//
//	/** @brief Maps OpenGL buffer to host memory.
//
//	mapHost maps to the client's address space the entire data store of the buffer object. The data can
//	then be directly read and/or written relative to the returned pointer, depending on the specified
//	access policy.
//
//	A mapped data store must be unmapped with ogl::Buffer::unmapHost before its buffer object is used.
//
//	This operation can lead to memory transfers between host and device.
//
//	Only one buffer object can be mapped at a time.
//	@param access Access policy, indicating whether it will be possible to read from, write to, or both
//	read from and write to the buffer object's mapped data store. The symbolic constant must be
//	ogl::Buffer::READ_ONLY , ogl::Buffer::WRITE_ONLY or ogl::Buffer::READ_WRITE .
//	*/
//	mapHost(access: BufferAccess) : _mat.Mat
//
//		/** @brief Unmaps OpenGL buffer.
//		*/
//		unmapHost() : void;
//
//	//! map to device memory (blocking)
//	mapDevice() : _cuda.cuda.GpuMat
//		unmapDevice() : void;
//	//
//	//    /** @brief Maps OpenGL buffer to CUDA device memory.
//	//
//	//    This operatation doesn't copy data. Several buffer objects can be mapped to CUDA memory at a time.
//	//
//	//    A mapped data store must be unmapped with ogl::Buffer::unmapDevice before its buffer object is used.
//	//     */
//	//    cuda::GpuMat mapDevice(cuda::Stream& stream);
//	//
//	//    /** @brief Unmaps OpenGL buffer.
//	//    */
//	//    void unmapDevice(cuda::Stream& stream);
//	//
//	rows() : _st.int;
//	cols() : _st.int;
//	size() : _types.Size;
//	empty() : boolean;
//
//	type() : _st.int;
//	depth() : _st.int;
//	channels() : _st.int;
//	elemSize() : _st.int;
//	elemSize1() : _st.int;
//
//	//! get OpenGL opject id
//	bufId() : _st.uint;
//	//
//	//    class Impl;
//	//
//	//private:
//	//    Ptr<Impl> impl_;
//	//    int rows_;
//	//    int cols_;
//	//    int type_;
//	};
//
//	export var Buffer : BufferStatic = alvision_module.Buffer;

}

v8::Local<v8::Function> Buffer::get_constructor() {
	assert(!constructor.IsEmpty() && "constructor is empty");
	return Nan::New(constructor)->GetFunction();
}


text:
module Caboose
  class LineItemModification < ActiveRecord::Base
    self.table_name  = 'store_line_item_modifications'
    self.primary_key = 'id'

    belongs_to :line_item, :class_name => 'Caboose::LineItem'
    belongs_to :modification, :class_name => 'Caboose::Modification'
    belongs_to :modification_value, :class_name => 'Caboose::ModificationValue'
    attr_accessible :id,
      :line_item_id,
      :modification_id,
      :modification_value_id,
      :input

  end
end


text:
<!--
    Description: Ensure version 1.0 doesn't cause a KeyError
    Expect: entries[0].psc_chapters.chapters
-->
<rss xmlns:psc="http://podlove.org/simple-chapters">
    <channel>
        <item>
            <psc:chapters version="1.0">
               <psc:chapter start="00:00:00" title="Example" />
            </psc:chapters>
        </item>
    </channel>
</rss>


text:
#include <aws/memorydb/model/ReshardingStatus.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace MemoryDB
{
namespace Model
{

ReshardingStatus::ReshardingStatus() :
    m_slotMigrationHasBeenSet(false)
{
}

ReshardingStatus::ReshardingStatus(JsonView jsonValue) :
    m_slotMigrationHasBeenSet(false)
{
  *this = jsonValue;
}

ReshardingStatus& ReshardingStatus::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("SlotMigration"))
  {
    m_slotMigration = jsonValue.GetObject("SlotMigration");

    m_slotMigrationHasBeenSet = true;
  }

  return *this;
}

JsonValue ReshardingStatus::Jsonize() const
{
  JsonValue payload;

  if(m_slotMigrationHasBeenSet)
  {
   payload.WithObject("SlotMigration", m_slotMigration.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace MemoryDB
} // namespace Aws


text:
#import "audio/ios/CDAudioManager.h"

NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";

//NSOperation object used to asynchronously initialise
@implementation CDAsynchInitialiser

-(void) main {
    [super main];
    [CDAudioManager sharedManager];
}

@end

@implementation CDLongAudioSource

@synthesize audioSourcePlayer, audioSourceFilePath, delegate, backgroundMusic, paused;

-(id) init {
    if ((self = [super init])) {
        state = kLAS_Init;
        volume = 1.0f;
        mute = NO;
        enabled_ = YES;
        paused = NO;
        stopped = NO;
    }
    return self;
}

-(void) dealloc {
    CDLOGINFO(@"Denshion::CDLongAudioSource - deallocating %@", self);
    [audioSourcePlayer release];
    [audioSourceFilePath release];
    [super dealloc];
}

-(void) load:(NSString*) filePath {
    //We have already loaded a file previously, check if we are being asked to load the same file
    if (state == kLAS_Init || ![filePath isEqualToString:audioSourceFilePath]) {
        CDLOGINFO(@"Denshion::CDLongAudioSource - Loading new audio source %@",filePath);
        //New file
        if (state != kLAS_Init) {
            [audioSourceFilePath release];//Release old file path
            [audioSourcePlayer release];//Release old AVAudioPlayer, they can't be reused
        }
        audioSourceFilePath = [filePath copy];
        NSError *error = nil;
        NSString *path = [CDUtilities fullPathFromRelativePath:audioSourceFilePath];
        audioSourcePlayer = [(AVAudioPlayer*)[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
        if (error == nil) {
            [audioSourcePlayer prepareToPlay];
            audioSourcePlayer.delegate = self;
            if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceFileDidChange:)]) {
                //Tell our delegate the file has changed
                [delegate cdAudioSourceFileDidChange:self];
            }
        } else {
            CDLOG(@"Denshion::CDLongAudioSource - Error initialising audio player: %@",error);
        }
    } else {
        //Same file - just return it to a consistent state
        [self pause];
        [self rewind];
    }
    audioSourcePlayer.volume = volume;
    audioSourcePlayer.numberOfLoops = numberOfLoops;
    state = kLAS_Loaded;
}

-(void) play {
    if (enabled_) {
        systemPaused = NO;
        paused = NO;
        stopped = NO;
        [audioSourcePlayer play];
    } else {
        CDLOGINFO(@"Denshion::CDLongAudioSource long audio source didn't play because it is disabled");
    }
}

-(void) stop {
    paused = NO;
    stopped = YES;
    [audioSourcePlayer stop];
}

-(void) pause {
    paused = YES;
    [audioSourcePlayer pause];
}

-(void) rewind {
    paused = NO;
    [audioSourcePlayer setCurrentTime:0];
    [audioSourcePlayer play];
    stopped = NO;
}

-(void) resume {
    if (!stopped) {
        paused = NO;
        [audioSourcePlayer play];
    }
}

-(BOOL) isPlaying {
    if (state != kLAS_Init) {
        return [audioSourcePlayer isPlaying];
    } else {
        return NO;
    }
}

-(void) setVolume:(float) newVolume
{
    volume = newVolume;
    if (state != kLAS_Init && !mute) {
        audioSourcePlayer.volume = newVolume;
    }
}

-(float) volume
{
    return volume;
}

#pragma mark Audio Interrupt Protocol
-(BOOL) mute
{
    return mute;
}

-(void) setMute:(BOOL) muteValue
{
    if (mute != muteValue) {
        if (mute) {
            //Turn sound back on
            audioSourcePlayer.volume = volume;
        } else {
            audioSourcePlayer.volume = 0.0f;
        }
        mute = muteValue;
    }
}

-(BOOL) enabled
{
    return enabled_;
}

-(void) setEnabled:(BOOL)enabledValue
{
    if (enabledValue != enabled_) {
        enabled_ = enabledValue;
        if (!enabled_) {
            //"Stop" the sounds
            [self pause];
            [self rewind];
        }
    }
}

-(NSInteger) numberOfLoops {
    return numberOfLoops;
}

-(void) setNumberOfLoops:(NSInteger) loopCount
{
    audioSourcePlayer.numberOfLoops = loopCount;
    numberOfLoops = loopCount;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    CDLOGINFO(@"Denshion::CDLongAudioSource - audio player finished");
#if TARGET_IPHONE_SIMULATOR
    CDLOGINFO(@"Denshion::CDLongAudioSource - workaround for OpenAL clobbered audio issue");
    //This is a workaround for an issue in all simulators (tested to 3.1.2).  Problem is
    //that OpenAL audio playback is clobbered when an AVAudioPlayer stops.  Workaround
    //is to keep the player playing on an endless loop with 0 volume and then when
    //it is played again reset the volume and set loop count appropriately.
    //NB: this workaround is not foolproof but it is good enough for most situations.
    player.numberOfLoops = -1;
    player.volume = 0;
    [player play];
#endif
    if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceDidFinishPlaying:)]) {
        [delegate cdAudioSourceDidFinishPlaying:self];
    }
}

-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
    CDLOGINFO(@"Denshion::CDLongAudioSource - audio player interrupted");
}

-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
    CDLOGINFO(@"Denshion::CDLongAudioSource - audio player resumed");
    if (self.backgroundMusic) {
        //Check if background music can play as rules may have changed during
        //the interruption. This is to address a specific issue in 4.x when
        //fast task switching
        if([CDAudioManager sharedManager].willPlayBackgroundMusic) {
            [player play];
        }
    } else {
        [player play];
    }
}

@end

@interface CDAudioManager (PrivateMethods)
-(BOOL) audioSessionSetActive:(BOOL) active;
-(BOOL) audioSessionSetCategory:(NSString*) category;
-(void) badAlContextHandler;
@end

@implementation CDAudioManager
#define BACKGROUND_MUSIC_CHANNEL kASC_Left

@synthesize soundEngine, willPlayBackgroundMusic;
static CDAudioManager *sharedManager;
static tAudioManagerState _sharedManagerState = kAMStateUninitialised;
static tAudioManagerMode configuredMode;
static BOOL configured = FALSE;

-(BOOL) audioSessionSetActive:(BOOL) active {
    NSError *activationError = nil;
    if ([[AVAudioSession sharedInstance] setActive:active error:&activationError]) {
        _audioSessionActive = active;
        CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active);
        return YES;
    } else {
        //Failed
        CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError);
        return NO;
    }
}

-(BOOL) audioSessionSetCategory:(NSString*) category {
    NSError *categoryError = nil;
    if ([[AVAudioSession sharedInstance] setCategory:category error:&categoryError]) {
        CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category);
        return YES;
    } else {
        //Failed
        CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError);
        return NO;
    }
}

// Init
+ (CDAudioManager *) sharedManager
{
    @synchronized(self)     {
        if (!sharedManager) {
            if (!configured) {
                //Set defaults here
                configuredMode = kAMM_FxPlusMusicIfNoOtherAudio;
            }
            sharedManager = [[CDAudioManager alloc] init:configuredMode];
            _sharedManagerState = kAMStateInitialised;//This is only really relevant when using asynchronous initialisation
            [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_AudioManagerInitialised object:nil];
        }
    }
    return sharedManager;
}

+ (tAudioManagerState) sharedManagerState {
    return _sharedManagerState;
}

/**
 * Call this to set up audio manager asynchronously.  Initialisation is finished when sharedManagerState == kAMStateInitialised
 */
+ (void) initAsynchronously: (tAudioManagerMode) mode {
    @synchronized(self) {
        if (_sharedManagerState == kAMStateUninitialised) {
            _sharedManagerState = kAMStateInitialising;
            [CDAudioManager configure:mode];
            CDAsynchInitialiser *initOp = [[[CDAsynchInitialiser alloc] init] autorelease];
            NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease];
            [opQ addOperation:initOp];
        }
    }
}

+ (id) alloc
{
    @synchronized(self)     {
        NSAssert(sharedManager == nil, @"Attempted to allocate a second instance of a singleton.");
        return [super alloc];
    }
    return nil;
}

/*
 * Call this method before accessing the shared manager in order to configure the shared audio manager
 */
+ (void) configure: (tAudioManagerMode) mode {
    configuredMode = mode;
    configured = TRUE;
}

-(BOOL) isOtherAudioPlaying
{
    // AudioSessionGetProperty removed from tvOS 9.1
#if defined(CC_TARGET_OS_TVOS)
    return false;
#else
    UInt32 isPlaying = 0;
    UInt32 varSize = sizeof(isPlaying);
    AudioSessionGetProperty (kAudioSessionProperty_OtherAudioIsPlaying, &varSize, &isPlaying);
    return (isPlaying != 0);
#endif
}

-(void) setMode:(tAudioManagerMode) mode {

    _mode = mode;
    switch (_mode) {

        case kAMM_FxOnly:
            //Share audio with other app
            CDLOGINFO(@"Denshion::CDAudioManager - Audio will be shared");
            //_audioSessionCategory = kAudioSessionCategory_AmbientSound;
            _audioSessionCategory = AVAudioSessionCategoryAmbient;
            willPlayBackgroundMusic = NO;
            break;

        case kAMM_FxPlusMusic:
            //Use audio exclusively - if other audio is playing it will be stopped
            CDLOGINFO(@"Denshion::CDAudioManager -  Audio will be exclusive");
            //_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound;
            _audioSessionCategory = AVAudioSessionCategorySoloAmbient;
            willPlayBackgroundMusic = YES;
            break;

        case kAMM_MediaPlayback:
            //Use audio exclusively, ignore mute switch and sleep
            CDLOGINFO(@"Denshion::CDAudioManager -  Media playback mode, audio will be exclusive");
            //_audioSessionCategory = kAudioSessionCategory_MediaPlayback;
            _audioSessionCategory = AVAudioSessionCategoryPlayback;
            willPlayBackgroundMusic = YES;
            break;

        case kAMM_PlayAndRecord:
            //Use audio exclusively, ignore mute switch and sleep, has inputs and outputs
            CDLOGINFO(@"Denshion::CDAudioManager -  Play and record mode, audio will be exclusive");
            //_audioSessionCategory = kAudioSessionCategory_PlayAndRecord;
            _audioSessionCategory = AVAudioSessionCategoryPlayAndRecord;
            willPlayBackgroundMusic = YES;
            break;

        default:
            //kAudioManagerFxPlusMusicIfNoOtherAudio
            if ([self isOtherAudioPlaying]) {
                CDLOGINFO(@"Denshion::CDAudioManager - Other audio is playing audio will be shared");
                //_audioSessionCategory = kAudioSessionCategory_AmbientSound;
                _audioSessionCategory = AVAudioSessionCategoryAmbient;
                willPlayBackgroundMusic = NO;
            } else {
                CDLOGINFO(@"Denshion::CDAudioManager - Other audio is not playing audio will be exclusive");
                //_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound;
                _audioSessionCategory = AVAudioSessionCategorySoloAmbient;
                willPlayBackgroundMusic = YES;
            }

            break;
    }

    [self audioSessionSetCategory:_audioSessionCategory];

}

/**
 * This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the
 * audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following
 * standard practices. If we detect this situation then we will attempt to resume the audio session ourselves.
 * Known triggers: lock the device then unlock it (iOS 4.2 gm), playback a song using MPMediaPlayer (iOS 4.0)
 */
- (void) badAlContextHandler {
    if (_interrupted && alcGetCurrentContext() == NULL) {
        CDLOG(@"Denshion::CDAudioManager - bad OpenAL context detected, attempting to resume audio session");
        [self audioSessionResumed];
    }
}

- (id) init: (tAudioManagerMode) mode {
    if ((self = [super init])) {

        // 'delegate' not supported on tvOS
#if !defined(CC_TARGET_OS_TVOS)
        //Initialise the audio session
        AVAudioSession* session = [AVAudioSession sharedInstance];
        session.delegate = self;
#endif

        _mode = mode;
        backgroundMusicCompletionSelector = nil;
        _isObservingAppEvents = FALSE;
        _mute = NO;
        _resigned = NO;
        _interrupted = NO;
        enabled_ = YES;
        _audioSessionActive = NO;
        [self setMode:mode];
        soundEngine = [[CDSoundEngine alloc] init];

        //Set up audioSource channels
        audioSourceChannels = [[NSMutableArray alloc] init];
        CDLongAudioSource *leftChannel = [[CDLongAudioSource alloc] init];
        leftChannel.backgroundMusic = YES;
        CDLongAudioSource *rightChannel = [[CDLongAudioSource alloc] init];
        rightChannel.backgroundMusic = NO;
        [audioSourceChannels insertObject:leftChannel atIndex:kASC_Left];
        [audioSourceChannels insertObject:rightChannel atIndex:kASC_Right];
        [leftChannel release];
        [rightChannel release];
        //Used to support legacy APIs
        backgroundMusic = [self audioSourceForChannel:BACKGROUND_MUSIC_CHANNEL];
        backgroundMusic.delegate = self;

        //Add handler for bad al context messages, these are posted by the sound engine.
        [[NSNotificationCenter defaultCenter] addObserver:self    selector:@selector(badAlContextHandler) name:kCDN_BadAlContext object:nil];

    }
    return self;
}

-(void) dealloc {
    CDLOGINFO(@"Denshion::CDAudioManager - deallocating");
    [self stopBackgroundMusic];
    [soundEngine release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self audioSessionSetActive:NO];
    [audioSourceChannels release];
    [super dealloc];
}

/** Retrieves the audio source for the specified channel */
-(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel
{
    return (CDLongAudioSource*)[audioSourceChannels objectAtIndex:channel];
}

/** Loads the data from the specified file path to the channel's audio source */
-(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel
{
    CDLongAudioSource *audioSource = [self audioSourceForChannel:channel];
    if (audioSource) {
        [audioSource load:filePath];
    }
    return audioSource;
}

-(BOOL) isBackgroundMusicPlaying {
    return [self.backgroundMusic isPlaying];
}

//NB: originally I tried using a route change listener and intended to store the current route,
//however, on a 3gs running 3.1.2 no route change is generated when the user switches the
//ringer mute switch to off (i.e. enables sound) therefore polling is the only reliable way to
//determine ringer switch state
-(BOOL) isDeviceMuted {

#if TARGET_IPHONE_SIMULATOR || defined(CC_TARGET_OS_TVOS)
    //Calling audio route stuff on the simulator causes problems
    return NO;
#else
    CFStringRef newAudioRoute;
    UInt32 propertySize = sizeof (CFStringRef);

    AudioSessionGetProperty (
                             kAudioSessionProperty_AudioRoute,
                             &propertySize,
                             &newAudioRoute
                             );

    if (newAudioRoute == NULL) {
        //Don't expect this to happen but playing safe otherwise a null in the CFStringCompare will cause a crash
        return YES;
    } else {
        CFComparisonResult newDeviceIsMuted =    CFStringCompare (
                                                                 newAudioRoute,
                                                                 (CFStringRef) @"",
                                                                 0
                                                                 );

        return (newDeviceIsMuted == kCFCompareEqualTo);
    }
#endif
}

#pragma mark Audio Interrupt Protocol

-(BOOL) mute {
    return _mute;
}

-(void) setMute:(BOOL) muteValue {
    if (muteValue != _mute) {
        _mute = muteValue;
        [soundEngine setMute:muteValue];
        for( CDLongAudioSource *audioSource in audioSourceChannels) {
            audioSource.mute = muteValue;
        }
    }
}

-(BOOL) enabled {
    return enabled_;
}

-(void) setEnabled:(BOOL) enabledValue {
    if (enabledValue != enabled_) {
        enabled_ = enabledValue;
        [soundEngine setEnabled:enabled_];
        for( CDLongAudioSource *audioSource in audioSourceChannels) {
            audioSource.enabled = enabled_;
        }
    }
}

-(CDLongAudioSource*) backgroundMusic
{
    return backgroundMusic;
}

//Load background music ready for playing
-(void) preloadBackgroundMusic:(NSString*) filePath
{
    [self.backgroundMusic load:filePath];
}

-(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop
{
    [self.backgroundMusic load:filePath];

	if (loop) {
		[self.backgroundMusic setNumberOfLoops:-1];
	} else {
		[self.backgroundMusic setNumberOfLoops:0];
	}

	if (!willPlayBackgroundMusic || _mute) {
		CDLOGINFO(@"Denshion::CDAudioManager - play bgm aborted because audio is not exclusive or sound is muted");
		return;
	}

	[self.backgroundMusic play];
}

-(void) stopBackgroundMusic
{
    [self.backgroundMusic stop];
}

-(void) pauseBackgroundMusic
{
    [self.backgroundMusic pause];
}

-(void) resumeBackgroundMusic
{
    if (!willPlayBackgroundMusic || _mute) {
        CDLOGINFO(@"Denshion::CDAudioManager - resume bgm aborted because audio is not exclusive or sound is muted");
        return;
    }

    if (![self.backgroundMusic paused]) {
        return;
    }

    [self.backgroundMusic resume];
}

-(void) rewindBackgroundMusic
{
    [self.backgroundMusic rewind];
}

-(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector {
    backgroundMusicCompletionListener = listener;
    backgroundMusicCompletionSelector = selector;
}

/*
 * Call this method to have the audio manager automatically handle application resign and
 * become active.  Pass a tAudioManagerResignBehavior to indicate the desired behavior
 * for resigning and becoming active again.
 *
 * If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive
 * methods are automatically called, otherwise you must call them yourself at the appropriate time.
 *
 * Based on idea of Dominique Bongard
 */
-(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle {

    if (!_isObservingAppEvents && autoHandle) {
        [[NSNotificationCenter defaultCenter] addObserver:self    selector:@selector(applicationWillResignActive:) name:@"UIApplicationWillResignActiveNotification" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self    selector:@selector(applicationDidBecomeActive:) name:@"UIApplicationDidBecomeActiveNotification" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self    selector:@selector(applicationWillTerminate:) name:@"UIApplicationWillTerminateNotification" object:nil];
        _isObservingAppEvents = TRUE;
    }
    _resignBehavior = resignBehavior;
}

- (void) applicationWillResignActive {
    _resigned = YES;

    //Set the audio session to one that allows sharing so that other audio won't be clobbered on resume
    [self audioSessionSetCategory:AVAudioSessionCategoryAmbient];

    switch (_resignBehavior) {

        case kAMRBStopPlay:

            for( CDLongAudioSource *audioSource in audioSourceChannels) {
                if (!audioSource->systemPaused) {
                    if (audioSource.isPlaying) {
                        audioSource->systemPaused = YES;
                        audioSource->systemPauseLocation = audioSource.audioSourcePlayer.currentTime;
                        [audioSource pause];
                    } else {
                        //Music is either paused or stopped, if it is paused it will be restarted
                        //by OS so we will stop it.
                        audioSource->systemPaused = NO;
                        [audioSource stop];
                    }
                }
            }
            break;

        case kAMRBStop:
            //Stop music regardless of whether it is playing or not because if it was paused
            //then the OS would resume it
            for( CDLongAudioSource *audioSource in audioSourceChannels) {
                [audioSource stop];
            }

        default:
            break;

    }
    CDLOGINFO(@"Denshion::CDAudioManager - handled resign active");
}

//Called when application resigns active only if setResignBehavior has been called
- (void) applicationWillResignActive:(NSNotification *) notification
{
    [self applicationWillResignActive];
}

- (void) applicationDidBecomeActive {

    if (_resigned) {
        _resigned = NO;
        //Reset the mode incase something changed with audio while we were inactive
        [self setMode:_mode];
        switch (_resignBehavior) {

            case kAMRBStopPlay:

                //Music had been stopped but stop maintains current time
                //so playing again will continue from where music was before resign active.
                //We check if music can be played because while we were inactive the user might have
                //done something that should force music to not play such as starting a track in the iPod
                if (self.willPlayBackgroundMusic) {
                    for( CDLongAudioSource *audioSource in audioSourceChannels) {
                        if (audioSource->systemPaused) {
                            [audioSource resume];
                            audioSource->systemPaused = NO;
                        }
                    }
                }
                break;

            default:
                break;

        }
        CDLOGINFO(@"Denshion::CDAudioManager - audio manager handled become active");
    }
}

//Called when application becomes active only if setResignBehavior has been called
- (void) applicationDidBecomeActive:(NSNotification *) notification
{
    [self applicationDidBecomeActive];
}

//Called when application terminates only if setResignBehavior has been called
- (void) applicationWillTerminate:(NSNotification *) notification
{
    CDLOGINFO(@"Denshion::CDAudioManager - audio manager handling terminate");
    [self stopBackgroundMusic];
}

/** The audio source completed playing */
- (void) cdAudioSourceDidFinishPlaying:(CDLongAudioSource *) audioSource {
    CDLOGINFO(@"Denshion::CDAudioManager - audio manager got told background music finished");
    if (backgroundMusicCompletionSelector != nil) {
        [backgroundMusicCompletionListener performSelector:backgroundMusicCompletionSelector];
    }
}

-(void) beginInterruption {
    CDLOGINFO(@"Denshion::CDAudioManager - begin interruption");
    [self audioSessionInterrupted];
}

-(void) endInterruption {
    CDLOGINFO(@"Denshion::CDAudioManager - end interruption");
    [self audioSessionResumed];
}

#if __CC_PLATFORM_IOS >= 40000
-(void) endInterruptionWithFlags:(NSUInteger)flags {
    CDLOGINFO(@"Denshion::CDAudioManager - interruption ended with flags %i",flags);
    if (flags == AVAudioSessionInterruptionFlags_ShouldResume) {
        [self audioSessionResumed];
    }
}
#endif

-(void)audioSessionInterrupted
{
    if (!_interrupted) {
        CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted");
        _interrupted = YES;

        // Deactivate the current audio session
        [self audioSessionSetActive:NO];

        if (alcGetCurrentContext() != NULL) {
            CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL");

            ALenum  error = AL_NO_ERROR;

            // set the current context to NULL will 'shutdown' openAL
            alcMakeContextCurrent(NULL);

            if((error = alGetError()) != AL_NO_ERROR) {
                CDLOG(@"Denshion::CDAudioManager - Error making context current %x\n", error);
            }
            #pragma unused(error)
        }
    }
}

-(void)audioSessionResumed
{
    if (_interrupted) {
        CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed");
        _interrupted = NO;

        BOOL activationResult = NO;
        // Reactivate the current audio session
        activationResult = [self audioSessionSetActive:YES];

        //This code is to handle a problem with iOS 4.0 and 4.01 where reactivating the session can fail if
        //task switching is performed too rapidly. A test case that reliably reproduces the issue is to call the
        //iPhone and then hang up after two rings (timing may vary ;))
        //Basically we keep waiting and trying to let the OS catch up with itself but the number of tries is
        //limited.
        if (!activationResult) {
            CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle");
            int activateCount = 0;
            while (!activationResult && activateCount < 10) {
                [NSThread sleepForTimeInterval:0.5];
                activationResult = [self audioSessionSetActive:YES];
                activateCount++;
                CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult);
            }
        }

        if (alcGetCurrentContext() == NULL) {
            CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context");
            ALenum  error = AL_NO_ERROR;
            // Restore open al context
            alcMakeContextCurrent([soundEngine openALContext]);
            if((error = alGetError()) != AL_NO_ERROR) {
                CDLOG(@"Denshion::CDAudioManager - Error making context current%x\n", error);
            }
            #pragma unused(error)
        }
    }
}

+(void) end {
    [sharedManager release];
    sharedManager = nil;
}

@end

///////////////////////////////////////////////////////////////////////////////////////
@implementation CDLongAudioSourceFader

-(void) _setTargetProperty:(float) newVal {
    ((CDLongAudioSource*)target).volume = newVal;
}

-(float) _getTargetProperty {
    return ((CDLongAudioSource*)target).volume;
}

-(void) _stopTarget {
    //Pause instead of stop as stop releases resources and causes problems in the simulator
    [((CDLongAudioSource*)target) pause];
}

-(Class) _allowableType {
    return [CDLongAudioSource class];
}

@end
///////////////////////////////////////////////////////////////////////////////////////
@implementation CDBufferManager

-(id) initWithEngine:(CDSoundEngine *) theSoundEngine {
    if ((self = [super init])) {
        soundEngine = theSoundEngine;
        loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START];
        freedBuffers = [[NSMutableArray alloc] init];
        nextBufferId = 0;
    }
    return self;
}

-(void) dealloc {
    [loadedBuffers release];
    [freedBuffers release];
    [super dealloc];
}

-(int) bufferForFile:(NSString*) filePath create:(BOOL) create {

    NSNumber* soundId = (NSNumber*)[loadedBuffers objectForKey:filePath];
    if(soundId == nil)
    {
        if (create) {
            NSNumber* bufferId = nil;
            //First try to get a buffer from the free buffers
            if ([freedBuffers count] > 0) {
                bufferId = [[[freedBuffers lastObject] retain] autorelease];
                [freedBuffers removeLastObject];
                CDLOGINFO(@"Denshion::CDBufferManager reusing buffer id %i",[bufferId intValue]);
            } else {
                bufferId = [[NSNumber alloc] initWithInt:nextBufferId];
                [bufferId autorelease];
                CDLOGINFO(@"Denshion::CDBufferManager generating new buffer id %i",[bufferId intValue]);
                nextBufferId++;
            }

            if ([soundEngine loadBuffer:[bufferId intValue] filePath:filePath]) {
                //File successfully loaded
                CDLOGINFO(@"Denshion::CDBufferManager buffer loaded %@ %@",bufferId,filePath);
                [loadedBuffers setObject:bufferId forKey:filePath];
                return [bufferId intValue];
            } else {
                //File didn't load, put buffer id on free list
                [freedBuffers addObject:bufferId];
                return kCDNoBuffer;
            }
        } else {
            //No matching buffer was found
            return kCDNoBuffer;
        }
    } else {
        return [soundId intValue];
    }
}

-(void) releaseBufferForFile:(NSString *) filePath {
    int bufferId = [self bufferForFile:filePath create:NO];
    if (bufferId != kCDNoBuffer) {
        [soundEngine unloadBuffer:bufferId];
        [loadedBuffers removeObjectForKey:filePath];
        NSNumber *freedBufferId = [[NSNumber alloc] initWithInt:bufferId];
        [freedBufferId autorelease];
        [freedBuffers addObject:freedBufferId];
    }
}
@end


text:
package imj.apps;

import static imj.IMJTools.loadAndTryToCache;
import static imj.database.IMJDatabaseTools.RGB;
import static imj.database.IMJDatabaseTools.checkDatabase;
import static imj.database.IMJDatabaseTools.updateDatabase;
import static java.util.Locale.ENGLISH;
import static multij.tools.Tools.baseName;
import static multij.tools.Tools.usedMemory;

import imj.apps.modules.RegionOfInterest;
import imj.database.BinningQuantizer;
import imj.database.LinearSampler;
import imj.database.PatchDatabase;
import imj.database.Quantizer;
import imj.database.Sample;
import imj.database.Sampler;
import imj.database.SeamGridSegmenter;
import imj.database.Segmenter;
import imj.database.SparseHistogramSampler;
import imj.database.TileSegmenter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import multij.tools.CommandLineArgumentsParser;
import multij.tools.IllegalInstantiationException;
import multij.tools.TicToc;

/**
 * @author codistmonk (creation 2013-04-11)
 */
public final class GenerateSampleDatabase {

	private GenerateSampleDatabase() {
		throw new IllegalInstantiationException();
	}

	/**
	 * @param commandLineArguments
	 * <br>Must not be null
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static final void main(final String[] commandLineArguments) throws FileNotFoundException, IOException {
		final Configuration configuration = new Configuration(commandLineArguments);
		final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments);
		final Map<Object, Object> database = new LinkedHashMap<Object, Object>();
		final TicToc timer = new TicToc();
		final String imageId = arguments.get("file", "");
		final int lod = configuration.getLod();
		final PatchDatabase<Sample> sampleDatabase = new PatchDatabase<Sample>(Sample.class);
		final String outPath = arguments.get("out", baseName(imageId) + configuration.getDatabaseSuffix());
		final Quantizer quantizer = new BinningQuantizer();

		System.out.println("Collecting data... " + new Date(timer.tic()));

		quantizer.initialize(loadAndTryToCache(imageId, lod), null, RGB, configuration.getQuantizationLevel());

		updateDatabase(imageId, lod, configuration.newSegmenter(), configuration.getSamplerClass(), RGB, quantizer,
				new HashMap<String, RegionOfInterest>(), sampleDatabase);

		database.put("samples", sampleDatabase);

		System.out.println("Collecting data done" + " time: " + timer.toc() + " memory: " + usedMemory());

		checkDatabase(sampleDatabase);

		System.out.println("Writing data... " + new Date(timer.tic()));

		final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outPath));

		try {
			out.writeObject(database);
		} finally {
			out.close();
		}

		System.out.println("Writing data done" + " time: " + timer.toc() + " memory: " + usedMemory());
	}

	/**
	 * @author codistmonk (creation 2013-06-04)
	 */
	public static final class Configuration {

		private final int tileRowCount;

		private final int tileColumnCount;

		private final int verticalTileStride;

		private final int horizontalTileStride;

		private final int lod;

		private final int quantizationLevel;

		private final String segmenterName;

		private final String descriptorName;

		private final String protosuffix;

		private final String databaseSuffix;

		private final String confusionSuffix;

		private final Class<? extends Sampler> samplerClass;

		private final int maximumGroupSize;

		public Configuration(final String... commandLineArguments) {
			final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments);
			this.tileRowCount = arguments.get("tileHeight", 3)[0];
			this.tileColumnCount = arguments.get("tileWidth", this.tileRowCount)[0];
			this.verticalTileStride = arguments.get("yStep", this.tileRowCount)[0];
			this.horizontalTileStride = arguments.get("xStep", this.verticalTileStride)[0];
			this.lod = arguments.get("lod", 4)[0];
			this.quantizationLevel = arguments.get("q", 0)[0];
			this.segmenterName = arguments.get("segmenter", "tiles").toLowerCase(ENGLISH);
			this.descriptorName = arguments.get("descriptor", "linear").toLowerCase(ENGLISH);
			this.maximumGroupSize = arguments.get("maximumGroupSize", 0)[0];

			String protosuffix =  ".lod" + this.lod + ".q" + this.quantizationLevel + "." + this.segmenterName;

			if ("tiles".equals(this.segmenterName)) {
				protosuffix += "_h" + this.tileRowCount + "w" + this.tileColumnCount + "dy" + this.verticalTileStride + "dx" + this.horizontalTileStride;
			} else if ("seams".equals(this.segmenterName)) {
				protosuffix += this.tileRowCount;
			} else {
				throw new IllegalArgumentException("Invalid segmenter: " + this.segmenterName);
			}

			protosuffix += "." + this.descriptorName;
			this.protosuffix = protosuffix;
			this.databaseSuffix = protosuffix + ".jo";
			this.confusionSuffix = protosuffix + ".mgs" + this.maximumGroupSize + ".jo";

			if ("linear".equals(this.descriptorName)) {
				this.samplerClass = LinearSampler.class;
			} else if ("histogram".equals(this.descriptorName)) {
				this.samplerClass = SparseHistogramSampler.class;
			} else {
				throw new IllegalArgumentException("Invalid descriptor: " + this.descriptorName);
			}
		}

		public final int getTileRowCount() {
			return this.tileRowCount;
		}

		public final int getTileColumnCount() {
			return this.tileColumnCount;
		}

		public final int getVerticalTileStride() {
			return this.verticalTileStride;
		}

		public final int getHorizontalTileStride() {
			return this.horizontalTileStride;
		}

		public final int getLod() {
			return this.lod;
		}

		public final int getQuantizationLevel() {
			return this.quantizationLevel;
		}

		public final String getSegmenterName() {
			return this.segmenterName;
		}

		public final String getDescriptorName() {
			return this.descriptorName;
		}

		public final int getMaximumGroupSize() {
			return this.maximumGroupSize;
		}

		public final String getProtosuffix() {
			return this.protosuffix;
		}

		public final String getDatabaseSuffix() {
			return this.databaseSuffix;
		}

		public final String getConfusionSuffix() {
			return this.confusionSuffix;
		}

		public final Segmenter newSegmenter() {
			if ("tiles".equals(this.segmenterName)) {
				return new TileSegmenter(this.tileRowCount, this.tileColumnCount, this.verticalTileStride, this.horizontalTileStride);
			} else if ("seams".equals(this.segmenterName)) {
				return new SeamGridSegmenter(this.tileRowCount);
			} else {
				throw new IllegalArgumentException("Invalid segmenter: " + this.segmenterName);
			}
		}

		public final Class<? extends Sampler> getSamplerClass() {
			return this.samplerClass;
		}

	}

}


text: see https://github.com/ssugiyama/walklog/


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

<TITLE>
ValueBinder (Hibernate JavaDocs)
</TITLE>

<META NAME="date" CONTENT="2013-10-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.hibernate.type.descriptor

Interface ValueBinder<X>

All Known Implementing Classes:
BasicBinder

public interface ValueBinder<X>

Contract for binding values to a PreparedStatement.

Method Summary

 void
bind(PreparedStatement st,
     X value,
     int index,
     WrapperOptions options)

          Bind a value to a prepared statement.

Method Detail

bind

void bind(PreparedStatement st,
          X value,
          int index,
          WrapperOptions options)
          throws SQLException

Bind a value to a prepared statement.

Parameters:
st - The prepared statement to which to bind the value.
value - The value to bind.
index - The position at which to bind the value within the prepared statement
options - The options.

Throws:

SQLException - Indicates a JDBC error occurred.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2001-2013 Red Hat, Inc.  All Rights Reserved.


text:
namespace Glipho.OAuth.Providers.Database
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// The Consumers database interface.
    /// </summary>
    public interface IConsumers
    {
        /// <summary>
        /// Create a new consumer.
        /// </summary>
        /// <param name="newConsumer">The <see cref="Consumer"/> to create.</param>
        /// <returns>The created <see cref="Consumer"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown if a parameter is null.</exception>
        /// <exception cref="Glipho.OAuth.OAuthException">Thrown if an error occurs while executing the requested command.</exception>
        Consumer Create(Consumer newConsumer);

        /// <summary>
        /// Retrieve a consumer from the database.
        /// </summary>
        /// <param name="id">The identifier of the consumer to retrieve.</param>
        /// <returns>The <see cref="Consumer"/> if found; else null.</returns>
        /// <exception cref="ArgumentException">Thrown if a parameter is not valid.</exception>
        /// <exception cref="Glipho.OAuth.OAuthException">Thrown if an error occurs while executing the requested command.</exception>
        Consumer Get(string id);

        /// <summary>
        /// List all consumers by name.
        /// </summary>
        /// <param name="offset">The amount to offset the results by. Minimum of 0.</param>
        /// <param name="limit">The maximum number of results to return. Maximum of 100.</param>
        /// <returns>A list of <see cref="Consumer"/> within the specified range.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if a parameter is outside of a permitted range.</exception>
        /// <exception cref="Glipho.OAuth.OAuthException">Thrown if an error occurs while executing the requested command.</exception>
        /// <remarks>
        /// <para>
        /// If there are no results with the given range, an empty list should be returned.
        /// </para>
        /// </remarks>
        IList<Consumer> List(int offset, int limit);
    }
}


text:
"""py.test for modeleditor"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from itertools import product
import os
import warnings

import pytest
from six import StringIO
from six import string_types

from eppy import modeleditor
from eppy.bunch_subclass import Bunch
from eppy.iddcurrent import iddcurrent
from eppy.modeleditor import IDF
from eppy.pytest_helpers import almostequal
import eppy.snippet as snippet

iddsnippet = iddcurrent.iddtxt
idfsnippet = snippet.idfsnippet

# idffhandle = StringIO(idfsnippet)
# iddfhandle = StringIO(iddsnippet)
# bunchdt, data, commdct, gdict = idfreader.idfreader(idffhandle, iddfhandle, None)

# idd is read only once in this test
# if it has already been read from some other test, it will continue with
# the old reading
iddfhandle = StringIO(iddcurrent.iddtxt)
if IDF.getiddname() == None:
    IDF.setiddname(iddfhandle)

def test_poptrailing():
    """py.test for poptrailing"""
    tdata = (
        (
            [1, 2, 3, '', 56, '', '', '', ''],
            [1, 2, 3, '', 56]
        ),  # lst, popped
        (
            [1, 2, 3, '', 56],
            [1, 2, 3, '', 56]
        ),  # lst, popped
        (
            [1, 2, 3, 56],
            [1, 2, 3, 56]
        ),  # lst, popped
    )
    for before, after in iter(tdata):
        assert modeleditor.poptrailing(before) == after

def test_extendlist():
    """py.test for extendlist"""
    tdata = (
        ([1, 2, 3], 2, 0, [1, 2, 3]),  # lst, i, value, nlst
        ([1, 2, 3], 3, 0, [1, 2, 3, 0]),  # lst, i, value, nlst
        ([1, 2, 3], 5, 0, [1, 2, 3, 0, 0, 0]),  # lst, i, value, nlst
        ([1, 2, 3], 7, 0, [1, 2, 3, 0, 0, 0, 0, 0]),  # lst, i, value, nlst
    )
    for lst, i, value, nlst in tdata:
        modeleditor.extendlist(lst, i, value=value)
        assert lst == nlst

def test_namebunch():
    """py.test for namebunch"""
    thedata = (
        (
            Bunch(dict(Name="", a=5)),
            "yay", "yay"
        ),  # abunch, aname, thename
        (
            Bunch(dict(Name=None, a=5)),
            "yay", None
        ),  # abunch, aname, thename
    )
    for abunch, aname, thename in thedata:
        result = modeleditor.namebunch(abunch, aname)
        assert result.Name == thename

def test_getnamedargs():
    """py.test for getnamedargs"""
    result = dict(a=1, b=2, c=3)
    assert result == modeleditor.getnamedargs(a=1, b=2, c=3)
    assert result == modeleditor.getnamedargs(dict(a=1, b=2, c=3))
    assert result == modeleditor.getnamedargs(dict(a=1, b=2), c=3)
    assert result == modeleditor.getnamedargs(dict(a=1), c=3, b=2)

def test_getrefnames():
    """py.test for getrefnames"""
    tdata = (
        (
            'ZONE',
            [
                'ZoneNames', 'OutFaceEnvNames', 'ZoneAndZoneListNames',
                'AirflowNetworkNodeAndZoneNames'
            ]
        ),  # objkey, therefs
        (
            'FluidProperties:Name'.upper(),
            ['FluidNames', 'FluidAndGlycolNames']
        ),  # objkey, therefs
        ('Building'.upper(), []),  # objkey, therefs
    )
    for objkey, therefs in tdata:
        fhandle = StringIO("")
        idf = IDF(fhandle)
        result = modeleditor.getrefnames(idf, objkey)
        assert result == therefs

def test_getallobjlists():
    """py.test for getallobjlists"""
    tdata = (
        (
            'TransformerNames',
            [
                (
                    'ElectricLoadCenter:Distribution'.upper(),
                    'TransformerNames',
                    [10, ]
                ),
            ],
        ),  # refname, objlists
    )
    for refname, objlists in tdata:
        fhandle = StringIO("")
        idf = IDF(fhandle)
        result = modeleditor.getallobjlists(idf, refname)
        assert result == objlists

def test_rename():
    """py.test for rename"""
    idftxt = """Material,
      G01a 19mm gypsum board,  !- Name
      MediumSmooth,            !- Roughness
      0.019,                   !- Thickness {m}
      0.16,                    !- Conductivity {W/m-K}
      800,                     !- Density {kg/m3}
      1090;                    !- Specific Heat {J/kg-K}

      Construction,
        Interior Wall,           !- Name
        G01a 19mm gypsum board,  !- Outside Layer
        F04 Wall air space resistance,  !- Layer 2
        G01a 19mm gypsum board;  !- Layer 3

      Construction,
        Other Wall,           !- Name
        G01a 19mm gypsum board,  !- Outside Layer
        G01a 19mm gypsum board,  !- Layer 2
        G01a 19mm gypsum board;  !- Layer 3

    """
    ridftxt = """Material,
      peanut butter,  !- Name
      MediumSmooth,            !- Roughness
      0.019,                   !- Thickness {m}
      0.16,                    !- Conductivity {W/m-K}
      800,                     !- Density {kg/m3}
      1090;                    !- Specific Heat {J/kg-K}

      Construction,
        Interior Wall,           !- Name
        peanut butter,  !- Outside Layer
        F04 Wall air space resistance,  !- Layer 2
        peanut butter;  !- Layer 3

      Construction,
        Other Wall,           !- Name
        peanut butter,  !- Outside Layer
        peanut butter,  !- Layer 2
        peanut butter;  !- Layer 3

    """
    fhandle = StringIO(idftxt)
    idf = IDF(fhandle)
    result = modeleditor.rename(
        idf,
        'Material'.upper(),
        'G01a 19mm gypsum board', 'peanut butter')
    assert result.Name == 'peanut butter'
    assert idf.idfobjects['CONSTRUCTION'][0].Outside_Layer == 'peanut butter'
    assert idf.idfobjects['CONSTRUCTION'][0].Layer_3 == 'peanut butter'

def test_zonearea_zonevolume():
    """py.test for zonearea and zonevolume"""
    idftxt = """Zone, 473222, 0.0, 0.0, 0.0, 0.0, , 1;
        BuildingSurface:Detailed, F7289B, Floor, Exterior Floor, 473222,
        Ground, ,
        NoSun, NoWind, , 4, 2.23, 2.56, 0.0, 2.23, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
        2.56, 0.0;  BuildingSurface:Detailed, F3659B, Wall, Exterior Wall,
        473222, Outdoors, , SunExposed, WindExposed, , 4, 2.23, 2.56, 1.49,
        2.23, 2.56, 0.0, 0.0, 2.56, 0.0, 0.0, 2.56, 1.49;
        BuildingSurface:Detailed, 46C6C9, Wall, Exterior Wall, 473222,
        Outdoors, , SunExposed, WindExposed, , 4, 2.23, 0.0, 1.49, 2.23,
        0.0, 0.0, 2.23, 1.02548139464, 0.0, 2.23, 1.02548139464, 1.49;
        BuildingSurface:Detailed, 4287DD, Wall, Exterior Wall, 473222,
        Outdoors, , SunExposed, WindExposed, , 4, 0.0, 2.56, 1.49, 0.0,
        2.56, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.49;
        BuildingSurface:Detailed, 570C2E, Wall, Exterior Wall, 473222,
        Outdoors, , SunExposed, WindExposed, , 4, 0.0, 0.0, 1.49, 0.0, 0.0,
        0.0, 2.23, 0.0, 0.0, 2.23, 0.0, 1.49;  BuildingSurface:Detailed,
        BAEA99, Roof, Exterior Roof, 473222, Outdoors, , SunExposed,
        WindExposed, , 4, 0.0, 2.56, 1.49, 0.0, 0.0, 1.49, 2.23, 0.0, 1.49,
        2.23, 2.56, 1.49;  BuildingSurface:Detailed, C879FE, Floor,
        Exterior Floor, 473222, Ground, , NoSun, NoWind, , 4, 3.22,
        2.52548139464, 0.0, 3.22, 1.02548139464, 0.0, 2.23,
        1.02548139464, 0.0, 2.23, 2.52548139464, 0.0;
        BuildingSurface:Detailed, 25B601, Wall, Exterior Wall, 473222,
        Outdoors, , SunExposed, WindExposed, , 4, 2.23,
        1.02548139464, 1.49, 2.23, 1.02548139464, 0.0, 2.23, 2.52548139464,
        0.0, 2.23, 2.52548139464, 1.49;  BuildingSurface:Detailed, F5EADC,
        Wall, Exterior Wall, 473222, Outdoors, , SunExposed, WindExposed, ,
        4, 2.23, 1.02548139464, 1.49, 2.23, 1.02548139464, 0.0, 3.22,
        1.02548139464, 0.0, 3.22, 1.02548139464, 1.49;
        BuildingSurface:Detailed, D0AABE, Wall, Exterior Wall, 473222,
        Outdoors, , SunExposed, WindExposed, , 4, 3.22, 1.02548139464,
        1.49, 3.22, 1.02548139464, 0.0, 3.22, 2.52548139464, 0.0, 3.22,
        2.52548139464, 1.49;  BuildingSurface:Detailed, B0EA02, Wall,
        Exterior Wall, 473222, Outdoors, , SunExposed, WindExposed, ,
        4, 3.22, 2.52548139464, 1.49, 3.22, 2.52548139464, 0.0, 2.23,
        2.52548139464, 0.0, 2.23, 2.52548139464, 1.49;
        BuildingSurface:Detailed, E6DF3B, Roof, Exterior Roof, 473222,
        Outdoors, , SunExposed, WindExposed, , 4, 2.23, 2.52548139464, 1.49,
        2.23, 1.02548139464, 1.49, 3.22, 1.02548139464, 1.49, 3.22,
        2.52548139464, 1.49;  BuildingSurface:Detailed, 4F8681, Wall,
        Exterior Wall, 473222, Outdoors, , SunExposed, WindExposed, , 4,
        2.23, 2.52548139464, 1.49, 2.23, 2.52548139464, 0.0, 2.23, 2.56,
        0.0, 2.23, 2.56, 1.49;  """
    idf = IDF(StringIO(idftxt))
    result = modeleditor.zonearea(idf, '473222')
    assert almostequal(result, 7.1938)
    result = modeleditor.zonearea_floor(idf, '473222')
    assert almostequal(result, 7.1938)
    result = modeleditor.zonearea_roofceiling(idf, '473222')
    assert almostequal(result, 7.1938)
    result = modeleditor.zone_floor2roofheight(idf, '473222')
    assert almostequal(result, 1.49)
    result = modeleditor.zoneheight(idf, '473222')
    assert almostequal(result, 1.49)
    result = modeleditor.zone_floor2roofheight(idf, '473222')
    assert almostequal(result, 1.49)
    result = modeleditor.zonevolume(idf, '473222')
    assert almostequal(result, 10.718762)
    # remove floor
    zone = idf.getobject('ZONE', '473222')
    surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()]
    zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name]
    floors = [s for s in zone_surfs if s.Surface_Type.upper() == 'FLOOR']
    for floor in floors:
        idf.removeidfobject(floor)
    result = modeleditor.zonearea_floor(idf, '473222')
    assert almostequal(result, 0)
    result = modeleditor.zonearea_roofceiling(idf, '473222')
    assert almostequal(result, 7.1938)
    result = modeleditor.zonearea(idf, '473222')
    assert almostequal(result, 7.1938)
    result = modeleditor.zoneheight(idf, '473222')
    assert almostequal(result, 1.49)
    result = modeleditor.zonevolume(idf, '473222')
    assert almostequal(result, 10.718762)
    # reload idf and remove roof/ceiling
    idf = IDF(StringIO(idftxt))
    zone = idf.getobject('ZONE', '473222')
    surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()]
    zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name]
    roofs = [s for s in zone_surfs if s.Surface_Type.upper() == 'ROOF']
    ceilings = [s for s in zone_surfs if s.Surface_Type.upper() == 'CEILING']
    topsurfaces = roofs + ceilings
    for surf in topsurfaces:
        idf.removeidfobject(surf)
    result = modeleditor.zonearea_roofceiling(idf, '473222')
    assert almostequal(result, 0)
    result = modeleditor.zonearea(idf, '473222')
    assert almostequal(result, 7.1938)
    result = modeleditor.zoneheight(idf, '473222')
    assert almostequal(result, 1.49)
    result = modeleditor.zonevolume(idf, '473222')
    assert almostequal(result, 10.718762)

def test_new():
    """py.test for IDF.new()"""
    idf = IDF()
    idf.new()
    # assert idf.idfobjects['building'.upper()] == Idf_MSequence()
    assert idf.idfobjects['building'.upper()].list1 == []
    assert idf.idfobjects['building'.upper()].list2 == []

def test_newidfobject():
    """py.test for newidfobject"""
    # make a blank idf
    # make a function for this and then continue.
    idf = IDF()
    idf.new()
    objtype = 'material:airgap'.upper()
    obj = idf.newidfobject(objtype, Name='Argon')
    obj = idf.newidfobject(objtype, Name='Krypton')
    obj = idf.newidfobject(objtype, Name='Xenon')
    assert idf.model.dt[objtype] == [['MATERIAL:AIRGAP', 'Argon'],
                                     ['MATERIAL:AIRGAP', 'Krypton'],
                                     ['MATERIAL:AIRGAP', 'Xenon'],
                                     ]
    # remove an object
    idf.popidfobject(objtype, 1)
    assert idf.model.dt[objtype] == [['MATERIAL:AIRGAP', 'Argon'],
                                     ['MATERIAL:AIRGAP', 'Xenon'],
                                     ]
    lastobject = idf.idfobjects[objtype][-1]
    idf.removeidfobject(lastobject)
    assert idf.model.dt[objtype] == [['MATERIAL:AIRGAP', 'Argon'], ]
    # copyidfobject
    onlyobject = idf.idfobjects[objtype][0]
    idf.copyidfobject(onlyobject)

    assert idf.model.dt[objtype] == [['MATERIAL:AIRGAP', 'Argon'],
                                     ['MATERIAL:AIRGAP', 'Argon'],
                                     ]
    # test some functions
    objtype = 'FENESTRATIONSURFACE:DETAILED'
    obj = idf.newidfobject(objtype, Name='A Wall')
    assert obj.coords == []
    assert obj.fieldvalues[1] == 'A Wall'

    # test defaultvalues=True and defaultvalues=False
    sim_deftrue = idf.newidfobject('SimulationControl'.upper(), defaultvalues=True)
    assert sim_deftrue.Do_Zone_Sizing_Calculation == 'No'
    sim_deffalse = idf.newidfobject('SimulationControl'.upper(), defaultvalues=False)
    assert sim_deffalse.Do_Zone_Sizing_Calculation == ''

def test_newidfobject_warning():
    """Test that the warning for newidfobject created with `aname` is working.

    Fails if the warning is not issued when `aname` is used, or if the warning
    is issued when `aname` is not used.
    """
    # make a blank idf
    # make a function for this and then continue.
    idf = IDF()
    idf.new()
    objtype = 'material:airgap'.upper()
    # expect warnings here
    with pytest.warns(UserWarning):
        idf.newidfobject(objtype, aname="Krypton")
    with pytest.warns(UserWarning):
        idf.newidfobject(objtype, "Krypton")

    # expect no warnings here - we pass None so as not to trigger the `Failed: DID NOT WARN` message from pytest
    with pytest.warns(None) as captured_warnings:
        idf.newidfobject(objtype, Name="Krypton")
    assert len(captured_warnings) == 0

def test_save():
    """
    Test the IDF.save() function using a filehandle to avoid external effects.
    """
    file_text = "Material,TestMaterial,  !- Name"
    idf = IDF(StringIO(file_text))
    # test save with just a filehandle
    file_handle = StringIO()
    idf.save(file_handle)
    expected = "TestMaterial"
    file_handle.seek(0)
    result = file_handle.read()
    # minimal test that TestMaterial is being written to the file handle
    assert expected in result

def test_save_with_lineendings_and_encodings():
    """
    Test the IDF.save() function with combinations of encodings and line
    endings.

    """
    file_text = "Material,TestMaterial,  !- Name"
    idf = IDF(StringIO(file_text))
    lineendings = ('windows', 'unix', 'default')
    encodings = ('ascii', 'latin-1', 'UTF-8')

    for le, enc in product(lineendings, encodings):
        file_handle = StringIO()
        idf.save(file_handle, encoding=enc, lineendings=le)
        file_handle.seek(0)
        result = file_handle.read().encode(enc)
        if le == 'windows':
            assert b'\r\n' in result
        elif le == 'unix':
            assert b'\r\n' not in result
        elif le == 'default':
            assert os.linesep.encode(enc) in result

def test_saveas():
    """Test the IDF.saveas() function.
    """
    file_text = "Material,TestMaterial,  !- Name"
    idf = IDF(StringIO(file_text))
    idf.idfname = 'test.idf'

    try:
        idf.saveas()  # this should raise an error as no filename is passed
        assert False
    except TypeError:
        pass

    file_handle = StringIO()
    idf.saveas(file_handle)  # save with a filehandle
    expected = "TestMaterial"
    file_handle.seek(0)
    result = file_handle.read()
    assert expected in result

    # test the idfname attribute has been changed
    assert idf.idfname != 'test.idf'

def test_savecopy():
    """Test the IDF.savecopy() function.
    """
    file_text = "Material,TestMaterial,  !- Name"
    idf = IDF(StringIO(file_text))
    idf.idfname = 'test.idf'

    try:
        idf.savecopy()  # this should raise an error as no filename is passed
        assert False
    except TypeError:
        pass

    file_handle = StringIO()
    idf.savecopy(file_handle)  # save a copy with a different filename
    expected = "TestMaterial"
    file_handle.seek(0)
    result = file_handle.read()
    assert expected in result

    # test the idfname attribute has not been changed
    assert idf.idfname == 'test.idf'

def test_initread():
    """Test for IDF.initread() with filename in unicode and as python str.
    """
    # setup
    idf = IDF()
    idf.initreadtxt(idfsnippet)
    idf.saveas('tmp.idf')

    # test fname as unicode
    fname = 'tmp.idf'
    assert isinstance(fname, string_types)
    idf = IDF()
    idf.initread(fname)
    assert idf.getobject('BUILDING', 'Building')

    # test fname as str
    fname = str('tmp.idf')
    assert isinstance(fname, string_types)
    idf = IDF()
    idf.initread(fname)
    assert idf.getobject('BUILDING', 'Building')

    # test that a nonexistent file raises an IOError
    fname = "notarealfilename.notreal"
    idf = IDF()
    try:
        idf.initread(fname)
        assert False  # shouldn't reach here
    except IOError:
        pass

    # teardown
    os.remove('tmp.idf')

def test_initreadtxt():
    """Test for IDF.initreadtxt().
    """
    idftxt = """
        Material,
          G01a 19mm gypsum board,  !- Name
          MediumSmooth,            !- Roughness
          0.019,                   !- Thickness {m}
          0.16,                    !- Conductivity {W/m-K}
          800,                     !- Density {kg/m3}
          1090;                    !- Specific Heat {J/kg-K}

        Construction,
          Interior Wall,           !- Name
          G01a 19mm gypsum board,  !- Outside Layer
          F04 Wall air space resistance,  !- Layer 2
          G01a 19mm gypsum board;  !- Layer 3
        """
    idf = IDF()
    idf.initreadtxt(idftxt)
    assert idf.getobject('MATERIAL', 'G01a 19mm gypsum board')

def test_idfstr():
    """Test all outputtype options in IDF.idfstr().
    """
    idf = IDF()
    idf.initreadtxt(idfsnippet)
    assert idf.outputtype == 'standard'  # start with the default
    original = idf.idfstr()
    assert "!-" in original  # has comment
    assert "\n" in original  # has line break
    assert "\n\n" in original  # has empty line

    idf.outputtype = 'standard'
    s = idf.idfstr()
    assert "!-" in s  # has comment
    assert "\n" in s  # has line break
    assert "\n\n" in s  # has empty line
    assert s == original  # is unchanged

    idf.outputtype = 'nocomment'
    s = idf.idfstr()
    assert "!-" not in s  # has no comments
    assert "\n" in s  # has line break
    assert "\n\n" in s  # has empty line
    assert s != original  # is changed

    idf.outputtype = 'nocomment1'
    s = idf.idfstr()
    assert "!-" not in s  # has no comments
    assert "\n" in s  # has line break
    assert "\n\n" in s  # has empty lines
    assert s != original  # is changed

    idf.outputtype = 'nocomment2'
    s = idf.idfstr()
    assert "!-" not in s  # has no comments
    assert "\n" in s  # has line break
    assert "\n\n" not in s  # has no empty lines
    assert s != original  # is changed

    idf.outputtype = 'compressed'
    s = idf.idfstr()
    assert "!-" not in s  # has no comments
    assert "\n" not in s  # has no line breaks
    assert "\n\n" not in s  # has no empty lines
    assert s != original  # is changed

def test_refname2key():
    """py.test for refname2key"""
    tdata = (
        (
            'TransformerNames',
            ['ElectricLoadCenter:Distribution'.upper(), ],
        ),  # refname, key
        (
            'AllCurves',
            [u'PUMP:VARIABLESPEED',
            u'PUMP:CONSTANTSPEED', u'BOILER:HOTWATER',
            u'ENERGYMANAGEMENTSYSTEM:CURVEORTABLEINDEXVARIABLE'],
        ),  # refname, key
    )
    for refname, key in tdata:
        fhandle = StringIO("")
        idf = IDF(fhandle)
        result = modeleditor.refname2key(idf, refname)
        assert result == key

def test_getiddgroupdict():
    """py.test for IDF.getiddgroupdict()"""
    data = ((
    {
        None: ['Lead Input', 'Simulation Data']
    },
    ),  # gdict,
    )
    for gdict, in data:
        fhandle = StringIO("")
        idf = IDF(fhandle)
        result = idf.getiddgroupdict()
        assert result[None] == gdict[None]

def test_idfinmsequence():
    """py.test for setting of theidf in Idf_MSequence"""
    idftxt = """Version, 6.0;"""
    # theidf set in Idf_MSequence.__init__
    idf = IDF(StringIO(idftxt))
    versions = idf.idfobjects['version'.upper()]
    assert versions.theidf == idf
    assert versions[0].theidf == idf
    # theidf set in Idf_MSequence.insert()
    material = idf.newidfobject('material'.upper())
    assert material.theidf == idf
    # theidf set when you pop an item
    newmaterial = idf.newidfobject('material'.upper())
    materials = idf.idfobjects['material'.upper()]
    material = materials.pop(0)
    assert material.theidf == None
    assert materials[0].theidf == idf

def test_idd_index():
    """py.test to see if idd_index is returned"""
    idftxt = """"""
    idf = IDF(StringIO(idftxt))
    assert idf.idd_index == {}