repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
uw-loci/jar2lib | src/main/resources/project-files/jace/include/jace/JArray.h | 13952 |
#ifndef JACE_JARRAY_H
#define JACE_JARRAY_H
#ifndef JACE_OS_DEP_H
#include "jace/os_dep.h"
#endif
#ifndef JACE_NAMESPACE_H
#include "jace/namespace.h"
#endif
#ifndef JACE_JNI_HELPER_H
#include "jace/JNIHelper.h"
#endif
#ifndef JACE_JCLASS_IMPL_H
#include "jace/JClassImpl.h"
#endif
#ifndef JACE_ELEMENT_PROXY_H
#include "jace/ElementProxy.h"
#endif
#ifndef JACE_JARRAY_HELPER
#include "jace/JArrayHelper.h"
#endif
#ifndef JACE_JNI_EXCEPTION_H
#include "jace/JNIException.h"
#endif
#ifndef JACE_TYPES_JBOOLEAN_H
#include "jace/proxy/types/JBoolean.h"
#endif
#ifndef JACE_TYPES_JBYTE_H
#include "jace/proxy/types/JByte.h"
#endif
#ifndef JACE_TYPES_JCHAR_H
#include "jace/proxy/types/JChar.h"
#endif
#ifndef JACE_TYPES_JDOUBLE_H
#include "jace/proxy/types/JDouble.h"
#endif
#ifndef JACE_TYPES_JFLOAT_H
#include "jace/proxy/types/JFloat.h"
#endif
#ifndef JACE_TYPES_JINT_H
#include "jace/proxy/types/JInt.h"
#endif
#ifndef JACE_TYPES_JLONG_H
#include "jace/proxy/types/JLong.h"
#endif
#ifndef JACE_TYPES_JSHORT_H
#include "jace/proxy/types/JShort.h"
#endif
#include <string>
#include <vector>
#include "jace/BoostWarningOff.h"
#include <boost/thread/mutex.hpp>
#include "jace/BoostWarningOn.h"
BEGIN_NAMESPACE( jace )
/**
* Represents an array of JValues.
*
* A JArray may be constructed with any type that matches
* the JValue interface. JArrays act like any other array.
* For example:
*
* // Creates an empty array of type String of size 10.
* JArray<String> myArray( 10 );
*
* // Sets the 3rd element to the String, "Hello World".
* myArray[ 3 ] = String( "Hello World" );
*
* // Retrieves the String, "Hello World" from the array.
* String hw = myArray[ 3 ];
*
* @author Toby Reyelts
*
*/
template <class ElementType> class JArray : public ::jace::proxy::JObject
{
public:
/**
* Constructs a new JArray from the given JNI array.
*/
JArray( jvalue array ) : JObject( 0 )
{
this->setJavaJniValue( array );
this->length_ = -1;
}
/**
* Constructs a new JArray from the given JNI array.
*/
JArray( jobject array ) : JObject( 0 )
{
this->setJavaJniObject( array );
this->length_ = -1;
}
/**
* Constructs a new JArray from the given JNI array.
*/
JArray( jarray array ) : JObject( 0 )
{
this->setJavaJniObject( array );
this->length_ = -1;
}
/**
* Constructs a new JArray of the given size.
*/
JArray( int size ) : JObject( 0 )
{
jobject localRef = ::jace::JArrayHelper::newArray( size, ElementType::staticGetJavaJniClass() );
this->setJavaJniObject( localRef );
JNIEnv* env = ::jace::helper::attach();
::jace::helper::deleteLocalRef( env, localRef );
length_ = size;
}
/**
* Creates a new JArray from a vector of a convertible type, T.
*/
template <class T> JArray( const std::vector<T>& values ) : JObject( 0 )
{
#ifdef NO_IMPLICIT_TYPENAME
#define TYPENAME typename
#else
#define TYPENAME
#endif
jobjectArray localArray = ::jace::JArrayHelper::newArray( values.size(), ElementType::staticGetJavaJniClass() );
this->setJavaJniObject( localArray );
int i = 0;
JNIEnv* env = ::jace::helper::attach();
for ( TYPENAME std::vector<T>::const_iterator it = values.begin(); it != values.end(); ++it, ++i )
{
env->SetObjectArrayElement( localArray, i, ElementType( *it ).getJavaJniObject() );
::jace::helper::catchAndThrow();
}
length_ = values.size();
::jace::helper::deleteLocalRef( env, localArray );
}
JArray( const JArray& array ) : JObject( 0 )
{
this->setJavaJniObject( array.getJavaJniObject() );
this->length_ = array.length_;
}
/**
* Destroys this JArray.
*/
~JArray() throw ()
{}
/**
* Retrieves the length of the array.
*
*/
::jace::proxy::types::JInt length() const
{
#ifdef JACE_CHECK_NULLS
if ( ! this->getJavaJniObject() )
throw ::jace::JNIException( "[JArray::length] Can not retrieve the length of a null array." );
#endif
if ( length_ == -1 )
length_ = ::jace::JArrayHelper::getLength( this->getJavaJniObject() );
return length_;
}
/**
* Retrieves the element at the given index of the array.
*
* @throw ArrayIndexOutOfBoundsException if the index
* is outside of the range of the array.
*
* @internal This method needs to return a 'proxy ElementType' that, if assigned to,
* automatically pins and depins that single element in the array.
*/
ElementProxy<ElementType> operator[]( const int& index )
{
#ifdef JACE_CHECK_NULLS
if ( ! this->getJavaJniObject() )
throw ::jace::JNIException( "[JArray::operator[]] Can not dereference a null array." );
#endif
#ifdef JACE_CHECK_ARRAYS
if ( index >= length() )
throw ::jace::JNIException( "[JArray::operator[]] invalid array index." );
#endif
jvalue localElementRef = ::jace::JArrayHelper::getElement( this->getJavaJniObject(), index );
ElementProxy<ElementType> element( this->getJavaJniArray(), localElementRef, index );
JNIEnv* env = ::jace::helper::attach();
::jace::helper::deleteLocalRef( env, localElementRef.l );
return element;
}
/**
* An overloaded version of operator[] that works for const
* instances of JArray.
*/
const ElementProxy<ElementType> operator[]( const int& index ) const
{
#ifdef JACE_CHECK_NULLS
if ( ! this->getJavaJniObject() )
throw ::jace::JNIException( "[JArray::operator[]] Can not dereference a null array." );
#endif
#ifdef JACE_CHECK_ARRAYS
if ( index >= length() )
throw ::jace::JNIException( "[JArray::operator[]] invalid array index." );
#endif
jvalue localElementRef = ::jace::JArrayHelper::getElement( this->getJavaJniObject(), index );
ElementProxy<ElementType> element( this->getJavaJniArray(), localElementRef, index );
JNIEnv* env = ::jace::helper::attach();
::jace::helper::deleteLocalRef( env, localElementRef.l );
return element;
}
/**
* Returns the JClass for this instance.
*
* @throw JNIException if an error occurs while trying to retrieve the class.
*/
virtual const ::jace::JClass& getJavaJniClass() const throw ( ::jace::JNIException )
{
return JArray<ElementType>::staticGetJavaJniClass();
}
/**
* Returns the JClass for this class.
*
* @throw JNIException if an error occurs while trying to retrieve the class.
*/
static const ::jace::JClass& staticGetJavaJniClass() throw ( JNIException )
{
static boost::shared_ptr<JClassImpl> result;
boost::mutex::scoped_lock lock(javaClassMutex);
if (result == 0)
{
const std::string nameAsType = "[" + ElementType::staticGetJavaJniClass().getNameAsType();
// Aparently there is a bug in the JNI docs and arrays require the L...; around objects
const std::string name = nameAsType;
result = boost::shared_ptr<JClassImpl>(new JClassImpl(name, nameAsType));
}
return *result;
}
/**
* Returns the JNI jarray handle for this array.
*/
jarray getJavaJniArray() const
{
return static_cast<jarray>( this->getJavaJniObject() );
}
/**
* Returns the JNI jarray handle for this array as a non-const handle.
*/
jarray getJavaJniArray()
{
return static_cast<jarray>( this->getJavaJniObject() );
}
/**
* An Iterator class for use with the standard C++ library. For
* example you can use stl::copy() to copy the contents of a JArray:
*
* <code>
* JArray<JBoolean> javaArray = ...;
* jboolean* nativeArray = new jboolean[ javaArray.size() ];
*
* std::copy( myArray.begin(), myArray.end(), nativeArray );
* </code>
*
* Iterator should be preferred to operator[] for non-random
* access of arrays, as it allows Jace to perform smart caching
* against the array accesses.
*
* Note that an Iterator is only good for as long as it's parent
* is alive. Accessing an Iterator after the destruction of the
* parent array causes undefined behavior.
*/
class Iterator : public std::iterator<std::random_access_iterator_tag, ElementType>
{
public:
Iterator( JArray<ElementType>* parent_, int begin_, int end_ ) :
parent( parent_ ),
current( begin_ ),
end( end_ )
{
#ifdef JACE_CHECK_ARRAYS
if ( begin_ < 0 || begin_ > parent->length() ) {
throw ::jace::JNIException( "[JArray::Iterator::Iterator] begin is out of bounds." );
}
if ( ( end_ < begin_ && end_ != -1 ) || end > parent->length() ) {
throw ::jace::JNIException( "[JArray::Iterator::Iterator] end is out of bounds." );
}
#endif
parent->cache( current, end );
}
Iterator( const Iterator& it ) :
parent( it.parent ),
current( it.current ),
end( it.end )
{}
~Iterator()
{
parent->release( current, end );
}
Iterator operator=( const Iterator& it )
{
parent = it.parent;
current = it.current;
end = it.end;
return *this;
}
bool operator==( const Iterator& it )
{
return ( parent == it.parent && current == it.current );
}
bool operator!=( const Iterator& it )
{
return ! ( *this == it );
}
bool operator<( const Iterator& it )
{
return ( parent == it.parent && current < it.current );
}
bool operator<=( const Iterator& it )
{
return ( parent == it.parent && current <= it.current );
}
bool operator>( const Iterator& it )
{
return ( parent == it.parent && current > it.current );
}
bool operator>=( const Iterator& it )
{
return ( parent == it.parent && current >= it.current );
}
// pre
Iterator operator++()
{
#ifdef JACE_CHECK_ARRAYS
if ( current >= parent->length() )
throw ::jace::JNIException( "[JArray::Iterator::operator++] can not advance iterator out of bounds." );
#endif
++current;
return *this;
}
// post
Iterator operator++( int dummy )
{
#ifdef JACE_CHECK_ARRAYS
if ( current >= parent->length() )
throw ::jace::JNIException( "[JArray::Iterator::operator++] can not advance iterator out of bounds." );
#endif
Iterator it( *this );
++current;
return it;
}
Iterator operator+=( int i )
{
#ifdef JACE_CHECK_ARRAYS
if ( current + i > parent->length() )
throw ::jace::JNIException( "[JArray::Iterator::operator+=] can not advance iterator out of bounds." );
#endif
current += i;
return *this;
}
// pre
Iterator operator--()
{
#ifdef JACE_CHECK_ARRAYS
if ( current == 0 )
throw ::jace::JNIException( "[JArray::Iterator::operator--] can not rewind iterator out of bounds." );
#endif
--current;
return *this;
}
// post
Iterator operator--( int dummy )
{
#ifdef JACE_CHECK_ARRAYS
if ( current == 0 )
throw ::jace::JNIException( "[JArray::Iterator::operator--] can not rewind iterator out of bounds." );
#endif
Iterator it( *this );
--current;
return it;
}
Iterator operator-=( int i )
{
#ifdef JACE_CHECK_ARRAYS
if ( current - i < 0 )
throw ::jace::JNIException( "[JArray::Iterator::operator-=] can not rewind iterator out of bounds." );
#endif
current -= i;
return *this;
}
Iterator operator+( int i )
{
#ifdef JACE_CHECK_ARRAYS
if ( current + i > parent->length() )
throw ::jace::JNIException( "[JArray::Iterator::operator+] can not advance iterator out of bounds." );
#endif
Iterator it( *this );
it.current += i;
return it;
}
Iterator operator-( int i )
{
#ifdef JACE_CHECK_ARRAYS
if ( current - i < 0 )
throw ::jace::JNIException( "[JArray::Iterator::operator-] can not rewind iterator out of bounds." );
#endif
Iterator it( *this );
it.current -= i;
return it;
}
operator int()
{
return current;
}
/**
* Returns the element to which the Iterator points.
*/
ElementProxy<ElementType> operator*()
{
#ifdef JACE_CHECK_ARRAYS
if ( current < 0 || current >= parent->length() ) {
throw ::jace::JNIException( "[JArray::Iterator::operator*] can not dereference an out of bounds iterator." );
}
#endif
// Change to use caching in the future
return parent->operator[]( current );
}
private:
JArray<ElementType>* parent;
int current;
int end;
};
/**
* Returns an Iterator to the array at position, <code>start</code>
*
* @param start The position at which to place the iterator.
* @param end The position to which you are likely to iterate to.
* This should be equal to or larger than start, or may be set to -1
* to indicate the end of the array.
*/
Iterator begin( int start = 0, int end = -1 )
{
return Iterator( this, start, end );
}
/**
* Returns an Iterator at one past the end of the array.
* This Iterator should not be dereferenced.
*/
Iterator end()
{
return Iterator( this, length(), length() );
}
protected:
/**
* Creates a new JArray that does not yet refer
* to any java array.
*
* This constructor is provided for subclasses which
* need to do their own initialization.
*
* @param noOp - A dummy argument that signifies that
* this constructor should not do any work.
*
* All subclasses of JArray should provide this constructor
* for their own subclasses.
*/
JACE_API JArray( const NoOp& noOp );
private:
/**
* Disallow operator= for now.
*/
bool operator=( const JArray& array );
/**
* Disallow operator== for now.
*/
bool operator==( const JArray& array );
// Methods for future implementation of caching
void cache( int begin, int end )
{}
void release( int begin, int end )
{}
void setElement( ElementType& element, int index )
{}
friend class Iterator;
// The cached length of the array.
// Mutable, because it's calculation can be deferred.
mutable int length_;
static boost::mutex javaClassMutex;
};
template <class ElementType> boost::mutex JArray<ElementType>::javaClassMutex;
END_NAMESPACE( jace )
/**
* For those (oddball) compilers that need the template specialization
* definitions in the header.
*/
#ifdef PUT_TSDS_IN_HEADER
#include "jace/JArray.tsd"
#else
#include "jace/JArray.tsp"
#endif
#endif // #ifndef JACE_JARRAY_H
| bsd-2-clause |
FRC1296/CheezyDriver2016 | third_party/allwpilib_2016/simulation/JavaGazebo/src/main/java/org/gazebosim/transport/SubscriberCallback.java | 100 | package org.gazebosim.transport;
public interface SubscriberCallback<T> {
void callback(T msg);
}
| bsd-2-clause |
insidegui/FinderSyrahUI | SyrahUI/SyrahTableView.h | 272 | //
// SyrahTableView.h
// SyrahUI
//
// Created by Guilherme Rambo on 17/03/14.
// Copyright (c) 2014 Guilherme Rambo. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface SyrahTableView : NSTableView
@end
@interface SyrahTableRowView : NSTableRowView
@end
| bsd-2-clause |
neopenx/Dragon | Dragon/src/operators/activation/elu_op.cc | 1854 | #include "operators/activation/elu_op.h"
#include "utils/math_functions.h"
#include "utils/op_kernel.h"
namespace dragon {
template <class Context> template <typename T>
void EluOp<Context>::RunWithType() {
auto* Xdata = input(0).template data<T, Context>();
auto* Ydata = output(0)->template mutable_data<T, Context>();
kernel::Elu<T, Context>(output(0)->count(), Xdata, alpha, Ydata);
}
template <class Context>
void EluOp<Context>::RunOnDevice() {
output(0)->ReshapeLike(input(0));
if (input(0).template IsType<float>()) RunWithType<float>();
else LOG(FATAL) << "Unsupported input types.";
}
DEPLOY_CPU(Elu);
#ifdef WITH_CUDA
DEPLOY_CUDA(Elu);
#endif
OPERATOR_SCHEMA(Elu).NumInputs(1).NumOutputs(1).Inplace({ { 0, 0 } });
template <class Context> template <typename T>
void EluGradientOp<Context>::RunWithType() {
auto* Ydata = input(0).template data<T, Context>();
auto* dYdata = input(1).template data<T, Context>();
auto* dXdata = output(0)->template mutable_data<T, Context>();
kernel::EluGrad<T, Context>(output(0)->count(), dYdata, Ydata, alpha, dXdata);
}
template <class Context>
void EluGradientOp<Context>::RunOnDevice() {
output(0)->ReshapeLike(input(0));
if (input(0).template IsType<float>()) RunWithType<float>();
else LOG(FATAL) << "Unsupported input types.";
}
DEPLOY_CPU(EluGradient);
#ifdef WITH_CUDA
DEPLOY_CUDA(EluGradient);
#endif
OPERATOR_SCHEMA(EluGradient).NumInputs(2).NumOutputs(1).Inplace({ { 1, 0 }});
class GetEluGradient final : public GradientMakerBase {
public:
GRADIENT_MAKER_CTOR(GetEluGradient);
vector<OperatorDef> MakeDefs() override {
return SingleDef(def.type() + "Gradient", "",
vector<string> {O(0), GO(0)},
vector<string> {GI(0)});
}
};
REGISTER_GRADIENT(Elu, GetEluGradient);
} // namespace dragon | bsd-2-clause |
romainberger/voxel-painter-core | example/main.js | 604 | var voxelPainter = require('./../')
// Options
var options = {
container: '#container'
}
var painter = voxelPainter(options)
var loopThrough = function(elements, cb) {
[].forEach.call(elements, function(item) {
cb(item)
})
}
// Color selector
var colorSelector = document.querySelectorAll('.color-selector li')
loopThrough(colorSelector, function(color) {
color.addEventListener('click', function() {
painter.setColor(this.getAttribute('data-color'))
loopThrough(colorSelector, function(item) {
item.className = ''
})
this.className = 'selected'
}, false)
})
| bsd-2-clause |
y-iihoshi/ThScoreFileConverter | ThScoreFileConverter/Models/Th105Converter.cs | 4300 | //-----------------------------------------------------------------------
// <copyright file="Th105Converter.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
#pragma warning disable SA1600 // ElementsMustBeDocumented
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using ThScoreFileConverter.Helpers;
using ThScoreFileConverter.Models.Th105;
using ThScoreFileConverter.Properties;
namespace ThScoreFileConverter.Models
{
#if !DEBUG
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812", Justification = "Instantiated by ThConverterFactory.")]
#endif
internal class Th105Converter : ThConverter
{
private AllScoreData? allScoreData;
public override string SupportedVersions { get; } = "1.06a";
protected override bool ReadScoreFile(Stream input)
{
using var decrypted = new MemoryStream();
#if DEBUG
using var decoded = new FileStream("th105decoded.dat", FileMode.Create, FileAccess.ReadWrite);
#else
using var decoded = new MemoryStream();
#endif
if (!Decrypt(input, decrypted))
return false;
decrypted.Seek(0, SeekOrigin.Begin);
if (!Extract(decrypted, decoded))
return false;
decoded.Seek(0, SeekOrigin.Begin);
this.allScoreData = Read(decoded);
return this.allScoreData is not null;
}
protected override IEnumerable<IStringReplaceable> CreateReplacers(
INumberFormatter formatter, bool hideUntriedCards, string outputFilePath)
{
if (this.allScoreData is null)
{
throw new InvalidDataException(
Utils.Format(Resources.InvalidOperationExceptionMustBeInvokedAfter, nameof(this.ReadScoreFile)));
}
return new List<IStringReplaceable>
{
new CareerReplacer(this.allScoreData.ClearData, formatter),
new CardReplacer(this.allScoreData.ClearData, hideUntriedCards),
new CollectRateReplacer(this.allScoreData.ClearData, formatter),
new CardForDeckReplacer(this.allScoreData.SystemCards, this.allScoreData.ClearData, formatter, hideUntriedCards),
};
}
private static bool Decrypt(Stream input, Stream output)
{
var size = (int)input.Length;
var inData = new byte[size];
var outData = new byte[size];
_ = input.Seek(0, SeekOrigin.Begin);
_ = input.Read(inData, 0, size);
for (var index = 0; index < size; index++)
outData[index] = (byte)((index * 7) ^ inData[size - index - 1]);
_ = output.Seek(0, SeekOrigin.Begin);
output.Write(outData, 0, size);
// See section 2.2 of RFC 1950
return (outData[0] == 0x78) && (outData[1] == 0x9C);
}
private static bool Extract(Stream input, Stream output)
{
var extracted = new byte[0x80000];
var extractedSize = 0;
// Skip the header bytes of a zlib stream
_ = input.Seek(2, SeekOrigin.Begin);
using (var deflate = new DeflateStream(input, CompressionMode.Decompress, true))
extractedSize = deflate.Read(extracted, 0, extracted.Length);
_ = output.Seek(0, SeekOrigin.Begin);
output.Write(extracted, 0, extractedSize);
return true;
}
private static AllScoreData? Read(Stream input)
{
using var reader = new BinaryReader(input, EncodingHelper.UTF8NoBOM, true);
var allScoreData = new AllScoreData();
try
{
allScoreData.ReadFrom(reader);
}
catch (EndOfStreamException)
{
}
if (allScoreData.ClearData.Count == EnumHelper<Chara>.NumValues)
return allScoreData;
else
return null;
}
}
}
| bsd-2-clause |
mkusz/invoke | invoke/env.py | 4077 | """
Environment variable configuration loading class.
Using a class here doesn't really model anything but makes state passing (in a
situation requiring it) more convenient.
This module is currently considered private/an implementation detail and should
not be included in the Sphinx API documentation.
"""
import os
from .util import six
from .exceptions import UncastableEnvVar, AmbiguousEnvVar
from .util import debug
class Environment(object):
def __init__(self, config, prefix):
self._config = config
self._prefix = prefix
self.data = {} # Accumulator
def load(self):
"""
Return a nested dict containing values from `os.environ`.
Specifically, values whose keys map to already-known configuration
settings, allowing us to perform basic typecasting.
See :ref:`env-vars` for details.
"""
# Obtain allowed env var -> existing value map
env_vars = self._crawl(key_path=[], env_vars={})
m = "Scanning for env vars according to prefix: {!r}, mapping: {!r}"
debug(m.format(self._prefix, env_vars))
# Check for actual env var (honoring prefix) and try to set
for env_var, key_path in six.iteritems(env_vars):
real_var = (self._prefix or "") + env_var
if real_var in os.environ:
self._path_set(key_path, os.environ[real_var])
debug("Obtained env var config: {!r}".format(self.data))
return self.data
def _crawl(self, key_path, env_vars):
"""
Examine config at location ``key_path`` & return potential env vars.
Uses ``env_vars`` dict to determine if a conflict exists, and raises an
exception if so. This dict is of the following form::
{
'EXPECTED_ENV_VAR_HERE': ['actual', 'nested', 'key_path'],
...
}
Returns another dictionary of new keypairs as per above.
"""
new_vars = {}
obj = self._path_get(key_path)
# Sub-dict -> recurse
if (
hasattr(obj, 'keys')
and callable(obj.keys)
and hasattr(obj, '__getitem__')
):
for key in obj.keys():
merged_vars = dict(env_vars, **new_vars)
merged_path = key_path + [key]
crawled = self._crawl(merged_path, merged_vars)
# Handle conflicts
for key in crawled:
if key in new_vars:
err = "Found >1 source for {}"
raise AmbiguousEnvVar(err.format(key))
# Merge and continue
new_vars.update(crawled)
# Other -> is leaf, no recursion
else:
new_vars[self._to_env_var(key_path)] = key_path
return new_vars
def _to_env_var(self, key_path):
return '_'.join(key_path).upper()
def _path_get(self, key_path):
# Gets are from self._config because that's what determines valid env
# vars and/or values for typecasting.
obj = self._config
for key in key_path:
obj = obj[key]
return obj
def _path_set(self, key_path, value):
# Sets are to self.data since that's what we are presenting to the
# outer config object and debugging.
obj = self.data
for key in key_path[:-1]:
if key not in obj:
obj[key] = {}
obj = obj[key]
old = self._path_get(key_path)
new_ = self._cast(old, value)
obj[key_path[-1]] = new_
def _cast(self, old, new_):
if isinstance(old, bool):
return new_ not in ('0', '')
elif isinstance(old, six.string_types):
return new_
elif old is None:
return new_
elif isinstance(old, (list, tuple)):
err = "Can't adapt an environment string into a {}!"
err = err.format(type(old))
raise UncastableEnvVar(err)
else:
return old.__class__(new_)
| bsd-2-clause |
insideo/randomcoder-taglibs | src/main/java/org/randomcoder/taglibs/url/AddParamTag.java | 3000 | package org.randomcoder.taglibs.url;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Tag class which adds a parameter to a URL.
*
* <pre>
* Copyright (c) 2006, Craig Condit. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* </pre>
*/
public class AddParamTag extends TagSupport {
private static final long serialVersionUID = -1726710757304026189L;
private String name;
private String value;
/**
* Sets the parameter name.
*
* @param name parameter name
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the parameter value.
*
* @param value parameter value
*/
public void setValue(String value) {
this.value = value;
}
/**
* Release state.
*/
@Override public void release() {
super.release();
cleanup();
}
/**
* Adds the given parameter to the URL.
*
* @return EVAL_PAGE
*/
@Override public int doEndTag() throws JspException {
try {
ModifyTag mtag = (ModifyTag) findAncestorWithClass(this, ModifyTag.class);
if (mtag == null)
throw new JspException("No modify tag parent found");
Map<String, List<String>> params = mtag.getParams();
List<String> values = params.get(name);
if (values == null) {
values = new ArrayList<String>();
params.put(name, values);
}
values.add(value);
return EVAL_PAGE;
} finally {
cleanup();
}
}
private void cleanup() {
name = null;
value = null;
}
}
| bsd-2-clause |
ninchat/ninchat-go | ninchatapi/params.go | 513 | package ninchatapi
// AppendStrings duplicates the source slice while unwrapping the elements.
func AppendStrings(target []string, source []interface{}) []string {
if source != nil {
if target == nil || cap(target) < len(target)+len(source) {
t := make([]string, len(target), len(target)+len(source))
copy(t, target)
target = t
}
for _, x := range source {
y, _ := x.(string)
target = append(target, y)
}
}
return target
}
func intPointer(x float64) *int {
y := int(x)
return &y
}
| bsd-2-clause |
wolfv/SilverFlask | silverflask/mixins/PolymorphicMixin.py | 850 | #
# Polymorphic Mixins
#
from silverflask import db
from sqlalchemy.ext.declarative import declared_attr
from silverflask.helper import classproperty
class PolymorphicMixin(object):
type = db.Column(db.String(50))
@declared_attr
def __mapper_args__(cls):
if hasattr(cls, '__versioned_draft_class__'):
# Use same identities as draft class
ident = cls.__versioned_draft_class__.__mapper_args__["polymorphic_identity"]
else:
ident = cls.__tablename__
d = {
'polymorphic_identity': ident,
}
# this is a base object, therefore we are not
# redefining the column on which it is polymorphic
if hasattr(cls.__table__.columns, 'id') and not cls.__table__.columns.id.foreign_keys:
d['polymorphic_on'] = 'type'
return d
| bsd-2-clause |
jonathanventura/multi-camera-motion | include/multi-camera-motion/approx_relpose_axial.h | 430 | #ifndef APPROX_RELPOSE_AXIAL_H
#define APPROX_RELPOSE_AXIAL_H
#include <Eigen/Core>
#include <vector>
void
approx_relpose_axial
(
const Eigen::Matrix<double,6,6> &w1,
const Eigen::Matrix<double,6,6> &w2,
const Eigen::Matrix<double,6,6> &w3,
const Eigen::Matrix<double,6,6> &w4,
const Eigen::Matrix<double,6,6> &w5,
const Eigen::Matrix<double,6,6> &w6,
std::vector<Eigen::Vector3d> &rsolns
);
#endif
| bsd-2-clause |
dreamsxin/ultimatepp | uppsrc/Core/Xmlize.h | 8759 | class XmlIO;
template <class T>
void XmlAttrLoad(T& var, const String& text)
{
var.XmlAttrLoad(text);
}
template <class T>
String XmlAttrStore(const T& var)
{
return var.XmlAttrStore();
}
class XmlIO {
XmlNode& node;
bool loading;
Value userdata;
public:
bool IsLoading() const { return loading; }
bool IsStoring() const { return !loading; }
XmlNode& Node() { return node; }
const XmlNode& Node() const { return node; }
XmlNode *operator->() { return &node; }
String GetAttr(const char *id) { return node.Attr(id); }
void SetAttr(const char *id, const String& val) { node.SetAttr(id, val); }
template <class T> XmlIO operator()(const char *tag, T& var);
template <class T> XmlIO operator()(const char *tag, const char *itemtag, T& var);
template <class T> XmlIO Attr(const char *id, T& var) {
if(IsLoading())
XmlAttrLoad(var, node.Attr(id));
else
node.SetAttr(id, XmlAttrStore(var));
return *this;
}
template <class T> XmlIO Attr(const char *id, T& var, T def) {
if(IsLoading())
if(IsNull(node.Attr(id)))
var = def;
else
XmlAttrLoad(var, node.Attr(id));
else
if(var != def)
node.SetAttr(id, XmlAttrStore(var));
return *this;
}
XmlIO At(int i) { XmlIO m(node.At(i), IsLoading(), userdata); return m; }
XmlIO Add() { XmlIO m(node.Add(), IsLoading(), userdata); return m; }
XmlIO Add(const char *id) { XmlIO m(node.Add(id), IsLoading(), userdata); return m; }
XmlIO GetAdd(const char *id) { XmlIO m(node.GetAdd(id), IsLoading(), userdata); return m; }
void SetUserData(const Value& v) { userdata = v; }
Value GetUserData() const { return userdata; }
XmlIO(XmlNode& xml, bool loading, const Value& userdata) : node(xml), loading(loading), userdata(userdata) {}
XmlIO(XmlNode& xml, bool loading) : node(xml), loading(loading) {}
XmlIO(XmlIO xml, const char *tag) : node(xml.node.GetAdd(tag)), loading(xml.loading), userdata(xml.userdata) {}
};
template <class T>
void Xmlize(XmlIO& xml, T& var)
{
var.Xmlize(xml);
}
template <class T>
void Xmlize(XmlIO& xml, const char* itemtag, T& var)
{
var.Xmlize(xml, itemtag);
}
template <class T> XmlIO XmlIO::operator()(const char *tag, T& var) {
XmlIO n(*this, tag);
Xmlize(n, var);
return *this;
}
template <class T> XmlIO XmlIO::operator()(const char *tag, const char *itemtag, T& var) {
XmlIO n(*this, tag);
Xmlize(n, itemtag, var);
return *this;
}
template<> inline void XmlAttrLoad(String& var, const String& text) { var = text; }
template<> inline String XmlAttrStore(const String& var) { return var; }
template<> void XmlAttrLoad(WString& var, const String& text);
template<> String XmlAttrStore(const WString& var);
template<> void XmlAttrLoad(int& var, const String& text);
template<> String XmlAttrStore(const int& var);
template<> void XmlAttrLoad(dword& var, const String& text);
template<> String XmlAttrStore(const dword& var);
template<> void XmlAttrLoad(double& var, const String& text);
template<> String XmlAttrStore(const double& var);
template<> void XmlAttrLoad(bool& var, const String& text);
template<> String XmlAttrStore(const bool& var);
template <> void XmlAttrLoad(int16& var, const String& text);
template <> String XmlAttrStore(const int16& var);
template <> void XmlAttrLoad(int64& var, const String& text);
template <> String XmlAttrStore(const int64& var);
template <> void XmlAttrLoad(byte& var, const String& text);
template <> String XmlAttrStore(const byte& var);
template <> void XmlAttrLoad(Date& var, const String& text);
template <> String XmlAttrStore(const Date& var);
template <> void XmlAttrLoad(Time& var, const String& text);
template <> String XmlAttrStore(const Time& var);
template<> void Xmlize(XmlIO& xml, String& var);
template<> void Xmlize(XmlIO& xml, WString& var);
template<> void Xmlize(XmlIO& xml, int& var);
template<> void Xmlize(XmlIO& xml, dword& var);
template<> void Xmlize(XmlIO& xml, double& var);
template<> void Xmlize(XmlIO& xml, bool& var);
template<> void Xmlize(XmlIO& xml, Date& var);
template<> void Xmlize(XmlIO& xml, Time& var);
template<> void Xmlize(XmlIO& xml, int16& var);
template<> void Xmlize(XmlIO& xml, int64& var);
template<> void Xmlize(XmlIO& xml, byte& var);
void XmlizeLangAttr(XmlIO& xml, int& lang, const char *id = "lang");
void XmlizeLang(XmlIO& xml, const char *tag, int& lang, const char *id = "id");
template<class T>
void XmlizeContainer(XmlIO& xml, const char *tag, T& data)
{
if(xml.IsStoring())
for(int i = 0; i < data.GetCount(); i++) {
XmlIO io = xml.Add(tag);
Xmlize(io, data[i]);
}
else {
data.Clear();
for(int i = 0; i < xml->GetCount(); i++)
if(xml->Node(i).IsTag(tag)) {
XmlIO io = xml.At(i);
Xmlize(io, data.Add());
}
}
}
template<class T>
void XmlizeStore(XmlIO& xml, const T& data)
{
ASSERT(xml.IsStoring());
Xmlize(xml, const_cast<T&>(data));
}
template<class K, class V, class T>
void XmlizeMap(XmlIO& xml, const char *keytag, const char *valuetag, T& data)
{
if(xml.IsStoring()) {
for(int i = 0; i < data.GetCount(); i++)
if(!data.IsUnlinked(i)) {
XmlIO k = xml.Add(keytag);
XmlizeStore(k, data.GetKey(i));
XmlIO v = xml.Add(valuetag);
XmlizeStore(v, data[i]);
}
}
else {
data.Clear();
int i = 0;
while(i < xml->GetCount() - 1 && xml->Node(i).IsTag(keytag) && xml->Node(i + 1).IsTag(valuetag)) {
K key;
XmlIO k = xml.At(i++);
Xmlize(k, key);
XmlIO v = xml.At(i++);
Xmlize(v, data.Add(key));
}
}
}
template<class K, class T>
void XmlizeIndex(XmlIO& xml, const char *keytag, T& data)
{
if(xml.IsStoring()) {
for(int i = 0; i < data.GetCount(); i++)
if(!data.IsUnlinked(i)) {
//XmlizeStore(xml.Add(keytag), data.GetKey(i)); //FIXME xmlize with hashfn awareness
XmlIO io = xml.Add(keytag);
XmlizeStore(io, data[i]);
}
}
else {
data.Clear();
int i = 0;
//while(i < xml->GetCount() - 1 && xml->Node(i).IsTag(keytag) && xml->Node(i + 1).IsTag(valuetag)) {
while(i < xml->GetCount() && xml->Node(i).IsTag(keytag)) {
//K key;
//Xmlize(xml.At(i++), key); //FIXME dexmlize with hashfn awareness
K k;
XmlIO io = xml.At(i++);
Xmlize(io, k);
data.Add(k);
}
}
}
template <class T>
struct ParamHelper__ {
T& data;
void Invoke(XmlIO xml) {
Xmlize(xml, data);
}
ParamHelper__(T& data) : data(data) {}
};
String StoreAsXML(Callback1<XmlIO> xmlize, const char *name);
bool LoadFromXML(Callback1<XmlIO> xmlize, const String& xml);
bool TryLoadFromXML(Callback1<XmlIO> xmlize, const String& xml);
template <class T>
String StoreAsXML(const T& data, const char *name = NULL)
{
ParamHelper__<T> p(const_cast<T &>(data));
return StoreAsXML(callback(&p, &ParamHelper__<T>::Invoke), name);
}
template <class T>
bool LoadFromXML(T& data, const String& xml)
{
ParamHelper__<T> p(data);
return LoadFromXML(callback(&p, &ParamHelper__<T>::Invoke), xml);
}
template <class T>
bool TryLoadFromXML(T& data, const String& xml)
{
ParamHelper__<T> p(data);
return TryLoadFromXML(callback(&p, &ParamHelper__<T>::Invoke), xml);
}
bool StoreAsXMLFile(Callback1<XmlIO> xmlize, const char *name = NULL, const char *file = NULL);
bool LoadFromXMLFile(Callback1<XmlIO> xmlize, const char *file = NULL);
bool TryLoadFromXMLFile(Callback1<XmlIO> xmlize, const char *file = NULL);
template <class T>
bool StoreAsXMLFile(T& data, const char *name = NULL, const char *file = NULL)
{
ParamHelper__<T> p(data);
return StoreAsXMLFile(callback(&p, &ParamHelper__<T>::Invoke), name, file);
}
template <class T>
bool LoadFromXMLFile(T& data, const char *file = NULL)
{
ParamHelper__<T> p(data);
return LoadFromXMLFile(callback(&p, &ParamHelper__<T>::Invoke), file);
}
template <class T>
bool TryLoadFromXMLFile(T& data, const char *file = NULL)
{
ParamHelper__<T> p(data);
return TryLoadFromXMLFile(callback(&p, &ParamHelper__<T>::Invoke), file);
}
template <class T>
void XmlizeBySerialize(XmlIO& xio, T& x)
{
String h;
if(xio.IsStoring())
h = HexString(StoreAsString(x));
xio.Attr("data", h);
if(xio.IsLoading())
try {
LoadFromString(x, ScanHexString(h));
}
catch(LoadingError) {
throw XmlError("xmlize by serialize error");
}
}
void StoreJsonValue(XmlIO& xio, const Value& v);
Value LoadJsonValue(const XmlNode& n);
template <class T>
void XmlizeByJsonize(XmlIO& xio, T& x)
{
if(xio.IsStoring())
StoreJsonValue(xio, StoreAsJsonValue(x));
else {
try {
LoadFromJsonValue(x, LoadJsonValue(xio.Node()));
}
catch(JsonizeError e) {
throw XmlError("xmlize by jsonize error: " + e);
}
}
}
| bsd-2-clause |
crurik/GrapeFS | Doxygen/latex/class_grape_f_s_1_1_g_l_kernel.tex | 9086 | \hypertarget{class_grape_f_s_1_1_g_l_kernel}{\section{Grape\-F\-S\-:\-:G\-L\-Kernel Class Reference}
\label{class_grape_f_s_1_1_g_l_kernel}\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
}
The \hyperlink{class_grape_f_s_1_1_g_l_kernel}{G\-L\-Kernel} class supports G\-L\-S\-L code.
{\ttfamily \#include $<$gl\-Kernel.\-h$>$}
Inheritance diagram for Grape\-F\-S\-:\-:G\-L\-Kernel\-:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=4.000000cm]{class_grape_f_s_1_1_g_l_kernel}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{class_grape_f_s_1_1_g_l_kernel_a5d97a05887bb0f1869954f522a5b53a1}{G\-L\-Kernel} (\hyperlink{class_grape_f_s_1_1_directory}{Directory} $\ast$\hyperlink{class_grape_f_s_1_1_object_a4b06ea431ae5c83e39f99c47e2ba756f}{parent}=nullptr)
\item
virtual \hyperlink{class_grape_f_s_1_1_g_l_kernel_a89b0c298888208f08b2adfddd4941bc9}{$\sim$\-G\-L\-Kernel} ()
\item
int \hyperlink{class_grape_f_s_1_1_g_l_kernel_a69ddc289032c8307b3f67f2cf5dd284c}{execute\-Assembly} (\hyperlink{_grape_f_s__config_8h_a4c253e677fc10a5a14881452d413c0e8}{gfs\-\_\-data\-\_\-t} $\ast$$\ast$dest, size\-\_\-t $\ast$$\ast$\hyperlink{class_grape_f_s_1_1_object_a2cd150cc550f45b48b6c9736763a06bb}{size}) override
\end{DoxyCompactItemize}
\subsection*{Protected Member Functions}
\begin{DoxyCompactItemize}
\item
G\-Luint \hyperlink{class_grape_f_s_1_1_g_l_kernel_a4462d3081636cec2cdbe03ca494b5502}{create\-V\-B\-O} ()
\item
bool \hyperlink{class_grape_f_s_1_1_g_l_kernel_afb5108b66df3fce6f2ab119efec03bc8}{is\-Visible} (G\-Lenum type)
\item
const char $\ast$ \hyperlink{class_grape_f_s_1_1_g_l_kernel_a36c6c3e1dee7ec6a2288fd64901ec507}{map\-G\-L\-Type\-Name} (G\-Lenum type)
\item
\hyperlink{namespace_grape_f_s_ae75541399b29ea02f2bbb8be936702a2}{type\-\_\-t} \hyperlink{class_grape_f_s_1_1_g_l_kernel_ab13889efd280b7da23760240eb322237}{map\-G\-L\-Type} (G\-Lenum type)
\item
void \hyperlink{class_grape_f_s_1_1_g_l_kernel_aa6b200037aed7c7d3cd3e1701b72fa96}{parse\-Uniform} (std\-::string \hyperlink{class_grape_f_s_1_1_object_a50a5ab198c5eaa139493a403d8520a2a}{name}, \hyperlink{namespace_grape_f_s_ae75541399b29ea02f2bbb8be936702a2}{type\-\_\-t} type, std\-::map$<$ std\-::string, \hyperlink{class_grape_f_s_1_1_object}{Object} $\ast$ $>$ \&argument\-Mapping)
\item
bool \hyperlink{class_grape_f_s_1_1_g_l_kernel_a7b06a7509d10d7ab1341b426b07e2ab0}{update\-Program} ()
\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}
\subsection{Detailed Description}
The \hyperlink{class_grape_f_s_1_1_g_l_kernel}{G\-L\-Kernel} class supports G\-L\-S\-L code.
The processing code is specified using a single G\-L\-S\-L shader. The vertex and fragment code can be specified by the user. Uniforms from the shader are exported into the filesystem. Textures are used to provide raw data.
Beware\-: The \hyperlink{class_grape_f_s_1_1_g_l_kernel}{G\-L\-Kernel} is currently not thread-\/safe.
\subsection{Constructor \& Destructor Documentation}
\hypertarget{class_grape_f_s_1_1_g_l_kernel_a5d97a05887bb0f1869954f522a5b53a1}{\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}!G\-L\-Kernel@{G\-L\-Kernel}}
\index{G\-L\-Kernel@{G\-L\-Kernel}!GrapeFS::GLKernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
\subsubsection[{G\-L\-Kernel}]{\setlength{\rightskip}{0pt plus 5cm}G\-L\-Kernel\-::\-G\-L\-Kernel (
\begin{DoxyParamCaption}
\item[{{\bf Directory} $\ast$}]{parent = {\ttfamily nullptr}}
\end{DoxyParamCaption}
)}}\label{class_grape_f_s_1_1_g_l_kernel_a5d97a05887bb0f1869954f522a5b53a1}
\hypertarget{class_grape_f_s_1_1_g_l_kernel_a89b0c298888208f08b2adfddd4941bc9}{\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}!$\sim$\-G\-L\-Kernel@{$\sim$\-G\-L\-Kernel}}
\index{$\sim$\-G\-L\-Kernel@{$\sim$\-G\-L\-Kernel}!GrapeFS::GLKernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
\subsubsection[{$\sim$\-G\-L\-Kernel}]{\setlength{\rightskip}{0pt plus 5cm}G\-L\-Kernel\-::$\sim$\-G\-L\-Kernel (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [virtual]}}}\label{class_grape_f_s_1_1_g_l_kernel_a89b0c298888208f08b2adfddd4941bc9}
\subsection{Member Function Documentation}
\hypertarget{class_grape_f_s_1_1_g_l_kernel_a4462d3081636cec2cdbe03ca494b5502}{\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}!create\-V\-B\-O@{create\-V\-B\-O}}
\index{create\-V\-B\-O@{create\-V\-B\-O}!GrapeFS::GLKernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
\subsubsection[{create\-V\-B\-O}]{\setlength{\rightskip}{0pt plus 5cm}G\-Luint G\-L\-Kernel\-::create\-V\-B\-O (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [protected]}}}\label{class_grape_f_s_1_1_g_l_kernel_a4462d3081636cec2cdbe03ca494b5502}
\hypertarget{class_grape_f_s_1_1_g_l_kernel_a69ddc289032c8307b3f67f2cf5dd284c}{\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}!execute\-Assembly@{execute\-Assembly}}
\index{execute\-Assembly@{execute\-Assembly}!GrapeFS::GLKernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
\subsubsection[{execute\-Assembly}]{\setlength{\rightskip}{0pt plus 5cm}int G\-L\-Kernel\-::execute\-Assembly (
\begin{DoxyParamCaption}
\item[{{\bf gfs\-\_\-data\-\_\-t} $\ast$$\ast$}]{dest, }
\item[{size\-\_\-t $\ast$$\ast$}]{size}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [override]}, {\ttfamily [virtual]}}}\label{class_grape_f_s_1_1_g_l_kernel_a69ddc289032c8307b3f67f2cf5dd284c}
\begin{DoxySeeAlso}{See Also}
\hyperlink{class_grape_f_s_1_1_computation_kernel_acb4dea95069ed4b1ac2e483d9d4d0d17}{Computation\-Kernel\-::execute\-Assembly(gfs\-\_\-data\-\_\-t $\ast$$\ast$, size\-\_\-t $\ast$$\ast$)}
\end{DoxySeeAlso}
Implements \hyperlink{class_grape_f_s_1_1_computation_kernel_acb4dea95069ed4b1ac2e483d9d4d0d17}{Grape\-F\-S\-::\-Computation\-Kernel}.
\hypertarget{class_grape_f_s_1_1_g_l_kernel_afb5108b66df3fce6f2ab119efec03bc8}{\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}!is\-Visible@{is\-Visible}}
\index{is\-Visible@{is\-Visible}!GrapeFS::GLKernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
\subsubsection[{is\-Visible}]{\setlength{\rightskip}{0pt plus 5cm}bool G\-L\-Kernel\-::is\-Visible (
\begin{DoxyParamCaption}
\item[{G\-Lenum}]{type}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [protected]}}}\label{class_grape_f_s_1_1_g_l_kernel_afb5108b66df3fce6f2ab119efec03bc8}
\hypertarget{class_grape_f_s_1_1_g_l_kernel_ab13889efd280b7da23760240eb322237}{\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}!map\-G\-L\-Type@{map\-G\-L\-Type}}
\index{map\-G\-L\-Type@{map\-G\-L\-Type}!GrapeFS::GLKernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
\subsubsection[{map\-G\-L\-Type}]{\setlength{\rightskip}{0pt plus 5cm}{\bf type\-\_\-t} G\-L\-Kernel\-::map\-G\-L\-Type (
\begin{DoxyParamCaption}
\item[{G\-Lenum}]{type}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [protected]}}}\label{class_grape_f_s_1_1_g_l_kernel_ab13889efd280b7da23760240eb322237}
\hypertarget{class_grape_f_s_1_1_g_l_kernel_a36c6c3e1dee7ec6a2288fd64901ec507}{\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}!map\-G\-L\-Type\-Name@{map\-G\-L\-Type\-Name}}
\index{map\-G\-L\-Type\-Name@{map\-G\-L\-Type\-Name}!GrapeFS::GLKernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
\subsubsection[{map\-G\-L\-Type\-Name}]{\setlength{\rightskip}{0pt plus 5cm}const char $\ast$ G\-L\-Kernel\-::map\-G\-L\-Type\-Name (
\begin{DoxyParamCaption}
\item[{G\-Lenum}]{type}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [protected]}}}\label{class_grape_f_s_1_1_g_l_kernel_a36c6c3e1dee7ec6a2288fd64901ec507}
\hypertarget{class_grape_f_s_1_1_g_l_kernel_aa6b200037aed7c7d3cd3e1701b72fa96}{\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}!parse\-Uniform@{parse\-Uniform}}
\index{parse\-Uniform@{parse\-Uniform}!GrapeFS::GLKernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
\subsubsection[{parse\-Uniform}]{\setlength{\rightskip}{0pt plus 5cm}void G\-L\-Kernel\-::parse\-Uniform (
\begin{DoxyParamCaption}
\item[{std\-::string}]{name, }
\item[{{\bf type\-\_\-t}}]{type, }
\item[{std\-::map$<$ std\-::string, {\bf Object} $\ast$ $>$ \&}]{argument\-Mapping}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [protected]}}}\label{class_grape_f_s_1_1_g_l_kernel_aa6b200037aed7c7d3cd3e1701b72fa96}
\hypertarget{class_grape_f_s_1_1_g_l_kernel_a7b06a7509d10d7ab1341b426b07e2ab0}{\index{Grape\-F\-S\-::\-G\-L\-Kernel@{Grape\-F\-S\-::\-G\-L\-Kernel}!update\-Program@{update\-Program}}
\index{update\-Program@{update\-Program}!GrapeFS::GLKernel@{Grape\-F\-S\-::\-G\-L\-Kernel}}
\subsubsection[{update\-Program}]{\setlength{\rightskip}{0pt plus 5cm}bool G\-L\-Kernel\-::update\-Program (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [protected]}}}\label{class_grape_f_s_1_1_g_l_kernel_a7b06a7509d10d7ab1341b426b07e2ab0}
The documentation for this class was generated from the following files\-:\begin{DoxyCompactItemize}
\item
Code/\-Grape\-F\-S/\-Kernel/\hyperlink{gl_kernel_8h}{gl\-Kernel.\-h}\item
Code/\-Grape\-F\-S/\-Kernel/\hyperlink{gl_kernel_8cxx}{gl\-Kernel.\-cxx}\end{DoxyCompactItemize}
| bsd-2-clause |
nyaki-HUN/DESIRE | DESIRE-Modules/UI-HorusUI/Externals/horus_ui/libs/binpack/SkylineBinPack.h | 3183 | /** @file SkylineBinPack.h
@author Jukka Jylänki
@brief Implements different bin packer algorithms that use the SKYLINE data structure.
This work is released to Public Domain, do whatever you want with it.
*/
#pragma once
#include <vector>
#include "Rect.h"
#include "GuillotineBinPack.h"
/** Implements bin packing algorithms that use the SKYLINE data structure to store the bin contents. Uses
GuillotineBinPack as the waste map. */
class SkylineBinPack
{
public:
/// Instantiates a bin of size (0,0). Call Init to create a new bin.
SkylineBinPack();
/// Instantiates a bin of the given size.
SkylineBinPack(int binWidth, int binHeight, bool useWasteMap);
/// (Re)initializes the packer to an empty bin of width x height units. Call whenever
/// you need to restart with a new bin.
void Init(int binWidth, int binHeight, bool useWasteMap);
/// Defines the different heuristic rules that can be used to decide how to make the rectangle placements.
enum LevelChoiceHeuristic
{
LevelBottomLeft,
LevelMinWasteFit
};
/// Inserts the given list of rectangles in an offline/batch mode, possibly rotated.
/// @param rects The list of rectangles to insert. This vector will be destroyed in the process.
/// @param dst [out] This list will contain the packed rectangles. The indices will not correspond to that of rects.
/// @param method The rectangle placement rule to use when packing.
void Insert(std::vector<RectSize> &rects, std::vector<Rect> &dst, LevelChoiceHeuristic method);
/// Inserts a single rectangle into the bin, possibly rotated.
Rect Insert(int width, int height, LevelChoiceHeuristic method);
/// Computes the ratio of used surface area to the total bin area.
float Occupancy() const;
private:
int binWidth;
int binHeight;
#ifndef NDEBUG
DisjointRectCollection disjointRects;
#endif
/// Represents a single level (a horizontal line) of the skyline/horizon/envelope.
struct SkylineNode
{
/// The starting x-coordinate (leftmost).
int x;
/// The y-coordinate of the skyline level line.
int y;
/// The line width. The ending coordinate (inclusive) will be x+width-1.
int width;
};
std::vector<SkylineNode> skyLine;
unsigned long usedSurfaceArea;
/// If true, we use the GuillotineBinPack structure to recover wasted areas into a waste map.
bool useWasteMap;
GuillotineBinPack wasteMap;
Rect InsertBottomLeft(int width, int height);
Rect InsertMinWaste(int width, int height);
Rect FindPositionForNewNodeMinWaste(int width, int height, int &bestHeight, int &bestWastedArea, int &bestIndex) const;
Rect FindPositionForNewNodeBottomLeft(int width, int height, int &bestHeight, int &bestWidth, int &bestIndex) const;
bool RectangleFits(int skylineNodeIndex, int width, int height, int &y) const;
bool RectangleFits(int skylineNodeIndex, int width, int height, int &y, int &wastedArea) const;
int ComputeWastedArea(int skylineNodeIndex, int width, int height, int y) const;
void AddWasteMapArea(int skylineNodeIndex, int width, int height, int y);
void AddSkylineLevel(int skylineNodeIndex, const Rect &rect);
/// Merges all skyline nodes that are at the same level.
void MergeSkylines();
};
| bsd-2-clause |
epiqc/ScaffCC | clang/lib/Lex/LiteralSupport.cpp | 66118 | //===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the NumericLiteralParser, CharLiteralParser, and
// StringLiteralParser interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Lex/LiteralSupport.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/Token.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
using namespace clang;
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
switch (kind) {
default: llvm_unreachable("Unknown token type!");
case tok::char_constant:
case tok::string_literal:
case tok::utf8_char_constant:
case tok::utf8_string_literal:
return Target.getCharWidth();
case tok::wide_char_constant:
case tok::wide_string_literal:
return Target.getWCharWidth();
case tok::utf16_char_constant:
case tok::utf16_string_literal:
return Target.getChar16Width();
case tok::utf32_char_constant:
case tok::utf32_string_literal:
return Target.getChar32Width();
}
}
static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
FullSourceLoc TokLoc,
const char *TokBegin,
const char *TokRangeBegin,
const char *TokRangeEnd) {
SourceLocation Begin =
Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
TokLoc.getManager(), Features);
SourceLocation End =
Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
TokLoc.getManager(), Features);
return CharSourceRange::getCharRange(Begin, End);
}
/// Produce a diagnostic highlighting some portion of a literal.
///
/// Emits the diagnostic \p DiagID, highlighting the range of characters from
/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
/// a substring of a spelling buffer for the token beginning at \p TokBegin.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
const LangOptions &Features, FullSourceLoc TokLoc,
const char *TokBegin, const char *TokRangeBegin,
const char *TokRangeEnd, unsigned DiagID) {
SourceLocation Begin =
Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
TokLoc.getManager(), Features);
return Diags->Report(Begin, DiagID) <<
MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
}
/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
/// either a character or a string literal.
static unsigned ProcessCharEscape(const char *ThisTokBegin,
const char *&ThisTokBuf,
const char *ThisTokEnd, bool &HadError,
FullSourceLoc Loc, unsigned CharWidth,
DiagnosticsEngine *Diags,
const LangOptions &Features) {
const char *EscapeBegin = ThisTokBuf;
// Skip the '\' char.
++ThisTokBuf;
// We know that this character can't be off the end of the buffer, because
// that would have been \", which would not have been the end of string.
unsigned ResultChar = *ThisTokBuf++;
switch (ResultChar) {
// These map to themselves.
case '\\': case '\'': case '"': case '?': break;
// These have fixed mappings.
case 'a':
// TODO: K&R: the meaning of '\\a' is different in traditional C
ResultChar = 7;
break;
case 'b':
ResultChar = 8;
break;
case 'e':
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_nonstandard_escape) << "e";
ResultChar = 27;
break;
case 'E':
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_nonstandard_escape) << "E";
ResultChar = 27;
break;
case 'f':
ResultChar = 12;
break;
case 'n':
ResultChar = 10;
break;
case 'r':
ResultChar = 13;
break;
case 't':
ResultChar = 9;
break;
case 'v':
ResultChar = 11;
break;
case 'x': { // Hex escape.
ResultChar = 0;
if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::err_hex_escape_no_digits) << "x";
HadError = true;
break;
}
// Hex escapes are a maximal series of hex digits.
bool Overflow = false;
for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
if (CharVal == -1) break;
// About to shift out a digit?
if (ResultChar & 0xF0000000)
Overflow = true;
ResultChar <<= 4;
ResultChar |= CharVal;
}
// See if any bits will be truncated when evaluated as a character.
if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Overflow = true;
ResultChar &= ~0U >> (32-CharWidth);
}
// Check for overflow.
if (Overflow && Diags) // Too many digits to fit in
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::err_escape_too_large) << 0;
break;
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7': {
// Octal escapes.
--ThisTokBuf;
ResultChar = 0;
// Octal escapes are a series of octal digits with maximum length 3.
// "\0123" is a two digit sequence equal to "\012" "3".
unsigned NumDigits = 0;
do {
ResultChar <<= 3;
ResultChar |= *ThisTokBuf++ - '0';
++NumDigits;
} while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
// Check for overflow. Reject '\777', but not L'\777'.
if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::err_escape_too_large) << 1;
ResultChar &= ~0U >> (32-CharWidth);
}
break;
}
// Otherwise, these are not valid escapes.
case '(': case '{': case '[': case '%':
// GCC accepts these as extensions. We warn about them as such though.
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_nonstandard_escape)
<< std::string(1, ResultChar);
break;
default:
if (!Diags)
break;
if (isPrintable(ResultChar))
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_unknown_escape)
<< std::string(1, ResultChar);
else
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_unknown_escape)
<< "x" + llvm::utohexstr(ResultChar);
break;
}
return ResultChar;
}
static void appendCodePoint(unsigned Codepoint,
llvm::SmallVectorImpl<char> &Str) {
char ResultBuf[4];
char *ResultPtr = ResultBuf;
bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
(void)Res;
assert(Res && "Unexpected conversion failure");
Str.append(ResultBuf, ResultPtr);
}
void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
if (*I != '\\') {
Buf.push_back(*I);
continue;
}
++I;
assert(*I == 'u' || *I == 'U');
unsigned NumHexDigits;
if (*I == 'u')
NumHexDigits = 4;
else
NumHexDigits = 8;
assert(I + NumHexDigits <= E);
uint32_t CodePoint = 0;
for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
unsigned Value = llvm::hexDigitValue(*I);
assert(Value != -1U);
CodePoint <<= 4;
CodePoint += Value;
}
appendCodePoint(CodePoint, Buf);
--I;
}
}
/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
/// return the UTF32.
static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
const char *ThisTokEnd,
uint32_t &UcnVal, unsigned short &UcnLen,
FullSourceLoc Loc, DiagnosticsEngine *Diags,
const LangOptions &Features,
bool in_char_string_literal = false) {
const char *UcnBegin = ThisTokBuf;
// Skip the '\u' char's.
ThisTokBuf += 2;
if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
return false;
}
UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
unsigned short UcnLenSave = UcnLen;
for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
if (CharVal == -1) break;
UcnVal <<= 4;
UcnVal |= CharVal;
}
// If we didn't consume the proper number of digits, there is a problem.
if (UcnLenSave) {
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
diag::err_ucn_escape_incomplete);
return false;
}
// Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
UcnVal > 0x10FFFF) { // maximum legal UTF32 value
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
diag::err_ucn_escape_invalid);
return false;
}
// C++11 allows UCNs that refer to control characters and basic source
// characters inside character and string literals
if (UcnVal < 0xa0 &&
(UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
if (Diags) {
char BasicSCSChar = UcnVal;
if (UcnVal >= 0x20 && UcnVal < 0x7f)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
IsError ? diag::err_ucn_escape_basic_scs :
diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
<< StringRef(&BasicSCSChar, 1);
else
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
IsError ? diag::err_ucn_control_character :
diag::warn_cxx98_compat_literal_ucn_control_character);
}
if (IsError)
return false;
}
if (!Features.CPlusPlus && !Features.C99 && Diags)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
diag::warn_ucn_not_valid_in_c89_literal);
return true;
}
/// MeasureUCNEscape - Determine the number of bytes within the resulting string
/// which this UCN will occupy.
static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
const char *ThisTokEnd, unsigned CharByteWidth,
const LangOptions &Features, bool &HadError) {
// UTF-32: 4 bytes per escape.
if (CharByteWidth == 4)
return 4;
uint32_t UcnVal = 0;
unsigned short UcnLen = 0;
FullSourceLoc Loc;
if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
UcnLen, Loc, nullptr, Features, true)) {
HadError = true;
return 0;
}
// UTF-16: 2 bytes for BMP, 4 bytes otherwise.
if (CharByteWidth == 2)
return UcnVal <= 0xFFFF ? 2 : 4;
// UTF-8.
if (UcnVal < 0x80)
return 1;
if (UcnVal < 0x800)
return 2;
if (UcnVal < 0x10000)
return 3;
return 4;
}
/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
/// StringLiteralParser. When we decide to implement UCN's for identifiers,
/// we will likely rework our support for UCN's.
static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
const char *ThisTokEnd,
char *&ResultBuf, bool &HadError,
FullSourceLoc Loc, unsigned CharByteWidth,
DiagnosticsEngine *Diags,
const LangOptions &Features) {
typedef uint32_t UTF32;
UTF32 UcnVal = 0;
unsigned short UcnLen = 0;
if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
Loc, Diags, Features, true)) {
HadError = true;
return;
}
assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
"only character widths of 1, 2, or 4 bytes supported");
(void)UcnLen;
assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
if (CharByteWidth == 4) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF32 *ResultPtr = reinterpret_cast<llvm::UTF32*>(ResultBuf);
*ResultPtr = UcnVal;
ResultBuf += 4;
return;
}
if (CharByteWidth == 2) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF16 *ResultPtr = reinterpret_cast<llvm::UTF16*>(ResultBuf);
if (UcnVal <= (UTF32)0xFFFF) {
*ResultPtr = UcnVal;
ResultBuf += 2;
return;
}
// Convert to UTF16.
UcnVal -= 0x10000;
*ResultPtr = 0xD800 + (UcnVal >> 10);
*(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
ResultBuf += 4;
return;
}
assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
// Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
// The conversion below was inspired by:
// http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
// First, we determine how many bytes the result will require.
typedef uint8_t UTF8;
unsigned short bytesToWrite = 0;
if (UcnVal < (UTF32)0x80)
bytesToWrite = 1;
else if (UcnVal < (UTF32)0x800)
bytesToWrite = 2;
else if (UcnVal < (UTF32)0x10000)
bytesToWrite = 3;
else
bytesToWrite = 4;
const unsigned byteMask = 0xBF;
const unsigned byteMark = 0x80;
// Once the bits are split out into bytes of UTF8, this is a mask OR-ed
// into the first byte, depending on how many bytes follow.
static const UTF8 firstByteMark[5] = {
0x00, 0x00, 0xC0, 0xE0, 0xF0
};
// Finally, we write the bytes into ResultBuf.
ResultBuf += bytesToWrite;
switch (bytesToWrite) { // note: everything falls through.
case 4:
*--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
LLVM_FALLTHROUGH;
case 3:
*--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
LLVM_FALLTHROUGH;
case 2:
*--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
LLVM_FALLTHROUGH;
case 1:
*--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
}
// Update the buffer.
ResultBuf += bytesToWrite;
}
/// integer-constant: [C99 6.4.4.1]
/// decimal-constant integer-suffix
/// octal-constant integer-suffix
/// hexadecimal-constant integer-suffix
/// binary-literal integer-suffix [GNU, C++1y]
/// user-defined-integer-literal: [C++11 lex.ext]
/// decimal-literal ud-suffix
/// octal-literal ud-suffix
/// hexadecimal-literal ud-suffix
/// binary-literal ud-suffix [GNU, C++1y]
/// decimal-constant:
/// nonzero-digit
/// decimal-constant digit
/// octal-constant:
/// 0
/// octal-constant octal-digit
/// hexadecimal-constant:
/// hexadecimal-prefix hexadecimal-digit
/// hexadecimal-constant hexadecimal-digit
/// hexadecimal-prefix: one of
/// 0x 0X
/// binary-literal:
/// 0b binary-digit
/// 0B binary-digit
/// binary-literal binary-digit
/// integer-suffix:
/// unsigned-suffix [long-suffix]
/// unsigned-suffix [long-long-suffix]
/// long-suffix [unsigned-suffix]
/// long-long-suffix [unsigned-sufix]
/// nonzero-digit:
/// 1 2 3 4 5 6 7 8 9
/// octal-digit:
/// 0 1 2 3 4 5 6 7
/// hexadecimal-digit:
/// 0 1 2 3 4 5 6 7 8 9
/// a b c d e f
/// A B C D E F
/// binary-digit:
/// 0
/// 1
/// unsigned-suffix: one of
/// u U
/// long-suffix: one of
/// l L
/// long-long-suffix: one of
/// ll LL
///
/// floating-constant: [C99 6.4.4.2]
/// TODO: add rules...
///
NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
SourceLocation TokLoc,
Preprocessor &PP)
: PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
// This routine assumes that the range begin/end matches the regex for integer
// and FP constants (specifically, the 'pp-number' regex), and assumes that
// the byte at "*end" is both valid and not part of the regex. Because of
// this, it doesn't have to check for 'overscan' in various places.
assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
s = DigitsBegin = ThisTokBegin;
saw_exponent = false;
saw_period = false;
saw_ud_suffix = false;
saw_fixed_point_suffix = false;
isLong = false;
isUnsigned = false;
isLongLong = false;
isHalf = false;
isFloat = false;
isImaginary = false;
isFloat16 = false;
isFloat128 = false;
MicrosoftInteger = 0;
isFract = false;
isAccum = false;
hadError = false;
if (*s == '0') { // parse radix
ParseNumberStartingWithZero(TokLoc);
if (hadError)
return;
} else { // the first digit is non-zero
radix = 10;
s = SkipDigits(s);
if (s == ThisTokEnd) {
// Done.
} else {
ParseDecimalOrOctalCommon(TokLoc);
if (hadError)
return;
}
}
SuffixBegin = s;
checkSeparator(TokLoc, s, CSK_AfterDigits);
// Initial scan to lookahead for fixed point suffix.
if (PP.getLangOpts().FixedPoint) {
for (const char *c = s; c != ThisTokEnd; ++c) {
if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
saw_fixed_point_suffix = true;
break;
}
}
}
// Parse the suffix. At this point we can classify whether we have an FP or
// integer constant.
bool isFPConstant = isFloatingLiteral();
// Loop over all of the characters of the suffix. If we see something bad,
// we break out of the loop.
for (; s != ThisTokEnd; ++s) {
switch (*s) {
case 'R':
case 'r':
if (!PP.getLangOpts().FixedPoint) break;
if (isFract || isAccum) break;
if (!(saw_period || saw_exponent)) break;
isFract = true;
continue;
case 'K':
case 'k':
if (!PP.getLangOpts().FixedPoint) break;
if (isFract || isAccum) break;
if (!(saw_period || saw_exponent)) break;
isAccum = true;
continue;
case 'h': // FP Suffix for "half".
case 'H':
// OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
if (!(PP.getLangOpts().Half || PP.getLangOpts().FixedPoint)) break;
if (isIntegerLiteral()) break; // Error for integer constant.
if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
isHalf = true;
continue; // Success.
case 'f': // FP Suffix for "float"
case 'F':
if (!isFPConstant) break; // Error for integer constant.
if (isHalf || isFloat || isLong || isFloat128)
break; // HF, FF, LF, QF invalid.
// CUDA host and device may have different _Float16 support, therefore
// allows f16 literals to avoid false alarm.
// ToDo: more precise check for CUDA.
if ((PP.getTargetInfo().hasFloat16Type() || PP.getLangOpts().CUDA) &&
s + 2 < ThisTokEnd && s[1] == '1' && s[2] == '6') {
s += 2; // success, eat up 2 characters.
isFloat16 = true;
continue;
}
isFloat = true;
continue; // Success.
case 'q': // FP Suffix for "__float128"
case 'Q':
if (!isFPConstant) break; // Error for integer constant.
if (isHalf || isFloat || isLong || isFloat128)
break; // HQ, FQ, LQ, QQ invalid.
isFloat128 = true;
continue; // Success.
case 'u':
case 'U':
if (isFPConstant) break; // Error for floating constant.
if (isUnsigned) break; // Cannot be repeated.
isUnsigned = true;
continue; // Success.
case 'l':
case 'L':
if (isLong || isLongLong) break; // Cannot be repeated.
if (isHalf || isFloat || isFloat128) break; // LH, LF, LQ invalid.
// Check for long long. The L's need to be adjacent and the same case.
if (s[1] == s[0]) {
assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
if (isFPConstant) break; // long long invalid for floats.
isLongLong = true;
++s; // Eat both of them.
} else {
isLong = true;
}
continue; // Success.
case 'i':
case 'I':
if (PP.getLangOpts().MicrosoftExt) {
if (isLong || isLongLong || MicrosoftInteger)
break;
if (!isFPConstant) {
// Allow i8, i16, i32, and i64.
switch (s[1]) {
case '8':
s += 2; // i8 suffix
MicrosoftInteger = 8;
break;
case '1':
if (s[2] == '6') {
s += 3; // i16 suffix
MicrosoftInteger = 16;
}
break;
case '3':
if (s[2] == '2') {
s += 3; // i32 suffix
MicrosoftInteger = 32;
}
break;
case '6':
if (s[2] == '4') {
s += 3; // i64 suffix
MicrosoftInteger = 64;
}
break;
default:
break;
}
}
if (MicrosoftInteger) {
assert(s <= ThisTokEnd && "didn't maximally munch?");
break;
}
}
LLVM_FALLTHROUGH;
case 'j':
case 'J':
if (isImaginary) break; // Cannot be repeated.
isImaginary = true;
continue; // Success.
}
// If we reached here, there was an error or a ud-suffix.
break;
}
// "i", "if", and "il" are user-defined suffixes in C++1y.
if (s != ThisTokEnd || isImaginary) {
// FIXME: Don't bother expanding UCNs if !tok.hasUCN().
expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) {
if (!isImaginary) {
// Any suffix pieces we might have parsed are actually part of the
// ud-suffix.
isLong = false;
isUnsigned = false;
isLongLong = false;
isFloat = false;
isFloat16 = false;
isHalf = false;
isImaginary = false;
MicrosoftInteger = 0;
saw_fixed_point_suffix = false;
isFract = false;
isAccum = false;
}
saw_ud_suffix = true;
return;
}
if (s != ThisTokEnd) {
// Report an error if there are any.
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
diag::err_invalid_suffix_constant)
<< StringRef(SuffixBegin, ThisTokEnd - SuffixBegin) << isFPConstant;
hadError = true;
}
}
if (!hadError && saw_fixed_point_suffix) {
assert(isFract || isAccum);
}
}
/// ParseDecimalOrOctalCommon - This method is called for decimal or octal
/// numbers. It issues an error for illegal digits, and handles floating point
/// parsing. If it detects a floating point number, the radix is set to 10.
void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
assert((radix == 8 || radix == 10) && "Unexpected radix");
// If we have a hex digit other than 'e' (which denotes a FP exponent) then
// the code is using an incorrect base.
if (isHexDigit(*s) && *s != 'e' && *s != 'E' &&
!isValidUDSuffix(PP.getLangOpts(), StringRef(s, ThisTokEnd - s))) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 1 : 0);
hadError = true;
return;
}
if (*s == '.') {
checkSeparator(TokLoc, s, CSK_AfterDigits);
s++;
radix = 10;
saw_period = true;
checkSeparator(TokLoc, s, CSK_BeforeDigits);
s = SkipDigits(s); // Skip suffix.
}
if (*s == 'e' || *s == 'E') { // exponent
checkSeparator(TokLoc, s, CSK_AfterDigits);
const char *Exponent = s;
s++;
radix = 10;
saw_exponent = true;
if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
const char *first_non_digit = SkipDigits(s);
if (containsDigits(s, first_non_digit)) {
checkSeparator(TokLoc, s, CSK_BeforeDigits);
s = first_non_digit;
} else {
if (!hadError) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
diag::err_exponent_has_no_digits);
hadError = true;
}
return;
}
}
}
/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
/// suffixes as ud-suffixes, because the diagnostic experience is better if we
/// treat it as an invalid suffix.
bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
StringRef Suffix) {
if (!LangOpts.CPlusPlus11 || Suffix.empty())
return false;
// By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
if (Suffix[0] == '_')
return true;
// In C++11, there are no library suffixes.
if (!LangOpts.CPlusPlus14)
return false;
// In C++14, "s", "h", "min", "ms", "us", and "ns" are used in the library.
// Per tweaked N3660, "il", "i", and "if" are also used in the library.
// In C++2a "d" and "y" are used in the library.
return llvm::StringSwitch<bool>(Suffix)
.Cases("h", "min", "s", true)
.Cases("ms", "us", "ns", true)
.Cases("il", "i", "if", true)
.Cases("d", "y", LangOpts.CPlusPlus2a)
.Default(false);
}
void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
const char *Pos,
CheckSeparatorKind IsAfterDigits) {
if (IsAfterDigits == CSK_AfterDigits) {
if (Pos == ThisTokBegin)
return;
--Pos;
} else if (Pos == ThisTokEnd)
return;
if (isDigitSeparator(*Pos)) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
diag::err_digit_separator_not_between_digits)
<< IsAfterDigits;
hadError = true;
}
}
/// ParseNumberStartingWithZero - This method is called when the first character
/// of the number is found to be a zero. This means it is either an octal
/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
/// a floating point number (01239.123e4). Eat the prefix, determining the
/// radix etc.
void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
assert(s[0] == '0' && "Invalid method call");
s++;
int c1 = s[0];
// Handle a hex number like 0x1234.
if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
s++;
assert(s < ThisTokEnd && "didn't maximally munch?");
radix = 16;
DigitsBegin = s;
s = SkipHexDigits(s);
bool HasSignificandDigits = containsDigits(DigitsBegin, s);
if (s == ThisTokEnd) {
// Done.
} else if (*s == '.') {
s++;
saw_period = true;
const char *floatDigitsBegin = s;
s = SkipHexDigits(s);
if (containsDigits(floatDigitsBegin, s))
HasSignificandDigits = true;
if (HasSignificandDigits)
checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
}
if (!HasSignificandDigits) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
diag::err_hex_constant_requires)
<< PP.getLangOpts().CPlusPlus << 1;
hadError = true;
return;
}
// A binary exponent can appear with or with a '.'. If dotted, the
// binary exponent is required.
if (*s == 'p' || *s == 'P') {
checkSeparator(TokLoc, s, CSK_AfterDigits);
const char *Exponent = s;
s++;
saw_exponent = true;
if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
const char *first_non_digit = SkipDigits(s);
if (!containsDigits(s, first_non_digit)) {
if (!hadError) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
diag::err_exponent_has_no_digits);
hadError = true;
}
return;
}
checkSeparator(TokLoc, s, CSK_BeforeDigits);
s = first_non_digit;
if (!PP.getLangOpts().HexFloats)
PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus
? diag::ext_hex_literal_invalid
: diag::ext_hex_constant_invalid);
else if (PP.getLangOpts().CPlusPlus17)
PP.Diag(TokLoc, diag::warn_cxx17_hex_literal);
} else if (saw_period) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
diag::err_hex_constant_requires)
<< PP.getLangOpts().CPlusPlus << 0;
hadError = true;
}
return;
}
// Handle simple binary numbers 0b01010
if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
// 0b101010 is a C++1y / GCC extension.
PP.Diag(TokLoc,
PP.getLangOpts().CPlusPlus14
? diag::warn_cxx11_compat_binary_literal
: PP.getLangOpts().CPlusPlus
? diag::ext_binary_literal_cxx14
: diag::ext_binary_literal);
++s;
assert(s < ThisTokEnd && "didn't maximally munch?");
radix = 2;
DigitsBegin = s;
s = SkipBinaryDigits(s);
if (s == ThisTokEnd) {
// Done.
} else if (isHexDigit(*s) &&
!isValidUDSuffix(PP.getLangOpts(),
StringRef(s, ThisTokEnd - s))) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
diag::err_invalid_digit) << StringRef(s, 1) << 2;
hadError = true;
}
// Other suffixes will be diagnosed by the caller.
return;
}
// For now, the radix is set to 8. If we discover that we have a
// floating point constant, the radix will change to 10. Octal floating
// point constants are not permitted (only decimal and hexadecimal).
radix = 8;
DigitsBegin = s;
s = SkipOctalDigits(s);
if (s == ThisTokEnd)
return; // Done, simple octal number like 01234
// If we have some other non-octal digit that *is* a decimal digit, see if
// this is part of a floating point number like 094.123 or 09e1.
if (isDigit(*s)) {
const char *EndDecimal = SkipDigits(s);
if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
s = EndDecimal;
radix = 10;
}
}
ParseDecimalOrOctalCommon(TokLoc);
}
static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
switch (Radix) {
case 2:
return NumDigits <= 64;
case 8:
return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
case 10:
return NumDigits <= 19; // floor(log10(2^64))
case 16:
return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
default:
llvm_unreachable("impossible Radix");
}
}
/// GetIntegerValue - Convert this numeric literal value to an APInt that
/// matches Val's input width. If there is an overflow, set Val to the low bits
/// of the result and return true. Otherwise, return false.
bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
// Fast path: Compute a conservative bound on the maximum number of
// bits per digit in this radix. If we can't possibly overflow a
// uint64 based on that bound then do the simple conversion to
// integer. This avoids the expensive overflow checking below, and
// handles the common cases that matter (small decimal integers and
// hex/octal values which don't overflow).
const unsigned NumDigits = SuffixBegin - DigitsBegin;
if (alwaysFitsInto64Bits(radix, NumDigits)) {
uint64_t N = 0;
for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
if (!isDigitSeparator(*Ptr))
N = N * radix + llvm::hexDigitValue(*Ptr);
// This will truncate the value to Val's input width. Simply check
// for overflow by comparing.
Val = N;
return Val.getZExtValue() != N;
}
Val = 0;
const char *Ptr = DigitsBegin;
llvm::APInt RadixVal(Val.getBitWidth(), radix);
llvm::APInt CharVal(Val.getBitWidth(), 0);
llvm::APInt OldVal = Val;
bool OverflowOccurred = false;
while (Ptr < SuffixBegin) {
if (isDigitSeparator(*Ptr)) {
++Ptr;
continue;
}
unsigned C = llvm::hexDigitValue(*Ptr++);
// If this letter is out of bound for this radix, reject it.
assert(C < radix && "NumericLiteralParser ctor should have rejected this");
CharVal = C;
// Add the digit to the value in the appropriate radix. If adding in digits
// made the value smaller, then this overflowed.
OldVal = Val;
// Multiply by radix, did overflow occur on the multiply?
Val *= RadixVal;
OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
// Add value, did overflow occur on the value?
// (a + b) ult b <=> overflow
Val += CharVal;
OverflowOccurred |= Val.ult(CharVal);
}
return OverflowOccurred;
}
llvm::APFloat::opStatus
NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
using llvm::APFloat;
unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
llvm::SmallString<16> Buffer;
StringRef Str(ThisTokBegin, n);
if (Str.find('\'') != StringRef::npos) {
Buffer.reserve(n);
std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
&isDigitSeparator);
Str = Buffer;
}
auto StatusOrErr =
Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
assert(StatusOrErr && "Invalid floating point representation");
return !errorToBool(StatusOrErr.takeError()) ? *StatusOrErr
: APFloat::opInvalidOp;
}
static inline bool IsExponentPart(char c) {
return c == 'p' || c == 'P' || c == 'e' || c == 'E';
}
bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale) {
assert(radix == 16 || radix == 10);
// Find how many digits are needed to store the whole literal.
unsigned NumDigits = SuffixBegin - DigitsBegin;
if (saw_period) --NumDigits;
// Initial scan of the exponent if it exists
bool ExpOverflowOccurred = false;
bool NegativeExponent = false;
const char *ExponentBegin;
uint64_t Exponent = 0;
int64_t BaseShift = 0;
if (saw_exponent) {
const char *Ptr = DigitsBegin;
while (!IsExponentPart(*Ptr)) ++Ptr;
ExponentBegin = Ptr;
++Ptr;
NegativeExponent = *Ptr == '-';
if (NegativeExponent) ++Ptr;
unsigned NumExpDigits = SuffixBegin - Ptr;
if (alwaysFitsInto64Bits(radix, NumExpDigits)) {
llvm::StringRef ExpStr(Ptr, NumExpDigits);
llvm::APInt ExpInt(/*numBits=*/64, ExpStr, /*radix=*/10);
Exponent = ExpInt.getZExtValue();
} else {
ExpOverflowOccurred = true;
}
if (NegativeExponent) BaseShift -= Exponent;
else BaseShift += Exponent;
}
// Number of bits needed for decimal literal is
// ceil(NumDigits * log2(10)) Integral part
// + Scale Fractional part
// + ceil(Exponent * log2(10)) Exponent
// --------------------------------------------------
// ceil((NumDigits + Exponent) * log2(10)) + Scale
//
// But for simplicity in handling integers, we can round up log2(10) to 4,
// making:
// 4 * (NumDigits + Exponent) + Scale
//
// Number of digits needed for hexadecimal literal is
// 4 * NumDigits Integral part
// + Scale Fractional part
// + Exponent Exponent
// --------------------------------------------------
// (4 * NumDigits) + Scale + Exponent
uint64_t NumBitsNeeded;
if (radix == 10)
NumBitsNeeded = 4 * (NumDigits + Exponent) + Scale;
else
NumBitsNeeded = 4 * NumDigits + Exponent + Scale;
if (NumBitsNeeded > std::numeric_limits<unsigned>::max())
ExpOverflowOccurred = true;
llvm::APInt Val(static_cast<unsigned>(NumBitsNeeded), 0, /*isSigned=*/false);
bool FoundDecimal = false;
int64_t FractBaseShift = 0;
const char *End = saw_exponent ? ExponentBegin : SuffixBegin;
for (const char *Ptr = DigitsBegin; Ptr < End; ++Ptr) {
if (*Ptr == '.') {
FoundDecimal = true;
continue;
}
// Normal reading of an integer
unsigned C = llvm::hexDigitValue(*Ptr);
assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Val *= radix;
Val += C;
if (FoundDecimal)
// Keep track of how much we will need to adjust this value by from the
// number of digits past the radix point.
--FractBaseShift;
}
// For a radix of 16, we will be multiplying by 2 instead of 16.
if (radix == 16) FractBaseShift *= 4;
BaseShift += FractBaseShift;
Val <<= Scale;
uint64_t Base = (radix == 16) ? 2 : 10;
if (BaseShift > 0) {
for (int64_t i = 0; i < BaseShift; ++i) {
Val *= Base;
}
} else if (BaseShift < 0) {
for (int64_t i = BaseShift; i < 0 && !Val.isNullValue(); ++i)
Val = Val.udiv(Base);
}
bool IntOverflowOccurred = false;
auto MaxVal = llvm::APInt::getMaxValue(StoreVal.getBitWidth());
if (Val.getBitWidth() > StoreVal.getBitWidth()) {
IntOverflowOccurred |= Val.ugt(MaxVal.zext(Val.getBitWidth()));
StoreVal = Val.trunc(StoreVal.getBitWidth());
} else if (Val.getBitWidth() < StoreVal.getBitWidth()) {
IntOverflowOccurred |= Val.zext(MaxVal.getBitWidth()).ugt(MaxVal);
StoreVal = Val.zext(StoreVal.getBitWidth());
} else {
StoreVal = Val;
}
return IntOverflowOccurred || ExpOverflowOccurred;
}
/// \verbatim
/// user-defined-character-literal: [C++11 lex.ext]
/// character-literal ud-suffix
/// ud-suffix:
/// identifier
/// character-literal: [C++11 lex.ccon]
/// ' c-char-sequence '
/// u' c-char-sequence '
/// U' c-char-sequence '
/// L' c-char-sequence '
/// u8' c-char-sequence ' [C++1z lex.ccon]
/// c-char-sequence:
/// c-char
/// c-char-sequence c-char
/// c-char:
/// any member of the source character set except the single-quote ',
/// backslash \, or new-line character
/// escape-sequence
/// universal-character-name
/// escape-sequence:
/// simple-escape-sequence
/// octal-escape-sequence
/// hexadecimal-escape-sequence
/// simple-escape-sequence:
/// one of \' \" \? \\ \a \b \f \n \r \t \v
/// octal-escape-sequence:
/// \ octal-digit
/// \ octal-digit octal-digit
/// \ octal-digit octal-digit octal-digit
/// hexadecimal-escape-sequence:
/// \x hexadecimal-digit
/// hexadecimal-escape-sequence hexadecimal-digit
/// universal-character-name: [C++11 lex.charset]
/// \u hex-quad
/// \U hex-quad hex-quad
/// hex-quad:
/// hex-digit hex-digit hex-digit hex-digit
/// \endverbatim
///
CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
SourceLocation Loc, Preprocessor &PP,
tok::TokenKind kind) {
// At this point we know that the character matches the regex "(L|u|U)?'.*'".
HadError = false;
Kind = kind;
const char *TokBegin = begin;
// Skip over wide character determinant.
if (Kind != tok::char_constant)
++begin;
if (Kind == tok::utf8_char_constant)
++begin;
// Skip over the entry quote.
assert(begin[0] == '\'' && "Invalid token lexed");
++begin;
// Remove an optional ud-suffix.
if (end[-1] != '\'') {
const char *UDSuffixEnd = end;
do {
--end;
} while (end[-1] != '\'');
// FIXME: Don't bother with this if !tok.hasUCN().
expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
UDSuffixOffset = end - TokBegin;
}
// Trim the ending quote.
assert(end != begin && "Invalid token lexed");
--end;
// FIXME: The "Value" is an uint64_t so we can handle char literals of
// up to 64-bits.
// FIXME: This extensively assumes that 'char' is 8-bits.
assert(PP.getTargetInfo().getCharWidth() == 8 &&
"Assumes char is 8 bits");
assert(PP.getTargetInfo().getIntWidth() <= 64 &&
(PP.getTargetInfo().getIntWidth() & 7) == 0 &&
"Assumes sizeof(int) on target is <= 64 and a multiple of char");
assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
"Assumes sizeof(wchar) on target is <= 64");
SmallVector<uint32_t, 4> codepoint_buffer;
codepoint_buffer.resize(end - begin);
uint32_t *buffer_begin = &codepoint_buffer.front();
uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
// Unicode escapes representing characters that cannot be correctly
// represented in a single code unit are disallowed in character literals
// by this implementation.
uint32_t largest_character_for_kind;
if (tok::wide_char_constant == Kind) {
largest_character_for_kind =
0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
} else if (tok::utf8_char_constant == Kind) {
largest_character_for_kind = 0x7F;
} else if (tok::utf16_char_constant == Kind) {
largest_character_for_kind = 0xFFFF;
} else if (tok::utf32_char_constant == Kind) {
largest_character_for_kind = 0x10FFFF;
} else {
largest_character_for_kind = 0x7Fu;
}
while (begin != end) {
// Is this a span of non-escape characters?
if (begin[0] != '\\') {
char const *start = begin;
do {
++begin;
} while (begin != end && *begin != '\\');
char const *tmp_in_start = start;
uint32_t *tmp_out_start = buffer_begin;
llvm::ConversionResult res =
llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start),
reinterpret_cast<llvm::UTF8 const *>(begin),
&buffer_begin, buffer_end, llvm::strictConversion);
if (res != llvm::conversionOK) {
// If we see bad encoding for unprefixed character literals, warn and
// simply copy the byte values, for compatibility with gcc and
// older versions of clang.
bool NoErrorOnBadEncoding = isAscii();
unsigned Msg = diag::err_bad_character_encoding;
if (NoErrorOnBadEncoding)
Msg = diag::warn_bad_character_encoding;
PP.Diag(Loc, Msg);
if (NoErrorOnBadEncoding) {
start = tmp_in_start;
buffer_begin = tmp_out_start;
for (; start != begin; ++start, ++buffer_begin)
*buffer_begin = static_cast<uint8_t>(*start);
} else {
HadError = true;
}
} else {
for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
if (*tmp_out_start > largest_character_for_kind) {
HadError = true;
PP.Diag(Loc, diag::err_character_too_large);
}
}
}
continue;
}
// Is this a Universal Character Name escape?
if (begin[1] == 'u' || begin[1] == 'U') {
unsigned short UcnLen = 0;
if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
FullSourceLoc(Loc, PP.getSourceManager()),
&PP.getDiagnostics(), PP.getLangOpts(), true)) {
HadError = true;
} else if (*buffer_begin > largest_character_for_kind) {
HadError = true;
PP.Diag(Loc, diag::err_character_too_large);
}
++buffer_begin;
continue;
}
unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
uint64_t result =
ProcessCharEscape(TokBegin, begin, end, HadError,
FullSourceLoc(Loc,PP.getSourceManager()),
CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
*buffer_begin++ = result;
}
unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
if (NumCharsSoFar > 1) {
if (isWide())
PP.Diag(Loc, diag::warn_extraneous_char_constant);
else if (isAscii() && NumCharsSoFar == 4)
PP.Diag(Loc, diag::ext_four_char_character_literal);
else if (isAscii())
PP.Diag(Loc, diag::ext_multichar_character_literal);
else
PP.Diag(Loc, diag::err_multichar_utf_character_literal);
IsMultiChar = true;
} else {
IsMultiChar = false;
}
llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
// Narrow character literals act as though their value is concatenated
// in this implementation, but warn on overflow.
bool multi_char_too_long = false;
if (isAscii() && isMultiChar()) {
LitVal = 0;
for (size_t i = 0; i < NumCharsSoFar; ++i) {
// check for enough leading zeros to shift into
multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
LitVal <<= 8;
LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
}
} else if (NumCharsSoFar > 0) {
// otherwise just take the last character
LitVal = buffer_begin[-1];
}
if (!HadError && multi_char_too_long) {
PP.Diag(Loc, diag::warn_char_constant_too_large);
}
// Transfer the value from APInt to uint64_t
Value = LitVal.getZExtValue();
// If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
// if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
// character constants are not sign extended in the this implementation:
// '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
PP.getLangOpts().CharIsSigned)
Value = (signed char)Value;
}
/// \verbatim
/// string-literal: [C++0x lex.string]
/// encoding-prefix " [s-char-sequence] "
/// encoding-prefix R raw-string
/// encoding-prefix:
/// u8
/// u
/// U
/// L
/// s-char-sequence:
/// s-char
/// s-char-sequence s-char
/// s-char:
/// any member of the source character set except the double-quote ",
/// backslash \, or new-line character
/// escape-sequence
/// universal-character-name
/// raw-string:
/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
/// r-char-sequence:
/// r-char
/// r-char-sequence r-char
/// r-char:
/// any member of the source character set, except a right parenthesis )
/// followed by the initial d-char-sequence (which may be empty)
/// followed by a double quote ".
/// d-char-sequence:
/// d-char
/// d-char-sequence d-char
/// d-char:
/// any member of the basic source character set except:
/// space, the left parenthesis (, the right parenthesis ),
/// the backslash \, and the control characters representing horizontal
/// tab, vertical tab, form feed, and newline.
/// escape-sequence: [C++0x lex.ccon]
/// simple-escape-sequence
/// octal-escape-sequence
/// hexadecimal-escape-sequence
/// simple-escape-sequence:
/// one of \' \" \? \\ \a \b \f \n \r \t \v
/// octal-escape-sequence:
/// \ octal-digit
/// \ octal-digit octal-digit
/// \ octal-digit octal-digit octal-digit
/// hexadecimal-escape-sequence:
/// \x hexadecimal-digit
/// hexadecimal-escape-sequence hexadecimal-digit
/// universal-character-name:
/// \u hex-quad
/// \U hex-quad hex-quad
/// hex-quad:
/// hex-digit hex-digit hex-digit hex-digit
/// \endverbatim
///
StringLiteralParser::
StringLiteralParser(ArrayRef<Token> StringToks,
Preprocessor &PP, bool Complain)
: SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr),
MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
init(StringToks);
}
void StringLiteralParser::init(ArrayRef<Token> StringToks){
// The literal token may have come from an invalid source location (e.g. due
// to a PCH error), in which case the token length will be 0.
if (StringToks.empty() || StringToks[0].getLength() < 2)
return DiagnoseLexingError(SourceLocation());
// Scan all of the string portions, remember the max individual token length,
// computing a bound on the concatenated string length, and see whether any
// piece is a wide-string. If any of the string portions is a wide-string
// literal, the result is a wide-string literal [C99 6.4.5p4].
assert(!StringToks.empty() && "expected at least one token");
MaxTokenLength = StringToks[0].getLength();
assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
SizeBound = StringToks[0].getLength()-2; // -2 for "".
Kind = StringToks[0].getKind();
hadError = false;
// Implement Translation Phase #6: concatenation of string literals
/// (C99 5.1.1.2p1). The common case is only one string fragment.
for (unsigned i = 1; i != StringToks.size(); ++i) {
if (StringToks[i].getLength() < 2)
return DiagnoseLexingError(StringToks[i].getLocation());
// The string could be shorter than this if it needs cleaning, but this is a
// reasonable bound, which is all we need.
assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
SizeBound += StringToks[i].getLength()-2; // -2 for "".
// Remember maximum string piece length.
if (StringToks[i].getLength() > MaxTokenLength)
MaxTokenLength = StringToks[i].getLength();
// Remember if we see any wide or utf-8/16/32 strings.
// Also check for illegal concatenations.
if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
if (isAscii()) {
Kind = StringToks[i].getKind();
} else {
if (Diags)
Diags->Report(StringToks[i].getLocation(),
diag::err_unsupported_string_concat);
hadError = true;
}
}
}
// Include space for the null terminator.
++SizeBound;
// TODO: K&R warning: "traditional C rejects string constant concatenation"
// Get the width in bytes of char/wchar_t/char16_t/char32_t
CharByteWidth = getCharWidth(Kind, Target);
assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
CharByteWidth /= 8;
// The output buffer size needs to be large enough to hold wide characters.
// This is a worst-case assumption which basically corresponds to L"" "long".
SizeBound *= CharByteWidth;
// Size the temporary buffer to hold the result string data.
ResultBuf.resize(SizeBound);
// Likewise, but for each string piece.
SmallString<512> TokenBuf;
TokenBuf.resize(MaxTokenLength);
// Loop over all the strings, getting their spelling, and expanding them to
// wide strings as appropriate.
ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Pascal = false;
SourceLocation UDSuffixTokLoc;
for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
const char *ThisTokBuf = &TokenBuf[0];
// Get the spelling of the token, which eliminates trigraphs, etc. We know
// that ThisTokBuf points to a buffer that is big enough for the whole token
// and 'spelled' tokens can only shrink.
bool StringInvalid = false;
unsigned ThisTokLen =
Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
&StringInvalid);
if (StringInvalid)
return DiagnoseLexingError(StringToks[i].getLocation());
const char *ThisTokBegin = ThisTokBuf;
const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
// Remove an optional ud-suffix.
if (ThisTokEnd[-1] != '"') {
const char *UDSuffixEnd = ThisTokEnd;
do {
--ThisTokEnd;
} while (ThisTokEnd[-1] != '"');
StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
if (UDSuffixBuf.empty()) {
if (StringToks[i].hasUCN())
expandUCNs(UDSuffixBuf, UDSuffix);
else
UDSuffixBuf.assign(UDSuffix);
UDSuffixToken = i;
UDSuffixOffset = ThisTokEnd - ThisTokBuf;
UDSuffixTokLoc = StringToks[i].getLocation();
} else {
SmallString<32> ExpandedUDSuffix;
if (StringToks[i].hasUCN()) {
expandUCNs(ExpandedUDSuffix, UDSuffix);
UDSuffix = ExpandedUDSuffix;
}
// C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
// result of a concatenation involving at least one user-defined-string-
// literal, all the participating user-defined-string-literals shall
// have the same ud-suffix.
if (UDSuffixBuf != UDSuffix) {
if (Diags) {
SourceLocation TokLoc = StringToks[i].getLocation();
Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
<< UDSuffixBuf << UDSuffix
<< SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
<< SourceRange(TokLoc, TokLoc);
}
hadError = true;
}
}
}
// Strip the end quote.
--ThisTokEnd;
// TODO: Input character set mapping support.
// Skip marker for wide or unicode strings.
if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
++ThisTokBuf;
// Skip 8 of u8 marker for utf8 strings.
if (ThisTokBuf[0] == '8')
++ThisTokBuf;
}
// Check for raw string
if (ThisTokBuf[0] == 'R') {
ThisTokBuf += 2; // skip R"
const char *Prefix = ThisTokBuf;
while (ThisTokBuf[0] != '(')
++ThisTokBuf;
++ThisTokBuf; // skip '('
// Remove same number of characters from the end
ThisTokEnd -= ThisTokBuf - Prefix;
assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
// C++14 [lex.string]p4: A source-file new-line in a raw string literal
// results in a new-line in the resulting execution string-literal.
StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
while (!RemainingTokenSpan.empty()) {
// Split the string literal on \r\n boundaries.
size_t CRLFPos = RemainingTokenSpan.find("\r\n");
StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
// Copy everything before the \r\n sequence into the string literal.
if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
hadError = true;
// Point into the \n inside the \r\n sequence and operate on the
// remaining portion of the literal.
RemainingTokenSpan = AfterCRLF.substr(1);
}
} else {
if (ThisTokBuf[0] != '"') {
// The file may have come from PCH and then changed after loading the
// PCH; Fail gracefully.
return DiagnoseLexingError(StringToks[i].getLocation());
}
++ThisTokBuf; // skip "
// Check if this is a pascal string
if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
// If the \p sequence is found in the first token, we have a pascal string
// Otherwise, if we already have a pascal string, ignore the first \p
if (i == 0) {
++ThisTokBuf;
Pascal = true;
} else if (Pascal)
ThisTokBuf += 2;
}
while (ThisTokBuf != ThisTokEnd) {
// Is this a span of non-escape characters?
if (ThisTokBuf[0] != '\\') {
const char *InStart = ThisTokBuf;
do {
++ThisTokBuf;
} while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
// Copy the character span over.
if (CopyStringFragment(StringToks[i], ThisTokBegin,
StringRef(InStart, ThisTokBuf - InStart)))
hadError = true;
continue;
}
// Is this a Universal Character Name escape?
if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
ResultPtr, hadError,
FullSourceLoc(StringToks[i].getLocation(), SM),
CharByteWidth, Diags, Features);
continue;
}
// Otherwise, this is a non-UCN escape character. Process it.
unsigned ResultChar =
ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
FullSourceLoc(StringToks[i].getLocation(), SM),
CharByteWidth*8, Diags, Features);
if (CharByteWidth == 4) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr);
*ResultWidePtr = ResultChar;
ResultPtr += 4;
} else if (CharByteWidth == 2) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr);
*ResultWidePtr = ResultChar & 0xFFFF;
ResultPtr += 2;
} else {
assert(CharByteWidth == 1 && "Unexpected char width");
*ResultPtr++ = ResultChar & 0xFF;
}
}
}
}
if (Pascal) {
if (CharByteWidth == 4) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data());
ResultWidePtr[0] = GetNumStringChars() - 1;
} else if (CharByteWidth == 2) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data());
ResultWidePtr[0] = GetNumStringChars() - 1;
} else {
assert(CharByteWidth == 1 && "Unexpected char width");
ResultBuf[0] = GetNumStringChars() - 1;
}
// Verify that pascal strings aren't too large.
if (GetStringLength() > 256) {
if (Diags)
Diags->Report(StringToks.front().getLocation(),
diag::err_pascal_string_too_long)
<< SourceRange(StringToks.front().getLocation(),
StringToks.back().getLocation());
hadError = true;
return;
}
} else if (Diags) {
// Complain if this string literal has too many characters.
unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
if (GetNumStringChars() > MaxChars)
Diags->Report(StringToks.front().getLocation(),
diag::ext_string_too_long)
<< GetNumStringChars() << MaxChars
<< (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
<< SourceRange(StringToks.front().getLocation(),
StringToks.back().getLocation());
}
}
static const char *resyncUTF8(const char *Err, const char *End) {
if (Err == End)
return End;
End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err);
while (++Err != End && (*Err & 0xC0) == 0x80)
;
return Err;
}
/// This function copies from Fragment, which is a sequence of bytes
/// within Tok's contents (which begin at TokBegin) into ResultPtr.
/// Performs widening for multi-byte characters.
bool StringLiteralParser::CopyStringFragment(const Token &Tok,
const char *TokBegin,
StringRef Fragment) {
const llvm::UTF8 *ErrorPtrTmp;
if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
return false;
// If we see bad encoding for unprefixed string literals, warn and
// simply copy the byte values, for compatibility with gcc and older
// versions of clang.
bool NoErrorOnBadEncoding = isAscii();
if (NoErrorOnBadEncoding) {
memcpy(ResultPtr, Fragment.data(), Fragment.size());
ResultPtr += Fragment.size();
}
if (Diags) {
const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
FullSourceLoc SourceLoc(Tok.getLocation(), SM);
const DiagnosticBuilder &Builder =
Diag(Diags, Features, SourceLoc, TokBegin,
ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
: diag::err_bad_string_encoding);
const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
StringRef NextFragment(NextStart, Fragment.end()-NextStart);
// Decode into a dummy buffer.
SmallString<512> Dummy;
Dummy.reserve(Fragment.size() * CharByteWidth);
char *Ptr = Dummy.data();
while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
ErrorPtr, NextStart);
NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
}
}
return !NoErrorOnBadEncoding;
}
void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
hadError = true;
if (Diags)
Diags->Report(Loc, diag::err_lexing_string);
}
/// getOffsetOfStringByte - This function returns the offset of the
/// specified byte of the string data represented by Token. This handles
/// advancing over escape sequences in the string.
unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
unsigned ByteNo) const {
// Get the spelling of the token.
SmallString<32> SpellingBuffer;
SpellingBuffer.resize(Tok.getLength());
bool StringInvalid = false;
const char *SpellingPtr = &SpellingBuffer[0];
unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
&StringInvalid);
if (StringInvalid)
return 0;
const char *SpellingStart = SpellingPtr;
const char *SpellingEnd = SpellingPtr+TokLen;
// Handle UTF-8 strings just like narrow strings.
if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
SpellingPtr += 2;
assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
// For raw string literals, this is easy.
if (SpellingPtr[0] == 'R') {
assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
// Skip 'R"'.
SpellingPtr += 2;
while (*SpellingPtr != '(') {
++SpellingPtr;
assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
}
// Skip '('.
++SpellingPtr;
return SpellingPtr - SpellingStart + ByteNo;
}
// Skip over the leading quote
assert(SpellingPtr[0] == '"' && "Should be a string literal!");
++SpellingPtr;
// Skip over bytes until we find the offset we're looking for.
while (ByteNo) {
assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
// Step over non-escapes simply.
if (*SpellingPtr != '\\') {
++SpellingPtr;
--ByteNo;
continue;
}
// Otherwise, this is an escape character. Advance over it.
bool HadError = false;
if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
const char *EscapePtr = SpellingPtr;
unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1, Features, HadError);
if (Len > ByteNo) {
// ByteNo is somewhere within the escape sequence.
SpellingPtr = EscapePtr;
break;
}
ByteNo -= Len;
} else {
ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
FullSourceLoc(Tok.getLocation(), SM),
CharByteWidth*8, Diags, Features);
--ByteNo;
}
assert(!HadError && "This method isn't valid on erroneous strings");
}
return SpellingPtr-SpellingStart;
}
/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
/// suffixes as ud-suffixes, because the diagnostic experience is better if we
/// treat it as an invalid suffix.
bool StringLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
StringRef Suffix) {
return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) ||
Suffix == "sv";
}
| bsd-2-clause |
ChrisLidbury/CLSmith | scripts/driver0.sh | 178 | set -e
while [ true ]
do
echo .
csmith > test.c;
clang -I${CSMITH_PATH}/runtime -O3 -w test.c -o /dev/null;
gcc -I${CSMITH_PATH}/runtime -O3 -w test.c -o /dev/null;
done
| bsd-2-clause |
sebastienros/jint | Jint.Tests.Test262/test/language/expressions/super/call-spread-obj-mult-spread.js | 1479 | // This file was procedurally generated from the following sources:
// - src/spread/obj-mult-spread.case
// - src/spread/default/super-call.template
/*---
description: Multiple Object Spread operation (SuperCall)
esid: sec-super-keyword-runtime-semantics-evaluation
es6id: 12.3.5.1
features: [object-spread]
flags: [generated]
info: |
SuperCall : super Arguments
1. Let newTarget be GetNewTarget().
2. If newTarget is undefined, throw a ReferenceError exception.
3. Let func be GetSuperConstructor().
4. ReturnIfAbrupt(func).
5. Let argList be ArgumentListEvaluation of Arguments.
[...]
Pending Runtime Semantics: PropertyDefinitionEvaluation
PropertyDefinition:...AssignmentExpression
1. Let exprValue be the result of evaluating AssignmentExpression.
2. Let fromValue be GetValue(exprValue).
3. ReturnIfAbrupt(fromValue).
4. Let excludedNames be a new empty List.
5. Return CopyDataProperties(object, fromValue, excludedNames).
---*/
let o = {a: 2, b: 3};
let o2 = {c: 4, d: 5};
var callCount = 0;
class Test262ParentClass {
constructor(obj) {
assert.sameValue(obj.a, 2);
assert.sameValue(obj.b, 3);
assert.sameValue(obj.c, 4);
assert.sameValue(obj.d, 5);
assert.sameValue(Object.keys(obj).length, 4);
callCount += 1;
}
}
class Test262ChildClass extends Test262ParentClass {
constructor() {
super({...o, ...o2});
}
}
new Test262ChildClass();
assert.sameValue(callCount, 1);
| bsd-2-clause |
lettis/Clustering | README.md | 5804 |
This software package provides extensive tools for robust and stable
clustering of molecular dynamics trajectories.
The essential functions are:
- density-based geometric clustering for microstate generation
- dynamic clustering based on the Most-Probable-Path algorithm (MPP)
- variable dynamic coring for boundary corrections
Additionally, the package includes tools to efficiently filter original
coordinates or order parameters based on a discrete state definition
to identify representative structures and variables of clusters.
<!--
Computationally demanding functions are parallelized in a hybrid model using
OpenMP for SMP parallelization on a single node (multithreading)
and MPI over different cluster nodes. MPI support, however, is optional and
for a modern computer with a high number of fast cores or
even multiple CPUs, OpenMP parallelization is sufficiently fast.
-->
Computationally demanding functions are parallelized using OpenMP.
# Documentation
All options are well documented and may be viewed by 'clustering -h'.
The 'doc' directory includes an extensive tutorial which describes all technical
details in performing a complete clustering run from trajectory to markov state model.
The source code itself is additionally documented via doxygen. Run 'make doc' in
the build directory (see below for installation intructions) to compile the source
code documentation in html.
# Citations
The underlying methods are based on the following articles:
- A. Jain and G. Stock, *Hierarchical folding free energy landscape of HP35
revealed by most probable path clustering*,
J. of Phys. Chem. B, 118, 7750 - 7760, 2014; DOI: 10.1021/jp410398a
- F. Sittel and G. Stock, *Robust Density-Based Clustering to Identify
Metastable Conformational States of Proteins*,
J. Chem. Theory Comput., Article ASAP; DOI: 10.1021/acs.jctc.5b01233
We kindly ask you to cite these articles if you use this software package for
published works.
# Licensing
Copyright (c) 2015, [Florian Sittel](http://www.lettis.net)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Installation
## Requirements
required:
- **BOOST >= 1.49**
- **cmake >= 2.8**
- a **recent** C++ compiler (e.g. GNU g++ >= 4.9, must
support C++11 standard)
optional:
- doxygen (to build the API docs)
<!-- - MPI (for parallelized execution on clusters) -->
## Quick-Start
To quickly get a working (but possibly underperforming) binary
- unpack the code ...
\# tar xfz clustering_VERSION.tar.gz
- create a build folder inside the code directory ...
\# cd clustering_VERSION
\# mkdir build
- change to the build directory ...
\# cd build
- ... and run cmake
\# cmake .. -DCMAKE_INSTALL_PREFIX=/my/installation/path
- then compile and install the package to /my/installation/path (or any other
path you chose above) by invoking
\# make
\# make install
## Optimized Binaries and Custom Build Options
### Vectorization
If you have a modern computer with vectorizing instruction sets (SSE2, SSE4_2,
AVX, ...), set the following **cmake-option**: -DCPU_ACCELERATION=<OPTION>,
where <OPTION> is one of
- SSE2
- SSE4_1
- SSE4_2
- AVX
It is important to select an option that is actually supported by your machine.
Otherwise the program will produce erratic results, crash or not compile at all.
On linux systems, you can check your computer's capabilities with
# cat /proc/cpuinfo
Check in the *flags:*-block, if a certain instruction set is supported.
If it is not listed, it is not supported.
### Native Compilation
To compile the code with '-march=native' option (specific to the GNU compiler),
add '-DNATIVE_COMPILATION=ON' to your cmake-flags.
Using this option, the GNU compiler will automatically use all available
instruction sets for optimal performance (**attention**: you still
need to set the vectorization option above, even if you use this option).
Unfortunately, the resulting binary will most likely run only on the computer
it was compiled on - do **not** use this option if you want
to distribute the binary, e.g. on a cluster.
<!--
### MPI
For MPI support, build your binary with the additional cmake-flag -DDC_USE_MPI=ON.
Invoke the *clustering_mpi* binary in the following way to run on several nodes with local multithreading via OpenMP:
# /usr/bin/mpirun -n N_NODES -bind-to-core -bynode -cpus-per-proc N_THREADS_PER_NODE -report-bindings \
clustering_mpi density -f COORDS_FILE -r RADIUS -p POPS_OUT -d FE_OUT -n N_THREADS_PER_NODE
-->
| bsd-2-clause |
TinnedTuna/speakeasyspeeches | wsgi/run.py | 46 | from speakeasy import app
app.run(debug=True)
| bsd-2-clause |
twpayne/go-geom | flat.go | 9818 | package geom
import "math"
type geom0 struct {
layout Layout
stride int
flatCoords []float64
srid int
}
type geom1 struct {
geom0
}
type geom2 struct {
geom1
ends []int
}
type geom3 struct {
geom1
endss [][]int
}
// Bounds returns the bounds of g.
func (g *geom0) Bounds() *Bounds {
return NewBounds(g.layout).extendFlatCoords(g.flatCoords, 0, len(g.flatCoords), g.stride)
}
// Coords returns all the coordinates in g, i.e. a single coordinate.
func (g *geom0) Coords() Coord {
return inflate0(g.flatCoords, 0, len(g.flatCoords), g.stride)
}
// Empty returns true if g contains no coordinates.
func (g *geom0) Empty() bool {
return len(g.flatCoords) == 0
}
// Ends returns the end indexes of sub-structures of g, i.e. an empty slice.
func (g *geom0) Ends() []int {
return nil
}
// Endss returns the end indexes of sub-sub-structures of g, i.e. an empty
// slice.
func (g *geom0) Endss() [][]int {
return nil
}
// FlatCoords returns the flat coordinates of g.
func (g *geom0) FlatCoords() []float64 {
return g.flatCoords
}
// Layout returns g's layout.
func (g *geom0) Layout() Layout {
return g.layout
}
// NumCoords returns the number of coordinates in g, i.e. 1.
func (g *geom0) NumCoords() int {
return 1
}
// Reserve reserves space in g for n coordinates.
func (g *geom0) Reserve(n int) {
if cap(g.flatCoords) < n*g.stride {
fcs := make([]float64, len(g.flatCoords), n*g.stride)
copy(fcs, g.flatCoords)
g.flatCoords = fcs
}
}
// SRID returns g's SRID.
func (g *geom0) SRID() int {
return g.srid
}
func (g *geom0) setCoords(coords0 []float64) error {
var err error
g.flatCoords, err = deflate0(nil, coords0, g.stride)
return err
}
// Stride returns g's stride.
func (g *geom0) Stride() int {
return g.stride
}
func (g *geom0) verify() error {
if g.stride != g.layout.Stride() {
return errStrideLayoutMismatch
}
if g.stride == 0 {
if len(g.flatCoords) != 0 {
return errNonEmptyFlatCoords
}
return nil
}
if len(g.flatCoords) != g.stride {
return errLengthStrideMismatch
}
return nil
}
// Coord returns the ith coord of g.
func (g *geom1) Coord(i int) Coord {
return g.flatCoords[i*g.stride : (i+1)*g.stride]
}
// Coords unpacks and returns all of g's coordinates.
func (g *geom1) Coords() []Coord {
return inflate1(g.flatCoords, 0, len(g.flatCoords), g.stride)
}
// NumCoords returns the number of coordinates in g.
func (g *geom1) NumCoords() int {
return len(g.flatCoords) / g.stride
}
// Reverse reverses the order of g's coordinates.
func (g *geom1) Reverse() {
reverse1(g.flatCoords, 0, len(g.flatCoords), g.stride)
}
func (g *geom1) setCoords(coords1 []Coord) error {
var err error
g.flatCoords, err = deflate1(nil, coords1, g.stride)
return err
}
func (g *geom1) verify() error {
if g.stride != g.layout.Stride() {
return errStrideLayoutMismatch
}
if g.stride == 0 {
if len(g.flatCoords) != 0 {
return errNonEmptyFlatCoords
}
} else {
if len(g.flatCoords)%g.stride != 0 {
return errLengthStrideMismatch
}
}
return nil
}
// Coords returns all of g's coordinates.
func (g *geom2) Coords() [][]Coord {
return inflate2(g.flatCoords, 0, g.ends, g.stride)
}
// Ends returns the end indexes of all sub-structures in g.
func (g *geom2) Ends() []int {
return g.ends
}
// Reverse reverses the order of coordinates for each sub-structure in g.
func (g *geom2) Reverse() {
reverse2(g.flatCoords, 0, g.ends, g.stride)
}
func (g *geom2) setCoords(coords2 [][]Coord) error {
var err error
g.flatCoords, g.ends, err = deflate2(nil, nil, coords2, g.stride)
return err
}
func (g *geom2) verify() error {
if g.stride != g.layout.Stride() {
return errStrideLayoutMismatch
}
if g.stride == 0 {
if len(g.flatCoords) != 0 {
return errNonEmptyFlatCoords
}
if len(g.ends) != 0 {
return errNonEmptyEnds
}
return nil
}
if len(g.flatCoords)%g.stride != 0 {
return errLengthStrideMismatch
}
offset := 0
for _, end := range g.ends {
if end%g.stride != 0 {
return errMisalignedEnd
}
if end < offset {
return errOutOfOrderEnd
}
offset = end
}
if offset != len(g.flatCoords) {
return errIncorrectEnd
}
return nil
}
// Coords returns all the coordinates in g.
func (g *geom3) Coords() [][][]Coord {
return inflate3(g.flatCoords, 0, g.endss, g.stride)
}
// Endss returns a list of all the sub-sub-structures in g.
func (g *geom3) Endss() [][]int {
return g.endss
}
// Reverse reverses the order of coordinates for each sub-sub-structure in g.
func (g *geom3) Reverse() {
reverse3(g.flatCoords, 0, g.endss, g.stride)
}
func (g *geom3) setCoords(coords3 [][][]Coord) error {
var err error
g.flatCoords, g.endss, err = deflate3(nil, nil, coords3, g.stride)
return err
}
func (g *geom3) verify() error {
if g.stride != g.layout.Stride() {
return errStrideLayoutMismatch
}
if g.stride == 0 {
if len(g.flatCoords) != 0 {
return errNonEmptyFlatCoords
}
if len(g.endss) != 0 {
return errNonEmptyEndss
}
return nil
}
if len(g.flatCoords)%g.stride != 0 {
return errLengthStrideMismatch
}
offset := 0
for _, ends := range g.endss {
for _, end := range ends {
if end%g.stride != 0 {
return errMisalignedEnd
}
if end < offset {
return errOutOfOrderEnd
}
offset = end
}
}
if offset != len(g.flatCoords) {
return errIncorrectEnd
}
return nil
}
func doubleArea1(flatCoords []float64, offset, end, stride int) float64 {
var doubleArea float64
for i := offset + stride; i < end; i += stride {
doubleArea += (flatCoords[i+1] - flatCoords[i+1-stride]) * (flatCoords[i] + flatCoords[i-stride])
}
return doubleArea
}
func doubleArea2(flatCoords []float64, offset int, ends []int, stride int) float64 {
var doubleArea float64
for i, end := range ends {
da := doubleArea1(flatCoords, offset, end, stride)
if i == 0 {
doubleArea = da
} else {
doubleArea -= da
}
offset = end
}
return doubleArea
}
func doubleArea3(flatCoords []float64, offset int, endss [][]int, stride int) float64 {
var doubleArea float64
for _, ends := range endss {
doubleArea += doubleArea2(flatCoords, offset, ends, stride)
offset = ends[len(ends)-1]
}
return doubleArea
}
func deflate0(flatCoords []float64, c Coord, stride int) ([]float64, error) {
if len(c) != stride {
return nil, ErrStrideMismatch{Got: len(c), Want: stride}
}
flatCoords = append(flatCoords, c...)
return flatCoords, nil
}
func deflate1(flatCoords []float64, coords1 []Coord, stride int) ([]float64, error) {
for _, c := range coords1 {
var err error
flatCoords, err = deflate0(flatCoords, c, stride)
if err != nil {
return nil, err
}
}
return flatCoords, nil
}
func deflate2(
flatCoords []float64, ends []int, coords2 [][]Coord, stride int,
) ([]float64, []int, error) {
for _, coords1 := range coords2 {
var err error
flatCoords, err = deflate1(flatCoords, coords1, stride)
if err != nil {
return nil, nil, err
}
ends = append(ends, len(flatCoords))
}
return flatCoords, ends, nil
}
func deflate3(
flatCoords []float64, endss [][]int, coords3 [][][]Coord, stride int,
) ([]float64, [][]int, error) {
for _, coords2 := range coords3 {
var err error
var ends []int
flatCoords, ends, err = deflate2(flatCoords, ends, coords2, stride)
if err != nil {
return nil, nil, err
}
endss = append(endss, ends)
}
return flatCoords, endss, nil
}
func inflate0(flatCoords []float64, offset, end, stride int) Coord {
if offset+stride != end {
panic("geom: stride mismatch")
}
c := make([]float64, stride)
copy(c, flatCoords[offset:end])
return c
}
func inflate1(flatCoords []float64, offset, end, stride int) []Coord {
coords1 := make([]Coord, (end-offset)/stride)
for i := range coords1 {
coords1[i] = inflate0(flatCoords, offset, offset+stride, stride)
offset += stride
}
return coords1
}
func inflate2(flatCoords []float64, offset int, ends []int, stride int) [][]Coord {
coords2 := make([][]Coord, len(ends))
for i := range coords2 {
end := ends[i]
coords2[i] = inflate1(flatCoords, offset, end, stride)
offset = end
}
return coords2
}
func inflate3(flatCoords []float64, offset int, endss [][]int, stride int) [][][]Coord {
coords3 := make([][][]Coord, len(endss))
for i := range coords3 {
ends := endss[i]
coords3[i] = inflate2(flatCoords, offset, ends, stride)
if len(ends) > 0 {
offset = ends[len(ends)-1]
}
}
return coords3
}
func length1(flatCoords []float64, offset, end, stride int) float64 {
var length float64
for i := offset + stride; i < end; i += stride {
dx := flatCoords[i] - flatCoords[i-stride]
dy := flatCoords[i+1] - flatCoords[i+1-stride]
length += math.Sqrt(dx*dx + dy*dy)
}
return length
}
func length2(flatCoords []float64, offset int, ends []int, stride int) float64 {
var length float64
for _, end := range ends {
length += length1(flatCoords, offset, end, stride)
offset = end
}
return length
}
func length3(flatCoords []float64, offset int, endss [][]int, stride int) float64 {
var length float64
for _, ends := range endss {
length += length2(flatCoords, offset, ends, stride)
offset = ends[len(ends)-1]
}
return length
}
func reverse1(flatCoords []float64, offset, end, stride int) {
for i, j := offset+stride, end; i <= j; i, j = i+stride, j-stride {
for k := 0; k < stride; k++ {
flatCoords[i-stride+k], flatCoords[j-stride+k] = flatCoords[j-stride+k], flatCoords[i-stride+k]
}
}
}
func reverse2(flatCoords []float64, offset int, ends []int, stride int) {
for _, end := range ends {
reverse1(flatCoords, offset, end, stride)
offset = end
}
}
func reverse3(flatCoords []float64, offset int, endss [][]int, stride int) {
for _, ends := range endss {
if len(ends) == 0 {
continue
}
reverse2(flatCoords, offset, ends, stride)
offset = ends[len(ends)-1]
}
}
| bsd-2-clause |
kbwatts/polymer-survey | quiz.html | 7898 |
<!--
@license
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<!doctype html>
<html>
<head>
<title>core-animated-pages</title>
<script src="https://www.polymer-project.org/components/platform/platform.js"></script>
<link href="https://www.polymer-project.org/components/core-icons/av-icons.html" rel="import">
<link href="https://www.polymer-project.org/components/paper-fab/paper-fab.html" rel="import">
<link href="https://www.polymer-project.org/components/core-animated-pages/core-animated-pages.html" rel="import">
<link href="https://www.polymer-project.org/components/core-animated-pages/transitions/slide-up.html" rel="import">
<link href="https://www.polymer-project.org/components/core-animated-pages/transitions/list-cascade.html" rel="import">
<style>
body {
font-family: 'Roboto 2', 'Helvetica Neue', Helvetica, Arial, sans-serif;
margin: 0;
background: #f1f1f1;
}
quiz-demo {
display: block;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<polymer-element name="quiz-demo">
<template>
<style>
core-animated-pages {
height: 100%;
}
section {
overflow: hidden;
}
.fab {
position: absolute;
fill: #fff;
}
.fab-0 {
bottom: 50px;
right: 24px;
}
.fab-1 {
top: 210px;
right: 24px;
}
paper-fab {
background-color: #ff4081;
}
.top {
background-color: #ffff8d;
}
.top-image {
background: url(quiz1-intro.png);
height: 287px;
width: 202px;
}
.bottom {
box-sizing: border-box;
position: relative;
height: 80px;
background-color: #ffeb3b;
padding: 24px;
color: #fff;
font-size: 32px;
}
.tall-toolbar {
box-sizing: border-box;
height: 240px;
position: relative;
color: #fff;
padding: 48px;
font-size: 48px;
}
.tall-toolbar.categories {
background-color: #00bbd3;
margin-bottom: 2px;
}
.tall-toolbar.questions {
background-color: #ffeb3b;
}
.middle {
background-color: #fafafa;
color: #3f3f3f;
padding: 24px 48px;
font-size: 24px;
line-height: 1.5;
}
.footer {
height: 80px;
}
.avatar {
height: 80px;
width: 80px;
background-color: #ff80ab;
}
.footer-right, .score {
border-top: 1px solid #ccc;
background-color: #fff;
padding: 30px;
}
.tile {
box-sizing: border-box;
float: left;
height: 200px;
width: 49%;
margin: 3px;
}
.tile-bottom {
padding: 8px;
color: #fff;
}
</style>
<core-animated-pages selected="{{page}}" transitions="hero-transition slide-up slide-down cross-fade list-cascade" on-core-animated-pages-transition-end="{{complete}}">
<section layout vertical>
<div class="tall-toolbar categories" slide-down>
<span>Your name here</span>
</div>
<div class="tiles-container">
<div class="tile" style="background-color:#ccc;" layout vertical>
<div class="tile-top" flex></div>
<div class="tile-bottom" style="background-color:#aaa;">
Leaderboard
</div>
</div>
<div class="tile" hero-id="category-image" hero style="background-color:#ffff8d;" layout vertical on-tap="{{transition}}">
<div class="tile-top" flex></div>
<div class="tile-bottom" hero-id="footer" hero style="background-color:#ffeb3b;">
General Knowledge
</div>
</div>
<div class="tile" style="background-color:#b9f6ca;" layout vertical>
<div class="tile-top" flex></div>
<div class="tile-bottom" style="background-color:#0f9d58;">
Category 2
</div>
</div>
<div class="tile" style="background-color:#ff8a80;" layout vertical>
<div class="tile-top" flex></div>
<div class="tile-bottom" style="background-color:#db4437;">
Category 3
</div>
</div>
<div class="tile" style="background-color:#82b1ff;" layout vertical>
<div class="tile-top" flex></div>
<div class="tile-bottom" style="background-color:#4285f4;">
Category 4
</div>
</div>
<div class="tile" style="background-color:#b388ff;" layout vertical>
<div class="tile-top" flex></div>
<div class="tile-bottom" style="background-color:#7e57c2;">
Category 5
</div>
</div>
</div>
</section>
<section layout vertical>
<div class="top" hero-id="category-image" hero flex layout horizontal center center-justified>
<div class="top-image" cross-fade></div>
</div>
<div class="bottom" hero-id="footer" hero cross-fade>
<span cross-fade>General Knowledge</span>
</div>
<div class="fab fab-0" hero-id="fab" hero>
<paper-fab icon="av:play-arrow" on-tap="{{transition}}" hero></paper-fab>
</div>
</section>
<section layout vertical>
<div class="tall-toolbar questions" hero-id="footer" hero>
<span cross-fade>Question here</span>
</div>
<div class="fab fab-1" hero-id="fab" hero>
<paper-fab icon="av:play-arrow" on-tap="{{transition}}" hero></paper-fab>
</div>
<div flex class="middle" slide-up list-cascade>
<p>Option 1</p>
<p>Option 2</p>
<p>Option 3</p>
<p>Option 4</p>
<p>Option 5</p>
</div>
<div class="footer" layout horizontal slide-up>
<div class="avatar"></div>
<div class="footer-right" flex>
some text here
</div>
<div class="score">
32 pts
</div>
</div>
</section>
</core-animated-pages>
</template>
<script>
Polymer('quiz-demo', {
page: 0,
transition: function(e) {
if (this.page === 2) {
this.page = 0;
} else {
this.page += 1;
}
}
});
</script>
</polymer-element>
<quiz-demo></quiz-demo>
</body>
</html>
| bsd-2-clause |
smistad/FAST | source/FAST/RuntimeMeasurement.hpp | 1189 | #pragma once
#include <string>
#include <memory>
#include <deque>
#include "FAST/Object.hpp"
namespace fast {
/**
* @brief A class for runtime measurement
*
* Collect multiple runtimes over time, and calculates running average, running standard deviation,
* sum, max, min etc.
*
* All measurements are in milliseconds
*
*/
class FAST_EXPORT RuntimeMeasurement : public Object {
public:
typedef std::shared_ptr<RuntimeMeasurement> pointer;
RuntimeMeasurement(std::string name, int warmupRounds = 0, int maximumSamples = -1);
void addSample(double runtime);
double getSum() const;
double getAverage() const;
unsigned int getSamples() const;
double getMax() const;
double getMin() const;
double getStdDeviation() const;
std::string print() const;
void reset();
~RuntimeMeasurement() override = default;
private:
RuntimeMeasurement();
double mSum;
unsigned int mSamples;
double mRunningVariance;
double mRunningMean;
double mMin;
double mMax;
double mFirstSample;
std::string mName;
int m_warmupRounds;
int m_maximumSamples;
std::deque<double> m_queueRuntime;
std::deque<double> m_queueAvg;
std::deque<double> m_queueStd;
};
}; // end namespace
| bsd-2-clause |
thomaseger/media | config/environment.rb | 149 | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
Media::Application.initialize!
| bsd-2-clause |
stuxo/PTHAndroid | PTHAndroid/src/main/java/me/passtheheadphones/request/RequestDetailFragment.java | 8720 | package me.passtheheadphones.request;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import api.cli.Utils;
import api.requests.Request;
import api.requests.Response;
import api.soup.MySoup;
import me.passtheheadphones.R;
import me.passtheheadphones.PTHApplication;
import me.passtheheadphones.callbacks.LoadingListener;
import me.passtheheadphones.callbacks.ViewTorrentCallbacks;
import me.passtheheadphones.callbacks.ViewUserCallbacks;
import me.passtheheadphones.settings.SettingsActivity;
import me.passtheheadphones.views.ImageDialog;
import java.util.Date;
/**
* Display the details of a request, bounty, artists etc.
*/
public class RequestDetailFragment extends Fragment implements View.OnClickListener, LoadingListener<Request> {
/**
* The request being viewed
*/
private Request request;
private ViewUserCallbacks viewUser;
private ViewTorrentCallbacks viewTorrent;
/**
* Various views displaying the information about the request along with associated headers/text
* so that we can hide any unused views
*/
private ImageView image;
private ProgressBar spinner;
private TextView title, created, recordLabel, catalogueNumber, releaseType, filled, filledBy,
acceptBitrates, acceptFormats, acceptMedia, votes, bounty, tags;
private View recordLabelText, catalogueNumberText, releaseTypeText, filledText, filledByText,
bitratesContainer, formatsContainer, mediaContainer, addVote, artContainer;
/**
* The list shows the artists & top contributors
*/
private ExpandableListView list;
/**
* Use this factory method to create a request fragment displaying the request
*
* @param id request to load
* @return fragment displaying the request
*/
public static RequestDetailFragment newInstance(int id){
RequestDetailFragment fragment = new RequestDetailFragment();
Bundle args = new Bundle();
args.putInt(RequestActivity.REQUEST_ID, id);
fragment.setArguments(args);
return fragment;
}
public RequestDetailFragment(){
//Required empty ctor
}
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
try {
viewTorrent = (ViewTorrentCallbacks)activity;
viewUser = (ViewUserCallbacks)activity;
}
catch (ClassCastException e){
throw new ClassCastException(activity.toString()
+ " must implement ViewUser and ViewTorrent callbacks");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.expandable_list_view, container, false);
list = (ExpandableListView)view.findViewById(R.id.exp_list);
View header = inflater.inflate(R.layout.header_request_info, null);
list.addHeaderView(header, null, false);
image = (ImageView)header.findViewById(R.id.image);
spinner = (ProgressBar)header.findViewById(R.id.loading_indicator);
artContainer = header.findViewById(R.id.art_container);
title = (TextView)header.findViewById(R.id.title);
created = (TextView)header.findViewById(R.id.created);
recordLabelText = header.findViewById(R.id.record_label_text);
recordLabel = (TextView)header.findViewById(R.id.record_label);
catalogueNumberText = header.findViewById(R.id.catalogue_number_text);
catalogueNumber = (TextView)header.findViewById(R.id.catalogue_number);
releaseType = (TextView)header.findViewById(R.id.release_type);
releaseTypeText = header.findViewById(R.id.release_type_text);
filled = (TextView)header.findViewById(R.id.filled_torrent);
filledText = header.findViewById(R.id.filled_torrent_text);
filledBy = (TextView)header.findViewById(R.id.filled_user);
filledByText = header.findViewById(R.id.filled_user_text);
acceptBitrates = (TextView)header.findViewById(R.id.accept_bitrates);
bitratesContainer = header.findViewById(R.id.accept_bitrates_container);
acceptFormats = (TextView)header.findViewById(R.id.accept_formats);
formatsContainer = header.findViewById(R.id.accept_formats_container);
acceptMedia = (TextView)header.findViewById(R.id.accept_media);
mediaContainer = header.findViewById(R.id.accept_media_container);
votes = (TextView)header.findViewById(R.id.votes);
bounty = (TextView)header.findViewById(R.id.bounty);
tags = (TextView)header.findViewById(R.id.tags);
addVote = header.findViewById(R.id.add_vote);
addVote.setOnClickListener(this);
image.setOnClickListener(this);
if (request != null){
populateViews();
}
return view;
}
@Override
public void onClick(View v){
if (v.getId() == R.id.add_vote){
VoteDialog dialog = VoteDialog.newInstance(request);
dialog.show(getChildFragmentManager(), "vote_dialog");
}
else if (v.getId() == R.id.image){
ImageDialog dialog = ImageDialog.newInstance(request.getResponse().getImage());
dialog.show(getChildFragmentManager(), "image_dialog");
}
}
@Override
public void onLoadingComplete(Request data){
request = data;
if (isAdded()){
populateViews();
}
}
/**
* Update the request information being shown
*/
private void populateViews(){
Response response = request.getResponse();
title.setText(response.getTitle());
votes.setText(response.getVoteCount().toString());
bounty.setText(Utils.toHumanReadableSize(response.getTotalBounty().longValue()));
Date createDate = MySoup.parseDate(response.getTimeAdded());
created.setText(DateUtils.getRelativeTimeSpanString(createDate.getTime(),
new Date().getTime(), DateUtils.WEEK_IN_MILLIS));
RequestAdapter adapter = new RequestAdapter(getActivity(), response.getMusicInfo(), response.getTopContributors());
list.setAdapter(adapter);
list.setOnChildClickListener(adapter);
//Requests may be missing any of these fields
String imgUrl = response.getImage();
if (!SettingsActivity.imagesEnabled(getActivity())) {
artContainer.setVisibility(View.GONE);
} else {
artContainer.setVisibility(View.VISIBLE);
PTHApplication.loadImage(getActivity(), imgUrl, image, spinner, null, null);
}
if (response.isFilled()){
addVote.setVisibility(View.GONE);
filled.setText("Yes");
filled.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
viewTorrent.viewTorrent(-1, request.getResponse().getTorrentId().intValue());
}
});
filledBy.setText(response.getFillerName());
filledBy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
viewUser.viewUser(request.getResponse().getFillerId().intValue());
}
});
}
else {
filledText.setVisibility(View.GONE);
filled.setVisibility(View.GONE);
filledByText.setVisibility(View.GONE);
filledBy.setVisibility(View.GONE);
}
if (response.getRecordLabel() != null && !response.getRecordLabel().isEmpty()){
recordLabel.setText(response.getRecordLabel());
}
else {
recordLabelText.setVisibility(View.GONE);
recordLabel.setVisibility(View.GONE);
}
if (response.getCatalogueNumber() != null && !response.getCatalogueNumber().isEmpty()){
catalogueNumber.setText(response.getCatalogueNumber());
}
else {
catalogueNumberText.setVisibility(View.GONE);
catalogueNumber.setVisibility(View.GONE);
}
if (response.getReleaseName() != null && !response.getReleaseName().isEmpty()){
releaseType.setText(response.getReleaseName());
}
else {
releaseTypeText.setVisibility(View.GONE);
releaseType.setVisibility(View.GONE);
}
if (!response.getBitrateList().isEmpty()){
String bitrates = response.getBitrateList().toString();
bitrates = bitrates.substring(bitrates.indexOf('[') + 1, bitrates.lastIndexOf(']'));
acceptBitrates.setText(bitrates);
}
else {
bitratesContainer.setVisibility(View.GONE);
}
if (!response.getFormatList().isEmpty()){
String formats = response.getFormatList().toString();
formats = formats.substring(formats.indexOf('[') + 1, formats.lastIndexOf(']'));
acceptFormats.setText(formats);
}
else {
formatsContainer.setVisibility(View.GONE);
}
if (!response.getMediaList().isEmpty()){
String media = response.getMediaList().toString();
media = media.substring(media.indexOf('[') + 1, media.lastIndexOf(']'));
acceptMedia.setText(media);
}
else {
mediaContainer.setVisibility(View.GONE);
}
String tagString = response.getTags().toString();
tagString = tagString.substring(tagString.indexOf('[') + 1, tagString.lastIndexOf(']'));
tags.setText(tagString);
}
}
| bsd-2-clause |
dreamsxin/ultimatepp | bazaar/Form/Form.hpp | 1446 | #ifndef FORM_HPP
#define FORM_HPP
#include <CtrlLib/CtrlLib.h>
#include <GridCtrl/GridCtrl.h>
using namespace Upp;
#include "Container.hpp"
#include "FormLayout.hpp"
class Form : public TopWindow
{
typedef Form CLASSNAME;
public:
Form();
~Form();
bool Load(const String& file);
bool Layout(const String& layout, Font font = StdFont());
bool Generate(Font font = StdFont());
bool Exit(const String& action);
bool Acceptor(const String& action);
bool Rejector(const String& action);
Ctrl* GetCtrl(const String& var);
Value GetData(const String& var);
String ExecuteForm();
String Script;
Callback3<const String&, const String&, const String& > SignalHandler;
ArrayMap<String, Ctrl>& GetCtrls() { return _Ctrls; }
const ArrayMap<String, Ctrl>& GetCtrls() const { return _Ctrls; }
void Clear(bool all = true);
bool IsLayout() { return _Current != -1; }
int HasLayout(const String& layout);
void Xmlize(XmlIO xml) { xml("layouts", _Layouts); }
Vector<FormLayout>& GetLayouts() { return _Layouts; }
const Vector<FormLayout>& GetLayouts() const { return _Layouts; }
protected:
void OnAction(const String& action);
bool SetCallback(const String& action, Callback c);
Vector<String> _Acceptors;
Vector<String> _Rejectors;
Vector<FormLayout> _Layouts;
ArrayMap<String, Ctrl> _Ctrls;
private:
int _Current;
String _File;
};
#endif // .. FORM_HPP
| bsd-2-clause |
Kolkir/blaze-nn | third-party/blaze/include/blaze/math/expressions/DVecDVecAddExpr.h | 54110 | //=================================================================================================
/*!
// \file blaze/math/expressions/DVecDVecAddExpr.h
// \brief Header file for the dense vector/dense vector addition expression
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZE_MATH_EXPRESSIONS_DVECDVECADDEXPR_H_
#define _BLAZE_MATH_EXPRESSIONS_DVECDVECADDEXPR_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <iterator>
#include <blaze/math/Aliases.h>
#include <blaze/math/constraints/DenseVector.h>
#include <blaze/math/constraints/RequiresEvaluation.h>
#include <blaze/math/constraints/TransposeFlag.h>
#include <blaze/math/constraints/VecVecAddExpr.h>
#include <blaze/math/Exception.h>
#include <blaze/math/expressions/Computation.h>
#include <blaze/math/expressions/DenseVector.h>
#include <blaze/math/expressions/Forward.h>
#include <blaze/math/expressions/VecVecAddExpr.h>
#include <blaze/math/shims/Serial.h>
#include <blaze/math/SIMD.h>
#include <blaze/math/traits/AddExprTrait.h>
#include <blaze/math/traits/AddTrait.h>
#include <blaze/math/typetraits/HasSIMDAdd.h>
#include <blaze/math/typetraits/IsAligned.h>
#include <blaze/math/typetraits/IsComputation.h>
#include <blaze/math/typetraits/IsExpression.h>
#include <blaze/math/typetraits/IsPadded.h>
#include <blaze/math/typetraits/IsTemporary.h>
#include <blaze/math/typetraits/RequiresEvaluation.h>
#include <blaze/math/typetraits/Size.h>
#include <blaze/system/Inline.h>
#include <blaze/system/Thresholds.h>
#include <blaze/util/Assert.h>
#include <blaze/util/constraints/Double.h>
#include <blaze/util/constraints/Float.h>
#include <blaze/util/EnableIf.h>
#include <blaze/util/FunctionTrace.h>
#include <blaze/util/IntegralConstant.h>
#include <blaze/util/mpl/And.h>
#include <blaze/util/mpl/If.h>
#include <blaze/util/mpl/Maximum.h>
#include <blaze/util/Types.h>
namespace blaze {
//=================================================================================================
//
// CLASS DVECDVECADDEXPR
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Expression object for dense vector-dense vector additions.
// \ingroup dense_vector_expression
//
// The DVecDVecAddExpr class represents the compile time expression for additions between
// dense vectors.
*/
template< typename VT1 // Type of the left-hand side dense vector
, typename VT2 // Type of the right-hand side dense vector
, bool TF > // Transpose flag
class DVecDVecAddExpr
: public VecVecAddExpr< DenseVector< DVecDVecAddExpr<VT1,VT2,TF>, TF > >
, private Computation
{
private:
//**Type definitions****************************************************************************
using RE1 = ResultType_<VT1>; //!< Result type of the left-hand side dense vector expression.
using RE2 = ResultType_<VT2>; //!< Result type of the right-hand side dense vector expression.
using RN1 = ReturnType_<VT1>; //!< Return type of the left-hand side dense vector expression.
using RN2 = ReturnType_<VT2>; //!< Return type of the right-hand side dense vector expression.
using CT1 = CompositeType_<VT1>; //!< Composite type of the left-hand side dense vector expression.
using CT2 = CompositeType_<VT2>; //!< Composite type of the right-hand side dense vector expression.
using ET1 = ElementType_<VT1>; //!< Element type of the left-hand side dense vector expression.
using ET2 = ElementType_<VT2>; //!< Element type of the right-hand side dense vector expression.
//**********************************************************************************************
//**Return type evaluation**********************************************************************
//! Compilation switch for the selection of the subscript operator return type.
/*! The \a returnExpr compile time constant expression is a compilation switch for the
selection of the \a ReturnType. If either vector operand returns a temporary vector
or matrix, \a returnExpr will be set to 0 and the subscript operator will return
it's result by value. Otherwise \a returnExpr will be set to 1 and the subscript
operator may return it's result as an expression. */
enum : bool { returnExpr = !IsTemporary<RN1>::value && !IsTemporary<RN2>::value };
//! Expression return type for the subscript operator.
using ExprReturnType = AddExprTrait_<RN1,RN2>;
//**********************************************************************************************
//**Serial evaluation strategy******************************************************************
//! Compilation switch for the serial evaluation strategy of the addition expression.
/*! The \a useAssign compile time constant expression represents a compilation switch for
the serial evaluation strategy of the addition expression. In case either of the two
dense vector operands requires an intermediate evaluation or the subscript operator
can only return by value, \a useAssign will be set to 1 and the addition expression
will be evaluated via the \a assign function family. Otherwise \a useAssign will be
set to 0 and the expression will be evaluated via the subscript operator. */
enum : bool { useAssign = ( RequiresEvaluation<VT1>::value || RequiresEvaluation<VT2>::value || !returnExpr ) };
/*! \cond BLAZE_INTERNAL */
//! Helper structure for the explicit application of the SFINAE principle.
template< typename VT >
struct UseAssign {
enum : bool { value = useAssign };
};
/*! \endcond */
//**********************************************************************************************
//**Parallel evaluation strategy****************************************************************
/*! \cond BLAZE_INTERNAL */
//! Helper structure for the explicit application of the SFINAE principle.
/*! The UseSMPAssign struct is a helper struct for the selection of the parallel evaluation
strategy. In case at least one of the two dense vector operands is not SMP assignable and
at least one of the two operands requires an intermediate evaluation, \a value is set to 1
and the expression specific evaluation strategy is selected. Otherwise \a value is set to
0 and the default strategy is chosen. */
template< typename VT >
struct UseSMPAssign {
enum : bool { value = ( !VT1::smpAssignable || !VT2::smpAssignable ) && useAssign };
};
/*! \endcond */
//**********************************************************************************************
public:
//**Type definitions****************************************************************************
using This = DVecDVecAddExpr<VT1,VT2,TF>; //!< Type of this DVecDVecAddExpr instance.
using ResultType = AddTrait_<RE1,RE2>; //!< Result type for expression template evaluations.
using TransposeType = TransposeType_<ResultType>; //!< Transpose type for expression template evaluations.
using ElementType = ElementType_<ResultType>; //!< Resulting element type.
//! Return type for expression template evaluations.
using ReturnType = const IfTrue_< returnExpr, ExprReturnType, ElementType >;
//! Data type for composite expression templates.
using CompositeType = IfTrue_< useAssign, const ResultType, const DVecDVecAddExpr& >;
//! Composite type of the left-hand side dense vector expression.
using LeftOperand = If_< IsExpression<VT1>, const VT1, const VT1& >;
//! Composite type of the right-hand side dense vector expression.
using RightOperand = If_< IsExpression<VT2>, const VT2, const VT2& >;
//**********************************************************************************************
//**ConstIterator class definition**************************************************************
/*!\brief Iterator over the elements of the dense vector.
*/
class ConstIterator
{
public:
//**Type definitions*************************************************************************
using IteratorCategory = std::random_access_iterator_tag; //!< The iterator category.
using ValueType = ElementType; //!< Type of the underlying elements.
using PointerType = ElementType*; //!< Pointer return type.
using ReferenceType = ElementType&; //!< Reference return type.
using DifferenceType = ptrdiff_t; //!< Difference between two iterators.
// STL iterator requirements
using iterator_category = IteratorCategory; //!< The iterator category.
using value_type = ValueType; //!< Type of the underlying elements.
using pointer = PointerType; //!< Pointer return type.
using reference = ReferenceType; //!< Reference return type.
using difference_type = DifferenceType; //!< Difference between two iterators.
//! ConstIterator type of the left-hand side dense vector expression.
using LeftIteratorType = ConstIterator_<VT1>;
//! ConstIterator type of the right-hand side dense vector expression.
using RightIteratorType = ConstIterator_<VT2>;
//*******************************************************************************************
//**Constructor******************************************************************************
/*!\brief Constructor for the ConstIterator class.
//
// \param left Iterator to the initial left-hand side element.
// \param right Iterator to the initial right-hand side element.
*/
explicit inline ConstIterator( LeftIteratorType left, RightIteratorType right )
: left_ ( left ) // Iterator to the current left-hand side element
, right_( right ) // Iterator to the current right-hand side element
{}
//*******************************************************************************************
//**Addition assignment operator*************************************************************
/*!\brief Addition assignment operator.
//
// \param inc The increment of the iterator.
// \return The incremented iterator.
*/
inline ConstIterator& operator+=( size_t inc ) {
left_ += inc;
right_ += inc;
return *this;
}
//*******************************************************************************************
//**Subtraction assignment operator**********************************************************
/*!\brief Subtraction assignment operator.
//
// \param dec The decrement of the iterator.
// \return The decremented iterator.
*/
inline ConstIterator& operator-=( size_t dec ) {
left_ -= dec;
right_ -= dec;
return *this;
}
//*******************************************************************************************
//**Prefix increment operator****************************************************************
/*!\brief Pre-increment operator.
//
// \return Reference to the incremented iterator.
*/
inline ConstIterator& operator++() {
++left_;
++right_;
return *this;
}
//*******************************************************************************************
//**Postfix increment operator***************************************************************
/*!\brief Post-increment operator.
//
// \return The previous position of the iterator.
*/
inline const ConstIterator operator++( int ) {
return ConstIterator( left_++, right_++ );
}
//*******************************************************************************************
//**Prefix decrement operator****************************************************************
/*!\brief Pre-decrement operator.
//
// \return Reference to the decremented iterator.
*/
inline ConstIterator& operator--() {
--left_;
--right_;
return *this;
}
//*******************************************************************************************
//**Postfix decrement operator***************************************************************
/*!\brief Post-decrement operator.
//
// \return The previous position of the iterator.
*/
inline const ConstIterator operator--( int ) {
return ConstIterator( left_--, right_-- );
}
//*******************************************************************************************
//**Element access operator******************************************************************
/*!\brief Direct access to the element at the current iterator position.
//
// \return The resulting value.
*/
inline ReturnType operator*() const {
return (*left_) + (*right_);
}
//*******************************************************************************************
//**Load function****************************************************************************
/*!\brief Access to the SIMD elements of the vector.
//
// \return The resulting SIMD element.
*/
inline auto load() const noexcept {
return left_.load() + right_.load();
}
//*******************************************************************************************
//**Equality operator************************************************************************
/*!\brief Equality comparison between two ConstIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the iterators refer to the same element, \a false if not.
*/
inline bool operator==( const ConstIterator& rhs ) const {
return left_ == rhs.left_;
}
//*******************************************************************************************
//**Inequality operator**********************************************************************
/*!\brief Inequality comparison between two ConstIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the iterators don't refer to the same element, \a false if they do.
*/
inline bool operator!=( const ConstIterator& rhs ) const {
return left_ != rhs.left_;
}
//*******************************************************************************************
//**Less-than operator***********************************************************************
/*!\brief Less-than comparison between two ConstIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the left-hand side iterator is smaller, \a false if not.
*/
inline bool operator<( const ConstIterator& rhs ) const {
return left_ < rhs.left_;
}
//*******************************************************************************************
//**Greater-than operator********************************************************************
/*!\brief Greater-than comparison between two ConstIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the left-hand side iterator is greater, \a false if not.
*/
inline bool operator>( const ConstIterator& rhs ) const {
return left_ > rhs.left_;
}
//*******************************************************************************************
//**Less-or-equal-than operator**************************************************************
/*!\brief Less-than comparison between two ConstIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the left-hand side iterator is smaller or equal, \a false if not.
*/
inline bool operator<=( const ConstIterator& rhs ) const {
return left_ <= rhs.left_;
}
//*******************************************************************************************
//**Greater-or-equal-than operator***********************************************************
/*!\brief Greater-than comparison between two ConstIterator objects.
//
// \param rhs The right-hand side iterator.
// \return \a true if the left-hand side iterator is greater or equal, \a false if not.
*/
inline bool operator>=( const ConstIterator& rhs ) const {
return left_ >= rhs.left_;
}
//*******************************************************************************************
//**Subtraction operator*********************************************************************
/*!\brief Calculating the number of elements between two iterators.
//
// \param rhs The right-hand side iterator.
// \return The number of elements between the two iterators.
*/
inline DifferenceType operator-( const ConstIterator& rhs ) const {
return left_ - rhs.left_;
}
//*******************************************************************************************
//**Addition operator************************************************************************
/*!\brief Addition between a ConstIterator and an integral value.
//
// \param it The iterator to be incremented.
// \param inc The number of elements the iterator is incremented.
// \return The incremented iterator.
*/
friend inline const ConstIterator operator+( const ConstIterator& it, size_t inc ) {
return ConstIterator( it.left_ + inc, it.right_ + inc );
}
//*******************************************************************************************
//**Addition operator************************************************************************
/*!\brief Addition between an integral value and a ConstIterator.
//
// \param inc The number of elements the iterator is incremented.
// \param it The iterator to be incremented.
// \return The incremented iterator.
*/
friend inline const ConstIterator operator+( size_t inc, const ConstIterator& it ) {
return ConstIterator( it.left_ + inc, it.right_ + inc );
}
//*******************************************************************************************
//**Subtraction operator*********************************************************************
/*!\brief Subtraction between a ConstIterator and an integral value.
//
// \param it The iterator to be decremented.
// \param dec The number of elements the iterator is decremented.
// \return The decremented iterator.
*/
friend inline const ConstIterator operator-( const ConstIterator& it, size_t dec ) {
return ConstIterator( it.left_ - dec, it.right_ - dec );
}
//*******************************************************************************************
private:
//**Member variables*************************************************************************
LeftIteratorType left_; //!< Iterator to the current left-hand side element.
RightIteratorType right_; //!< Iterator to the current right-hand side element.
//*******************************************************************************************
};
//**********************************************************************************************
//**Compilation flags***************************************************************************
//! Compilation switch for the expression template evaluation strategy.
enum : bool { simdEnabled = VT1::simdEnabled && VT2::simdEnabled &&
HasSIMDAdd<ET1,ET2>::value };
//! Compilation switch for the expression template assignment strategy.
enum : bool { smpAssignable = VT1::smpAssignable && VT2::smpAssignable };
//**********************************************************************************************
//**SIMD properties*****************************************************************************
//! The number of elements packed within a single SIMD element.
enum : size_t { SIMDSIZE = SIMDTrait<ElementType>::size };
//**********************************************************************************************
//**Constructor*********************************************************************************
/*!\brief Constructor for the DVecDVecAddExpr class.
//
// \param lhs The left-hand side operand of the addition expression.
// \param rhs The right-hand side operand of the addition expression.
*/
explicit inline DVecDVecAddExpr( const VT1& lhs, const VT2& rhs ) noexcept
: lhs_( lhs ) // Left-hand side dense vector of the addition expression
, rhs_( rhs ) // Right-hand side dense vector of the addition expression
{
BLAZE_INTERNAL_ASSERT( lhs.size() == rhs.size(), "Invalid vector sizes" );
}
//**********************************************************************************************
//**Subscript operator**************************************************************************
/*!\brief Subscript operator for the direct access to the vector elements.
//
// \param index Access index. The index has to be in the range \f$[0..N-1]\f$.
// \return The resulting value.
*/
inline ReturnType operator[]( size_t index ) const {
BLAZE_INTERNAL_ASSERT( index < lhs_.size(), "Invalid vector access index" );
return lhs_[index] + rhs_[index];
}
//**********************************************************************************************
//**At function*********************************************************************************
/*!\brief Checked access to the vector elements.
//
// \param index Access index. The index has to be in the range \f$[0..N-1]\f$.
// \return The resulting value.
// \exception std::out_of_range Invalid vector access index.
*/
inline ReturnType at( size_t index ) const {
if( index >= lhs_.size() ) {
BLAZE_THROW_OUT_OF_RANGE( "Invalid vector access index" );
}
return (*this)[index];
}
//**********************************************************************************************
//**Load function*******************************************************************************
/*!\brief Access to the SIMD elements of the vector.
//
// \param index Access index. The index has to be in the range \f$[0..N-1]\f$.
// \return Reference to the accessed values.
*/
BLAZE_ALWAYS_INLINE auto load( size_t index ) const noexcept {
BLAZE_INTERNAL_ASSERT( index < lhs_.size() , "Invalid vector access index" );
BLAZE_INTERNAL_ASSERT( index % SIMDSIZE == 0UL, "Invalid vector access index" );
return lhs_.load( index ) + rhs_.load( index );
}
//**********************************************************************************************
//**Begin function******************************************************************************
/*!\brief Returns an iterator to the first non-zero element of the dense vector.
//
// \return Iterator to the first non-zero element of the dense vector.
*/
inline ConstIterator begin() const {
return ConstIterator( lhs_.begin(), rhs_.begin() );
}
//**********************************************************************************************
//**End function********************************************************************************
/*!\brief Returns an iterator just past the last non-zero element of the dense vector.
//
// \return Iterator just past the last non-zero element of the dense vector.
*/
inline ConstIterator end() const {
return ConstIterator( lhs_.end(), rhs_.end() );
}
//**********************************************************************************************
//**Size function*******************************************************************************
/*!\brief Returns the current size/dimension of the vector.
//
// \return The size of the vector.
*/
inline size_t size() const noexcept {
return lhs_.size();
}
//**********************************************************************************************
//**Left operand access*************************************************************************
/*!\brief Returns the left-hand side dense vector operand.
//
// \return The left-hand side dense vector operand.
*/
inline LeftOperand leftOperand() const noexcept {
return lhs_;
}
//**********************************************************************************************
//**Right operand access************************************************************************
/*!\brief Returns the right-hand side dense vector operand.
//
// \return The right-hand side dense vector operand.
*/
inline RightOperand rightOperand() const noexcept {
return rhs_;
}
//**********************************************************************************************
//**********************************************************************************************
/*!\brief Returns whether the expression can alias with the given address \a alias.
//
// \param alias The alias to be checked.
// \return \a true in case the expression can alias, \a false otherwise.
*/
template< typename T >
inline bool canAlias( const T* alias ) const noexcept {
return ( IsExpression<VT1>::value && ( RequiresEvaluation<VT1>::value ? lhs_.isAliased( alias ) : lhs_.canAlias( alias ) ) ) ||
( IsExpression<VT2>::value && ( RequiresEvaluation<VT2>::value ? rhs_.isAliased( alias ) : rhs_.canAlias( alias ) ) );
}
//**********************************************************************************************
//**********************************************************************************************
/*!\brief Returns whether the expression is aliased with the given address \a alias.
//
// \param alias The alias to be checked.
// \return \a true in case an alias effect is detected, \a false otherwise.
*/
template< typename T >
inline bool isAliased( const T* alias ) const noexcept {
return ( lhs_.isAliased( alias ) || rhs_.isAliased( alias ) );
}
//**********************************************************************************************
//**********************************************************************************************
/*!\brief Returns whether the operands of the expression are properly aligned in memory.
//
// \return \a true in case the operands are aligned, \a false if not.
*/
inline bool isAligned() const noexcept {
return lhs_.isAligned() && rhs_.isAligned();
}
//**********************************************************************************************
//**********************************************************************************************
/*!\brief Returns whether the expression can be used in SMP assignments.
//
// \return \a true in case the expression can be used in SMP assignments, \a false if not.
*/
inline bool canSMPAssign() const noexcept {
return lhs_.canSMPAssign() || rhs_.canSMPAssign() ||
( size() > SMP_DVECDVECADD_THRESHOLD );
}
//**********************************************************************************************
private:
//**Member variables****************************************************************************
LeftOperand lhs_; //!< Left-hand side dense vector of the addition expression.
RightOperand rhs_; //!< Right-hand side dense vector of the addition expression.
//**********************************************************************************************
//**Assignment to dense vectors*****************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression to be assigned.
// \return void
//
// This function implements the performance optimized assignment of a dense vector-dense
// vector addition expression to a dense vector. Due to the explicit application of the
// SFINAE principle, this function can only be selected by the compiler in case either
// of the two operands requires an intermediate evaluation.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseAssign<VT> >
assign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
if( !IsComputation<VT1>::value && isSame( ~lhs, rhs.lhs_ ) ) {
addAssign( ~lhs, rhs.rhs_ );
}
else if( !IsComputation<VT2>::value && isSame( ~lhs, rhs.rhs_ ) ) {
addAssign( ~lhs, rhs.lhs_ );
}
else {
assign ( ~lhs, rhs.lhs_ );
addAssign( ~lhs, rhs.rhs_ );
}
}
/*! \endcond */
//**********************************************************************************************
//**Assignment to sparse vectors****************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Assignment of a dense vector-dense vector addition to a sparse vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side sparse vector.
// \param rhs The right-hand side addition expression to be assigned.
// \return void
//
// This function implements the performance optimized assignment of a dense vector-dense
// vector addition expression to a sparse vector. Due to the explicit application of the
// SFINAE principle, this function can only be selected by the compiler in case either
// of the two operands requires an intermediate evaluation.
*/
template< typename VT > // Type of the target sparse vector
friend inline EnableIf_< UseAssign<VT> >
assign( SparseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( ResultType );
BLAZE_CONSTRAINT_MUST_BE_VECTOR_WITH_TRANSPOSE_FLAG( ResultType, TF );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
const ResultType tmp( serial( rhs ) );
assign( ~lhs, tmp );
}
/*! \endcond */
//**********************************************************************************************
//**Addition assignment to dense vectors********************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Addition assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression to be added.
// \return void
//
// This function implements the performance optimized addition assignment of a dense vector-
// dense vector addition expression to a dense vector. Due to the explicit application of
// the SFINAE principle, this function can only be selected by the compiler in case either
// of the operands requires an intermediate evaluation.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseAssign<VT> >
addAssign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
addAssign( ~lhs, rhs.lhs_ );
addAssign( ~lhs, rhs.rhs_ );
}
/*! \endcond */
//**********************************************************************************************
//**Addition assignment to sparse vectors*******************************************************
// No special implementation for the addition assignment to sparse vectors.
//**********************************************************************************************
//**Subtraction assignment to dense vectors*****************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Subtraction assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression to be subtracted.
// \return void
//
// This function implements the performance optimized subtraction assignment of a dense vector-
// dense vector addition expression to a dense vector. Due to the explicit application of the
// SFINAE principle, this function can only be selected by the compiler in case either of the
// operands requires an intermediate evaluation.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseAssign<VT> >
subAssign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
subAssign( ~lhs, rhs.lhs_ );
subAssign( ~lhs, rhs.rhs_ );
}
/*! \endcond */
//**********************************************************************************************
//**Subtraction assignment to sparse vectors****************************************************
// No special implementation for the subtraction assignment to sparse vectors.
//**********************************************************************************************
//**Multiplication assignment to dense vectors**************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Multiplication assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression to be multiplied.
// \return void
//
// This function implements the performance optimized multiplication assignment of a dense
// vector-dense vector addition expression to a dense vector. Due to the explicit application
// of the SFINAE principle, this function can only be selected by the compiler in case either
// of the operands requires an intermediate evaluation.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseAssign<VT> >
multAssign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( ResultType );
BLAZE_CONSTRAINT_MUST_BE_VECTOR_WITH_TRANSPOSE_FLAG( ResultType, TF );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
const ResultType tmp( serial( rhs ) );
multAssign( ~lhs, tmp );
}
/*! \endcond */
//**********************************************************************************************
//**Multiplication assignment to sparse vectors*************************************************
// No special implementation for the multiplication assignment to sparse vectors.
//**********************************************************************************************
//**Division assignment to dense vectors********************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Division assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression divisor.
// \return void
//
// This function implements the performance optimized division assignment of a dense vector-
// dense vector addition expression to a dense vector. Due to the explicit application of the
// SFINAE principle, this function can only be selected by the compiler in case either of the
// operands requires an intermediate evaluation.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseAssign<VT> >
divAssign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( ResultType );
BLAZE_CONSTRAINT_MUST_BE_VECTOR_WITH_TRANSPOSE_FLAG( ResultType, TF );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
const ResultType tmp( serial( rhs ) );
divAssign( ~lhs, tmp );
}
/*! \endcond */
//**********************************************************************************************
//**Division assignment to sparse vectors*******************************************************
// No special implementation for the division assignment to sparse vectors.
//**********************************************************************************************
//**SMP assignment to dense vectors*************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief SMP assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression to be assigned.
// \return void
//
// This function implements the performance optimized SMP assignment of a dense vector-dense
// vector addition expression to a dense vector. Due to the explicit application of the SFINAE
// principle, this function can only be selected by the compiler in case the expression specific
// parallel evaluation strategy is selected.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseSMPAssign<VT> >
smpAssign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
if( !IsComputation<VT1>::value && isSame( ~lhs, rhs.lhs_ ) ) {
smpAddAssign( ~lhs, rhs.rhs_ );
}
else if( !IsComputation<VT2>::value && isSame( ~lhs, rhs.rhs_ ) ) {
smpAddAssign( ~lhs, rhs.lhs_ );
}
else {
smpAssign ( ~lhs, rhs.lhs_ );
smpAddAssign( ~lhs, rhs.rhs_ );
}
}
/*! \endcond */
//**********************************************************************************************
//**SMP assignment to sparse vectors************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief SMP assignment of a dense vector-dense vector addition to a sparse vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side sparse vector.
// \param rhs The right-hand side addition expression to be assigned.
// \return void
//
// This function implements the performance optimized SMP assignment of a dense vector-dense
// vector addition expression to a sparse vector. Due to the explicit application of the
// SFINAE principle, this function can only be selected by the compiler in case the expression
// specific parallel evaluation strategy is selected.
*/
template< typename VT > // Type of the target sparse vector
friend inline EnableIf_< UseSMPAssign<VT> >
smpAssign( SparseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( ResultType );
BLAZE_CONSTRAINT_MUST_BE_VECTOR_WITH_TRANSPOSE_FLAG( ResultType, TF );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
const ResultType tmp( rhs );
smpAssign( ~lhs, tmp );
}
/*! \endcond */
//**********************************************************************************************
//**SMP addition assignment to dense vectors****************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief SMP addition assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression to be added.
// \return void
//
// This function implements the performance optimized SMP addition assignment of a dense
// vector-dense vector addition expression to a dense vector. Due to the explicit application
// of the SFINAE principle, this function can only be selected by the compiler in case the
// expression specific parallel evaluation strategy is selected.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseSMPAssign<VT> >
smpAddAssign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
smpAddAssign( ~lhs, rhs.lhs_ );
smpAddAssign( ~lhs, rhs.rhs_ );
}
/*! \endcond */
//**********************************************************************************************
//**SMP addition assignment to sparse vectors***************************************************
// No special implementation for the SMP addition assignment to sparse vectors.
//**********************************************************************************************
//**SMP subtraction assignment to dense vectors*************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief SMP subtraction assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression to be subtracted.
// \return void
//
// This function implements the performance optimized SMP subtraction assignment of a dense
// vector-dense vector addition expression to a dense vector. Due to the explicit application
// of the SFINAE principle, this function can only be selected by the compiler in case the
// expression specific parallel evaluation strategy is selected.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseSMPAssign<VT> >
smpSubAssign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
smpSubAssign( ~lhs, rhs.lhs_ );
smpSubAssign( ~lhs, rhs.rhs_ );
}
/*! \endcond */
//**********************************************************************************************
//**SMP subtraction assignment to sparse vectors************************************************
// No special implementation for the SMP subtraction assignment to sparse vectors.
//**********************************************************************************************
//**SMP multiplication assignment to dense vectors**********************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief SMP multiplication assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression to be multiplied.
// \return void
//
// This function implements the performance optimized SMP multiplication assignment of a dense
// vector-dense vector addition expression to a dense vector. Due to the explicit application
// of the SFINAE principle, this function can only be selected by the compiler in case the
// expression specific parallel evaluation strategy is selected.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseSMPAssign<VT> >
smpMultAssign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( ResultType );
BLAZE_CONSTRAINT_MUST_BE_VECTOR_WITH_TRANSPOSE_FLAG( ResultType, TF );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
const ResultType tmp( rhs );
smpMultAssign( ~lhs, tmp );
}
/*! \endcond */
//**********************************************************************************************
//**SMP multiplication assignment to sparse vectors*********************************************
// No special implementation for the SMP multiplication assignment to sparse vectors.
//**********************************************************************************************
//**SMP division assignment to dense vectors****************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief SMP division assignment of a dense vector-dense vector addition to a dense vector.
// \ingroup dense_vector
//
// \param lhs The target left-hand side dense vector.
// \param rhs The right-hand side addition expression divisor.
// \return void
//
// This function implements the performance optimized SMP division assignment of a dense
// vector-dense vector addition expression to a dense vector. Due to the explicit application
// of the SFINAE principle, this function can only be selected by the compiler in case the
// expression specific parallel evaluation strategy is selected.
*/
template< typename VT > // Type of the target dense vector
friend inline EnableIf_< UseSMPAssign<VT> >
smpDivAssign( DenseVector<VT,TF>& lhs, const DVecDVecAddExpr& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( ResultType );
BLAZE_CONSTRAINT_MUST_BE_VECTOR_WITH_TRANSPOSE_FLAG( ResultType, TF );
BLAZE_CONSTRAINT_MUST_NOT_REQUIRE_EVALUATION( ResultType );
BLAZE_INTERNAL_ASSERT( (~lhs).size() == rhs.size(), "Invalid vector sizes" );
const ResultType tmp( rhs );
smpDivAssign( ~lhs, tmp );
}
/*! \endcond */
//**********************************************************************************************
//**SMP division assignment to sparse vectors***************************************************
// No special implementation for the SMP division assignment to sparse vectors.
//**********************************************************************************************
//**Compile time checks*************************************************************************
/*! \cond BLAZE_INTERNAL */
BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( VT1 );
BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( VT2 );
BLAZE_CONSTRAINT_MUST_BE_VECTOR_WITH_TRANSPOSE_FLAG( VT1, TF );
BLAZE_CONSTRAINT_MUST_BE_VECTOR_WITH_TRANSPOSE_FLAG( VT2, TF );
BLAZE_CONSTRAINT_MUST_FORM_VALID_VECVECADDEXPR( VT1, VT2 );
/*! \endcond */
//**********************************************************************************************
};
//*************************************************************************************************
//=================================================================================================
//
// GLOBAL BINARY ARITHMETIC OPERATORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Addition operator for the addition of two dense vectors (\f$ \vec{a}=\vec{b}+\vec{c} \f$).
// \ingroup dense_vector
//
// \param lhs The left-hand side dense vector for the vector addition.
// \param rhs The right-hand side dense vector for the vector addition.
// \return The sum of the two vectors.
// \exception std::invalid_argument Vector sizes do not match.
//
// This operator represents the addition of two dense vectors:
\code
blaze::DynamicVector<double> a, b, c;
// ... Resizing and initialization
c = a + b;
\endcode
// The operator returns an expression representing a dense vector of the higher-order element
// type of the two involved vector element types \a VT1::ElementType and \a VT2::ElementType.
// Both vector types \a VT1 and \a VT2 as well as the two element types \a VT1::ElementType
// and \a VT2::ElementType have to be supported by the AddTrait class template.\n
// In case the current sizes of the two given vectors don't match, a \a std::invalid_argument
// is thrown.
*/
template< typename VT1 // Type of the left-hand side dense vector
, typename VT2 // Type of the right-hand side dense vector
, bool TF > // Transpose flag
inline decltype(auto)
operator+( const DenseVector<VT1,TF>& lhs, const DenseVector<VT2,TF>& rhs )
{
BLAZE_FUNCTION_TRACE;
if( (~lhs).size() != (~rhs).size() ) {
BLAZE_THROW_INVALID_ARGUMENT( "Vector sizes do not match" );
}
using ReturnType = const DVecDVecAddExpr<VT1,VT2,TF>;
return ReturnType( ~lhs, ~rhs );
}
//*************************************************************************************************
//=================================================================================================
//
// SIZE SPECIALIZATIONS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
template< typename VT1, typename VT2, bool TF >
struct Size< DVecDVecAddExpr<VT1,VT2,TF> >
: public Maximum< Size<VT1>, Size<VT2> >
{};
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// ISALIGNED SPECIALIZATIONS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
template< typename VT1, typename VT2, bool TF >
struct IsAligned< DVecDVecAddExpr<VT1,VT2,TF> >
: public BoolConstant< And< IsAligned<VT1>, IsAligned<VT2> >::value >
{};
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// ISPADDED SPECIALIZATIONS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
template< typename VT1, typename VT2, bool TF >
struct IsPadded< DVecDVecAddExpr<VT1,VT2,TF> >
: public BoolConstant< And< IsPadded<VT1>, IsPadded<VT2> >::value >
{};
/*! \endcond */
//*************************************************************************************************
} // namespace blaze
#endif
| bsd-2-clause |
ToQoz/gopwt | _misc/readme.header.md | 950 | # gopwt
[](https://travis-ci.org/ToQoz/gopwt)
[](https://ci.appveyor.com/project/ToQoz/gopwt/branch/master)
[](https://goreportcard.com/report/github.com/ToQoz/gopwt)
[](https://codecov.io/gh/ToQoz/gopwt)
PowerAssert library for golang.
<img src="https://i.gyazo.com/fde9f5c049a94b02019a578d4b7e19c5.png" width="713" alt="screenshot">

## Supported go versions
See [.travis.yml](/.travis.yml)
## Getting Started
Check [online demo](http://gopwt.toqoz.net) at first!
| bsd-2-clause |
enriquefynn/contests | README.md | 54 | contests
========
Some programming challenges I made
| bsd-2-clause |
Devronium/ConceptApplicationServer | core/server/Samples/CIDE/Help/win32.graph.freeimage.FreeImage_GetDotsPerMeterY.html | 2339 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>win32.graph.freeimage.FreeImage_GetDotsPerMeterY</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
</head>
<body bgcolor="#ffffff">
<table border="0" width="100%" bgcolor="#F0F0FF">
<tr>
<td>Concept Framework 2.2 documentation</td>
<td align="right"><a href="index.html">Contents</a> | <a href="index_fun.html">Index</a></td>
</tr>
</table>
<h2><a href="win32.graph.freeimage.html">win32.graph.freeimage</a>.FreeImage_GetDotsPerMeterY</h2>
<table border="0" cellspacing="0" cellpadding="0" width="500" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr bgcolor="#f0f0f0">
<td><i>Name</i></td>
<td><i>Version</i></td>
<td><i>Deprecated</i></td>
</tr>
<tr bgcolor="#fafafa">
<td><b>FreeImage_GetDotsPerMeterY</b></td>
<td>version 1.0</td>
<td>no</td>
</tr>
</table>
<br />
<b>Prototype:</b><br />
<table bgcolor="#F0F0F0" width="100%" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"><tr><td><b>number FreeImage_GetDotsPerMeterY(number dib)</b></td></tr></table>
<br />
<br />
<b>Description:</b><br />
<table width="100%" bgcolor="#FAFAFF" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr><td>
Get the vertical resolution, in pixels-per-meter, of the target device for the bitmap.
</td></tr>
</table>
<br />
<b>Returns:</b><br />
Returns the vertical resolution, in pixels-per-meter, of the target device for the bitmap.
<br />
<br />
<!--
<p>
<a href="http://validator.w3.org/check?uri=referer"><img
src="http://www.w3.org/Icons/valid-html40"
alt="Valid HTML 4.0 Transitional" height="31" width="88" border="0"></a>
<a href="http://jigsaw.w3.org/css-validator/">
<img style="border:0;width:88px;height:31px"
src="http://jigsaw.w3.org/css-validator/images/vcss"
alt="Valid CSS!" border="0"/>
</a>
</p>
-->
<table bgcolor="#F0F0F0" width="100%"><tr><td>Documented by Eduard Suica, generation time: Sun Jan 27 18:15:20 2013
GMT</td><td align="right">(c)2013 <a href="http://www.devronium.com">Devronium Applications</a></td></tr></table>
</body>
</html> | bsd-2-clause |
bitmonk/fabtools | fabtools/openvz/contextmanager.py | 9146 | """
OpenVZ containers
=================
"""
from contextlib import contextmanager
import hashlib
import os
import posixpath
import tempfile
from fabric.api import (
env,
hide,
output,
settings,
sudo,
)
from fabric.operations import (
_AttributeString,
_execute,
_prefix_commands,
_prefix_env_vars,
_shell_wrap,
_sudo_prefix,
)
from fabric.state import default_channel
from fabric.utils import error
import fabric.operations
import fabric.sftp
from fabric.context_managers import (
quiet as quiet_manager,
warn_only as warn_only_manager,
)
@contextmanager
def guest(name_or_ctid):
"""
Context manager to run commands inside a guest container.
Supported basic operations are: `run`_, `sudo`_ and `put`_.
.. warning:: commands executed with ``run()`` will be run as
**root** inside the container.
Use ``sudo(command, user='foo')`` to run them as
an unpriviledged user.
Example::
from fabtools.openvz import guest
with guest('foo'):
run('hostname')
sudo('whoami', user='alice')
put('files/hello.txt')
.. _run: http://docs.fabfile.org/en/1.4.3/api/core/operations.html#fabric.operations.run
.. _sudo: http://docs.fabfile.org/en/1.4.3/api/core/operations.html#fabric.operations.sudo
.. _put: http://docs.fabfile.org/en/1.4.3/api/core/operations.html#fabric.operations.put
"""
# Monkey patch fabric operations
_orig_run_command = fabric.operations._run_command
_orig_put = fabric.sftp.SFTP.put
def run_guest_command(command, shell=True, pty=True, combine_stderr=True,
sudo=False, user=None, quiet=False, warn_only=False, stdout=None,
stderr=None, group=None, timeout=None):
"""
Run command inside a guest container
"""
# Use a non-login shell
_orig_shell = env.shell
env.shell = '/bin/bash -c'
# Use double quotes for the sudo prompt
_orig_sudo_prefix = env.sudo_prefix
env.sudo_prefix = 'sudo -S -p "%(sudo_prompt)s" '
# Try to cd to the user's home directory for consistency,
# as the default directory is "/" with "vzctl exec2"
if not env.cwd:
env.command_prefixes.insert(0, 'cd 2>/dev/null || true')
# Build the guest command
guest_command = _shell_wrap_inner(
_prefix_commands(_prefix_env_vars(command), 'remote'),
True,
_sudo_prefix(user) if sudo and user else None
)
host_command = "vzctl exec2 %s '%s'" % (name_or_ctid, guest_command)
# Restore env
env.shell = _orig_shell
env.sudo_prefix = _orig_sudo_prefix
if not env.cwd:
env.command_prefixes.pop(0)
# Run host command as root
return _run_host_command(host_command, shell=shell, pty=pty,
combine_stderr=combine_stderr)
def put_guest(self, local_path, remote_path, use_sudo, mirror_local_mode,
mode, local_is_path):
"""
Upload file to a guest container
"""
pre = self.ftp.getcwd()
pre = pre if pre else ''
if local_is_path and self.isdir(remote_path):
basename = os.path.basename(local_path)
remote_path = posixpath.join(remote_path, basename)
if output.running:
print(("[%s] put: %s -> %s" % (
env.host_string,
local_path if local_is_path else '<file obj>',
posixpath.join(pre, remote_path)
)))
# Have to bounce off FS if doing file-like objects
fd, real_local_path = None, local_path
if not local_is_path:
fd, real_local_path = tempfile.mkstemp()
old_pointer = local_path.tell()
local_path.seek(0)
file_obj = os.fdopen(fd, 'wb')
file_obj.write(local_path.read())
file_obj.close()
local_path.seek(old_pointer)
# Use temporary file with a unique name on the host machine
guest_path = remote_path
hasher = hashlib.sha1()
hasher.update(env.host_string)
hasher.update(name_or_ctid)
hasher.update(guest_path)
host_path = hasher.hexdigest()
# Upload the file to host machine
rattrs = self.ftp.put(real_local_path, host_path)
# Copy file to the guest container
with settings(hide('everything'), cwd=""):
cmd = "cat \"%s\" | vzctl exec \"%s\" 'cat - > \"%s\"'" \
% (host_path, name_or_ctid, guest_path)
_orig_run_command(cmd, sudo=True)
# Revert to original remote_path for return value's sake
remote_path = guest_path
# Clean up
if not local_is_path:
os.remove(real_local_path)
# Handle modes if necessary
if (local_is_path and mirror_local_mode) or (mode is not None):
lmode = os.stat(local_path).st_mode if mirror_local_mode else mode
lmode = lmode & 0o7777
rmode = rattrs.st_mode & 0o7777
if lmode != rmode:
with hide('everything'):
sudo('chmod %o \"%s\"' % (lmode, remote_path))
return remote_path
fabric.operations._run_command = run_guest_command
fabric.sftp.SFTP.put = put_guest
yield
# Monkey unpatch
fabric.operations._run_command = _orig_run_command
fabric.sftp.SFTP.put = _orig_put
@contextmanager
def _noop():
yield
def _run_host_command(command, shell=True, pty=True, combine_stderr=True,
quiet=False, warn_only=False, stdout=None, stderr=None, timeout=None):
"""
Run host wrapper command as root
(Modified from fabric.operations._run_command to ignore prefixes,
path(), cd(), and always use sudo.)
"""
manager = _noop
if warn_only:
manager = warn_only_manager
# Quiet's behavior is a superset of warn_only's, so it wins.
if quiet:
manager = quiet_manager
with manager():
# Set up new var so original argument can be displayed verbatim later.
given_command = command
# Handle context manager modifications, and shell wrapping
wrapped_command = _shell_wrap(
command, # !! removed _prefix_commands() & _prefix_env_vars()
shell,
_sudo_prefix(None) # !! always use sudo
)
# Execute info line
which = 'sudo' # !! always use sudo
if output.debug:
print(("[%s] %s: %s" % (env.host_string, which, wrapped_command)))
elif output.running:
print(("[%s] %s: %s" % (env.host_string, which, given_command)))
# Actual execution, stdin/stdout/stderr handling, and termination
result_stdout, result_stderr, status = _execute(
channel=default_channel(), command=wrapped_command, pty=pty,
combine_stderr=combine_stderr, invoke_shell=False, stdout=stdout,
stderr=stderr, timeout=timeout)
# Assemble output string
out = _AttributeString(result_stdout)
err = _AttributeString(result_stderr)
# Error handling
out.failed = False
out.command = given_command
out.real_command = wrapped_command
if status not in env.ok_ret_codes:
out.failed = True
msg = "%s() received nonzero return code %s while executing" % (
which, status
)
if env.warn_only:
msg += " '%s'!" % given_command
else:
msg += "!\n\nRequested: %s\nExecuted: %s" % (
given_command, wrapped_command
)
error(message=msg, stdout=out, stderr=err)
# Attach return code to output string so users who have set things to
# warn only, can inspect the error code.
out.return_code = status
# Convenience mirror of .failed
out.succeeded = not out.failed
# Attach stderr for anyone interested in that.
out.stderr = err
return out
def _shell_wrap_inner(command, shell=True, sudo_prefix=None):
"""
Conditionally wrap given command in env.shell (while honoring sudo.)
(Modified from fabric.operations._shell_wrap to avoid double escaping,
as the wrapping host command would also get shell escaped.)
"""
# Honor env.shell, while allowing the 'shell' kwarg to override it (at
# least in terms of turning it off.)
if shell and not env.use_shell:
shell = False
# Sudo plus space, or empty string
if sudo_prefix is None:
sudo_prefix = ""
else:
sudo_prefix += " "
# If we're shell wrapping, prefix shell and space, escape the command and
# then quote it. Otherwise, empty string.
if shell:
shell = env.shell + " "
command = '"%s"' % command # !! removed _shell_escape() here
else:
shell = ""
# Resulting string should now have correct formatting
return sudo_prefix + shell + command
| bsd-2-clause |
Mozlite/Mozlite.Core | Mozlite.Core/Data/Query/Translators/RelationalCompositeMethodCallTranslator.cs | 1993 | using System.Collections.Generic;
using System.Linq.Expressions;
using Microsoft.Extensions.Logging;
using Mozlite.Data.Query.Translators.Internal;
using System.Linq;
namespace Mozlite.Data.Query.Translators
{
/// <summary>
/// 方法调用转换实现基类。
/// </summary>
public abstract class RelationalCompositeMethodCallTranslator : IMethodCallTranslator
{
private readonly List<IMethodCallTranslator> _translators;
/// <summary>
/// 初始化类<see cref="RelationalCompositeMethodCallTranslator"/>。
/// </summary>
/// <param name="loggerFactory">日志工厂接口。</param>
protected RelationalCompositeMethodCallTranslator([NotNull] ILoggerFactory loggerFactory)
{
_translators = new List<IMethodCallTranslator>
{
new ContainsTranslator(),
new EndsWithTranslator(),
new EqualsTranslator(),
new StartsWithTranslator(),
new IsNullOrEmptyTranslator(),
new InTranslator(),
};
}
/// <summary>
/// 转换表达式。
/// </summary>
/// <param name="methodCallExpression">方法调用表达式。</param>
/// <returns>返回转换后的表达式。</returns>
public virtual Expression Translate(MethodCallExpression methodCallExpression)
{
return
_translators
.Select(translator => translator.Translate(methodCallExpression))
.FirstOrDefault(translatedMethodCall => translatedMethodCall != null);
}
/// <summary>
/// 添加转换类型。
/// </summary>
/// <param name="translators">转换类型列表。</param>
protected virtual void AddTranslators([NotNull] IEnumerable<IMethodCallTranslator> translators)
{
_translators.InsertRange(0, translators);
}
}
} | bsd-2-clause |
jayArnel/crimemapping | crimeprediction/migrations/0004_auto_20160429_0717.py | 586 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-29 07:17
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('crimeprediction', '0003_auto_20160406_1610'),
]
operations = [
migrations.RemoveField(
model_name='crimesample',
name='crime',
),
migrations.RemoveField(
model_name='crimesample',
name='grids',
),
migrations.DeleteModel(
name='CrimeSample',
),
]
| bsd-2-clause |
ibrarahmad/cstore | src/Wrappers/DictCPUDataSource.h | 3425 | /* Copyright (c) 2005, Regents of Massachusetts Institute of Technology,
* Brandeis University, Brown University, and University of Massachusetts
* Boston. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of Massachusetts Institute of Technology,
* Brandeis University, Brown University, or University of
* Massachusetts Boston nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Dictionary DataSource
// Problems: [email protected]
#ifndef _DICTCPUDATASOURCE_H_
#define _DICTCPUDATASOURCE_H_
#include "IntDataSource.h"
#include "Decoder/IntDecoder.h"
#include "Decoder/DictByteDecoder.h"
#include "Decoder/DictDelayedDecoder.h"
#include "Decoder/ShortCutDictDelayedDecoder.h"
#include "Decoder/DictMultiDecoder.h"
class DictCPUDataSource : public IntDataSource
{
public:
// Construct a datasource that :
// -access data through am_
// -writes blocks using writer_
DictCPUDataSource(AM* dictTableAM_, AM* entriesAM_, bool valSorted_);
// Copy constructor
DictCPUDataSource(const DictCPUDataSource&);
// Destructor
virtual ~DictCPUDataSource();
void setDecodingType(int type);
/*
// Gets the next value block from the operator
virtual Block* getNextValBlock(int colIndex_);
// Skips to the first block with this value
// Returns NULL if the value is outside the range of the column
virtual Block* skipToValBlock(int colIndex_, int val_);
// Gets the next position block (bitstring of positions) from the operator
virtual PosBlock* getNextPosBlock(int colIndex_);
// Skips to the first block with this position
// Returns NULL if the value is outside the range of the column
virtual PosBlock* skipToPosBlock(int colIndex_, int pos_);
protected:
void initTable();
bool checkOutBlock();
AM* dictTableAM;
AM* entriesAM;
bool valSorted;
bool init;
BitDecoder* bitDecoder;
IntDecoder* intDecoder;
BasicBlock* outBlock;
map<unsigned int, unsigned int> entryValueMap;
*/
AM* dictTableAM;
};
#endif //_DICTCPUDATASOURCE_H_
| bsd-2-clause |
dbcode/protobuf-nginx | protongx/ngx_size.cc | 12102 | #include <ngx_flags.h>
#include <ngx_generator.h>
#include <google/protobuf/descriptor.pb.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace nginx {
void
Generator::GenerateSize(const Descriptor* desc, io::Printer& printer)
{
std::map<std::string, std::string> vars;
vars["name"] = desc->full_name();
vars["root"] = TypedefRoot(desc->full_name());
vars["type"] = StructType(desc->full_name());
// statics for packed field size calcs. this is independent of field
// number and just calculates the payload size (of the actual data).
for (int i = 0; i < desc->field_count(); ++i) {
const FieldDescriptor *field = desc->field(i);
if (field->is_packable() && field->options().packed()) {
bool fixed = false;
vars["ffull"] = field->full_name();
vars["fname"] = field->name();
vars["ftype"] = FieldRealType(field);
printer.Print(vars,
"static size_t\n"
"$root$_$fname$__packed_size(ngx_array_t *a)\n"
"{\n");
Indent(printer);
switch (field->type()) {
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_FLOAT:
printer.Print("return (a && a->nelts > 0) ? a->nelts * 4 : 0;\n");
fixed = true;
break;
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
case FieldDescriptor::TYPE_DOUBLE:
printer.Print("return (a && a->nelts > 0) ? a->nelts * 8 : 0;\n");
fixed = true;
break;
default:
// continue with the codegen
break;
}
if (!fixed) {
printer.Print(vars,
"size_t size = 0;\n"
"ngx_uint_t i;\n"
"$ftype$ *fptr;\n"
"\n");
SimpleIf(printer, vars,
"a != NULL && a->nelts > 0");
printer.Print(vars,
"fptr = a->elts;\n"
"for (i = 0; i < a->nelts; ++i) {\n");
Indent(printer);
switch (field->type()) {
case FieldDescriptor::TYPE_BOOL:
case FieldDescriptor::TYPE_ENUM:
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_INT32:
printer.Print("size += ngx_protobuf_size_uint32(fptr[i]);\n");
break;
case FieldDescriptor::TYPE_SINT32:
printer.Print("size += ngx_protobuf_size_sint32(fptr[i]);\n");
break;
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_INT64:
printer.Print("size += ngx_protobuf_size_uint32(fptr[i]);\n");
break;
case FieldDescriptor::TYPE_SINT64:
printer.Print("size += ngx_protobuf_size_sint64(fptr[i]);\n");
break;
default:
printer.Print(vars,
"#error $ffull$ cannot be a packed field");
break;
}
CloseBrace(printer);
CloseBrace(printer);
printer.Print("\n"
"return size;\n");
}
CloseBrace(printer);
printer.Print("\n");
}
}
printer.Print(vars,
"size_t\n"
"$root$__size(\n"
" $type$ *obj)\n"
"{\n");
Indent(printer);
Flags flags(desc);
bool iterates = false;
for (int i = 0; i < desc->field_count(); ++i) {
const FieldDescriptor *field = desc->field(i);
if (field->is_repeated() && !IsFixedWidth(field) &&
!(field->is_packable() && field->options().packed())) {
iterates = true;
break;
}
}
printer.Print("size_t size = 0;\n");
if (flags.has_packed() || flags.has_message()) {
printer.Print("size_t n;\n");
}
if (iterates || HasUnknownFields(desc)) {
// we need to iterate any repeated non-fixed field or unknown fields
printer.Print("ngx_uint_t i;\n");
}
printer.Print("\n");
for (int i = 0; i < desc->field_count(); ++i) {
const FieldDescriptor *field = desc->field(i);
vars["fname"] = field->name();
vars["ftype"] = FieldRealType(field);
vars["fnum"] = Number(field->number());
if (field->is_repeated()) {
CuddledIf(printer, vars,
"obj->__has_$fname$",
"&& obj->$fname$ != NULL\n"
"&& obj->$fname$->nelts > 0");
if (field->is_packable() && field->options().packed()) {
printer.Print(vars,
"n = $root$_$fname$__packed_size(\n");
Indented(printer, vars, "obj->$fname$);\n");
printer.Print("\n");
printer.Print(vars,
"size += ngx_protobuf_size_message_field(n, $fnum$);\n");
} else if (IsFixedWidth(field)) {
// size calculation of a non-packed repeated fixed-width field
switch (field->type()) {
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_FLOAT:
printer.Print(vars,
"size += obj->$fname$->nelts *\n"
" ngx_protobuf_size_fixed32_field($fnum$);\n");
break;
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
case FieldDescriptor::TYPE_DOUBLE:
printer.Print(vars,
"size += obj->$fname$->nelts *\n"
" ngx_protobuf_size_fixed64_field($fnum$);\n");
break;
default:
break;
}
} else {
// size calculation of a non-packed repeated non-fixed width field
printer.Print(vars,
"$ftype$ *vals = obj->$fname$->elts;\n"
"\n"
"for (i = 0; i < obj->$fname$->nelts; ++i) {\n");
Indent(printer);
switch (field->type()) {
case FieldDescriptor::TYPE_MESSAGE:
vars["froot"] = TypedefRoot(field->message_type()->full_name());
printer.Print(vars,
"n = $froot$__size(vals + i);\n"
"size += ngx_protobuf_size_message_field("
"n, $fnum$);\n");
break;
case FieldDescriptor::TYPE_BYTES:
case FieldDescriptor::TYPE_STRING:
printer.Print(vars,
"size += ngx_protobuf_size_string_field("
"vals + i, $fnum$);\n");
break;
case FieldDescriptor::TYPE_BOOL:
printer.Print(vars,
"size += ngx_protobuf_size_uint32_field("
"(vals[i] != 0), $fnum$);\n");
break;
case FieldDescriptor::TYPE_ENUM:
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_INT32:
printer.Print(vars,
"size += ngx_protobuf_size_uint32_field("
"vals[i], $fnum$);\n");
break;
case FieldDescriptor::TYPE_SINT32:
printer.Print(vars,
"size += ngx_protobuf_size_sint32_field("
"vals[i], $fnum$);\n");
break;
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_INT64:
printer.Print(vars,
"size += ngx_protobuf_size_uint64_field("
"vals[i], $fnum$);\n");
break;
case FieldDescriptor::TYPE_SINT64:
printer.Print(vars,
"size += ngx_protobuf_size_sint64_field("
"vals[i], $fnum$);\n");
break;
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_FLOAT:
printer.Print(vars,
"size += ngx_protobuf_size_fixed32_field($fnum$);\n");
break;
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
case FieldDescriptor::TYPE_DOUBLE:
printer.Print(vars,
"size += ngx_protobuf_size_fixed64_field($fnum$);\n");
break;
default:
printer.Print(vars,
"size += FIXME; /* size $ftype$ */\n");
break;
}
Outdent(printer);
printer.Print("}\n");
}
Outdent(printer);
printer.Print("}\n");
} else {
switch (field->type()) {
case FieldDescriptor::TYPE_MESSAGE:
vars["froot"] = TypedefRoot(field->message_type()->full_name());
FullCuddledIf(printer, vars,
"obj->__has_$fname$",
"&& obj->$fname$ != NULL",
"n = $froot$__size(obj->$fname$);\n"
"size += ngx_protobuf_size_message_field(n, $fnum$);");
break;
case FieldDescriptor::TYPE_BYTES:
case FieldDescriptor::TYPE_STRING:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_string_field("
"&obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_BOOL:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_uint32_field("
"(obj->$fname$ != 0), $fnum$);");
break;
case FieldDescriptor::TYPE_ENUM:
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_INT32:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_uint32_field("
"obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_SINT32:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_sint32_field("
"obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_INT64:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_uint64_field("
"obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_SINT64:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_sint64_field("
"obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_FLOAT:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_fixed32_field($fnum$);");
break;
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
case FieldDescriptor::TYPE_DOUBLE:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_fixed64_field($fnum$);");
break;
default:
printer.Print(vars,
"size += FIXME; /* size $ftype$ */\n");
break;
}
}
}
if (desc->extension_range_count() > 0) {
FullSimpleIf(printer, vars,
"obj->__extensions != NULL",
"size += ngx_protobuf_size_extensions(obj->__extensions);");
}
if (HasUnknownFields(desc)) {
printer.Print("\n");
CuddledIf(printer, vars,
"obj->__unknown != NULL",
"&& obj->__unknown->elts != NULL\n"
"&& obj->__unknown->nelts > 0");
printer.Print("ngx_protobuf_unknown_field_t *unk = "
"obj->__unknown->elts;\n"
"\n"
"for (i = 0; i < obj->__unknown->nelts; ++i) ");
OpenBrace(printer);
printer.Print("size += ngx_protobuf_size_unknown_field(unk + i);\n");
CloseBrace(printer);
CloseBrace(printer);
}
printer.Print("\n"
"return size;\n");
CloseBrace(printer);
printer.Print("\n");
}
} // namespace nginx
} // namespace compiler
} // namespace protobuf
} // namespace google
| bsd-2-clause |
dshadowwolf/config-general | t/29-test-allowsinglequoteinterpolation.js | 416 | var tap = require('tap'),
plan = tap.plan,
test = tap.test,
parser = require('../index');
var cfg53 = new parser.parser( { String: "got = 1\nhave = '$got'", InterPolateVars: true, AllowSingleQuoteInterpolation: true } );
var hash53 = cfg53.getall();
test("test AllowSingleQuoteInterpolation", function(t) {
t.plan(1);
t.is(hash53.have,"'1'", "check AllowSingleQuoteInterpolation" );
t.end();
});
| bsd-2-clause |
gapry/refos | libs/libmuslc/src/math/expm1.c | 7529 | /* @LICENSE(MUSLC_MIT) */
/* origin: FreeBSD /usr/src/lib/msun/src/s_expm1.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* expm1(x)
* Returns exp(x)-1, the exponential of x minus 1.
*
* Method
* 1. Argument reduction:
* Given x, find r and integer k such that
*
* x = k*ln2 + r, |r| <= 0.5*ln2 ~ 0.34658
*
* Here a correction term c will be computed to compensate
* the error in r when rounded to a floating-point number.
*
* 2. Approximating expm1(r) by a special rational function on
* the interval [0,0.34658]:
* Since
* r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 - r^4/360 + ...
* we define R1(r*r) by
* r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 * R1(r*r)
* That is,
* R1(r**2) = 6/r *((exp(r)+1)/(exp(r)-1) - 2/r)
* = 6/r * ( 1 + 2.0*(1/(exp(r)-1) - 1/r))
* = 1 - r^2/60 + r^4/2520 - r^6/100800 + ...
* We use a special Reme algorithm on [0,0.347] to generate
* a polynomial of degree 5 in r*r to approximate R1. The
* maximum error of this polynomial approximation is bounded
* by 2**-61. In other words,
* R1(z) ~ 1.0 + Q1*z + Q2*z**2 + Q3*z**3 + Q4*z**4 + Q5*z**5
* where Q1 = -1.6666666666666567384E-2,
* Q2 = 3.9682539681370365873E-4,
* Q3 = -9.9206344733435987357E-6,
* Q4 = 2.5051361420808517002E-7,
* Q5 = -6.2843505682382617102E-9;
* z = r*r,
* with error bounded by
* | 5 | -61
* | 1.0+Q1*z+...+Q5*z - R1(z) | <= 2
* | |
*
* expm1(r) = exp(r)-1 is then computed by the following
* specific way which minimize the accumulation rounding error:
* 2 3
* r r [ 3 - (R1 + R1*r/2) ]
* expm1(r) = r + --- + --- * [--------------------]
* 2 2 [ 6 - r*(3 - R1*r/2) ]
*
* To compensate the error in the argument reduction, we use
* expm1(r+c) = expm1(r) + c + expm1(r)*c
* ~ expm1(r) + c + r*c
* Thus c+r*c will be added in as the correction terms for
* expm1(r+c). Now rearrange the term to avoid optimization
* screw up:
* ( 2 2 )
* ({ ( r [ R1 - (3 - R1*r/2) ] ) } r )
* expm1(r+c)~r - ({r*(--- * [--------------------]-c)-c} - --- )
* ({ ( 2 [ 6 - r*(3 - R1*r/2) ] ) } 2 )
* ( )
*
* = r - E
* 3. Scale back to obtain expm1(x):
* From step 1, we have
* expm1(x) = either 2^k*[expm1(r)+1] - 1
* = or 2^k*[expm1(r) + (1-2^-k)]
* 4. Implementation notes:
* (A). To save one multiplication, we scale the coefficient Qi
* to Qi*2^i, and replace z by (x^2)/2.
* (B). To achieve maximum accuracy, we compute expm1(x) by
* (i) if x < -56*ln2, return -1.0, (raise inexact if x!=inf)
* (ii) if k=0, return r-E
* (iii) if k=-1, return 0.5*(r-E)-0.5
* (iv) if k=1 if r < -0.25, return 2*((r+0.5)- E)
* else return 1.0+2.0*(r-E);
* (v) if (k<-2||k>56) return 2^k(1-(E-r)) - 1 (or exp(x)-1)
* (vi) if k <= 20, return 2^k((1-2^-k)-(E-r)), else
* (vii) return 2^k(1-((E+2^-k)-r))
*
* Special cases:
* expm1(INF) is INF, expm1(NaN) is NaN;
* expm1(-INF) is -1, and
* for finite argument, only expm1(0)=0 is exact.
*
* Accuracy:
* according to an error analysis, the error is always less than
* 1 ulp (unit in the last place).
*
* Misc. info.
* For IEEE double
* if x > 7.09782712893383973096e+02 then expm1(x) overflow
*
* Constants:
* The hexadecimal values are the intended ones for the following
* constants. The decimal values may be used, provided that the
* compiler will convert from decimal to binary accurately enough
* to produce the hexadecimal values shown.
*/
#include "libm.h"
static const double
huge = 1.0e+300,
tiny = 1.0e-300,
o_threshold = 7.09782712893383973096e+02, /* 0x40862E42, 0xFEFA39EF */
ln2_hi = 6.93147180369123816490e-01, /* 0x3fe62e42, 0xfee00000 */
ln2_lo = 1.90821492927058770002e-10, /* 0x3dea39ef, 0x35793c76 */
invln2 = 1.44269504088896338700e+00, /* 0x3ff71547, 0x652b82fe */
/* Scaled Q's: Qn_here = 2**n * Qn_above, for R(2*z) where z = hxs = x*x/2: */
Q1 = -3.33333333333331316428e-02, /* BFA11111 111110F4 */
Q2 = 1.58730158725481460165e-03, /* 3F5A01A0 19FE5585 */
Q3 = -7.93650757867487942473e-05, /* BF14CE19 9EAADBB7 */
Q4 = 4.00821782732936239552e-06, /* 3ED0CFCA 86E65239 */
Q5 = -2.01099218183624371326e-07; /* BE8AFDB7 6E09C32D */
double expm1(double x)
{
double y,hi,lo,c,t,e,hxs,hfx,r1,twopk;
int32_t k,xsb;
uint32_t hx;
GET_HIGH_WORD(hx, x);
xsb = hx&0x80000000; /* sign bit of x */
hx &= 0x7fffffff; /* high word of |x| */
/* filter out huge and non-finite argument */
if (hx >= 0x4043687A) { /* if |x|>=56*ln2 */
if (hx >= 0x40862E42) { /* if |x|>=709.78... */
if (hx >= 0x7ff00000) {
uint32_t low;
GET_LOW_WORD(low, x);
if (((hx&0xfffff)|low) != 0) /* NaN */
return x+x;
return xsb==0 ? x : -1.0; /* exp(+-inf)={inf,-1} */
}
if(x > o_threshold)
return huge*huge; /* overflow */
}
if (xsb != 0) { /* x < -56*ln2, return -1.0 with inexact */
/* raise inexact */
if(x+tiny<0.0)
return tiny-1.0; /* return -1 */
}
}
/* argument reduction */
if (hx > 0x3fd62e42) { /* if |x| > 0.5 ln2 */
if (hx < 0x3FF0A2B2) { /* and |x| < 1.5 ln2 */
if (xsb == 0) {
hi = x - ln2_hi;
lo = ln2_lo;
k = 1;
} else {
hi = x + ln2_hi;
lo = -ln2_lo;
k = -1;
}
} else {
k = invln2*x + (xsb==0 ? 0.5 : -0.5);
t = k;
hi = x - t*ln2_hi; /* t*ln2_hi is exact here */
lo = t*ln2_lo;
}
STRICT_ASSIGN(double, x, hi - lo);
c = (hi-x)-lo;
} else if (hx < 0x3c900000) { /* |x| < 2**-54, return x */
/* raise inexact flags when x != 0 */
t = huge+x;
return x - (t-(huge+x));
} else
k = 0;
/* x is now in primary range */
hfx = 0.5*x;
hxs = x*hfx;
r1 = 1.0+hxs*(Q1+hxs*(Q2+hxs*(Q3+hxs*(Q4+hxs*Q5))));
t = 3.0-r1*hfx;
e = hxs*((r1-t)/(6.0 - x*t));
if (k == 0) /* c is 0 */
return x - (x*e-hxs);
INSERT_WORDS(twopk, 0x3ff00000+(k<<20), 0); /* 2^k */
e = x*(e-c) - c;
e -= hxs;
if (k == -1)
return 0.5*(x-e) - 0.5;
if (k == 1) {
if (x < -0.25)
return -2.0*(e-(x+0.5));
return 1.0+2.0*(x-e);
}
if (k <= -2 || k > 56) { /* suffice to return exp(x)-1 */
y = 1.0 - (e-x);
if (k == 1024)
y = y*2.0*0x1p1023;
else
y = y*twopk;
return y - 1.0;
}
t = 1.0;
if (k < 20) {
SET_HIGH_WORD(t, 0x3ff00000 - (0x200000>>k)); /* t=1-2^-k */
y = t-(e-x);
y = y*twopk;
} else {
SET_HIGH_WORD(t, ((0x3ff-k)<<20)); /* 2^-k */
y = x-(e+t);
y += 1.0;
y = y*twopk;
}
return y;
}
| bsd-2-clause |
DeforaOS/libc | include/kernel/openbsd/errno.h | 2407 | /* $Id$ */
/* Copyright (c) 2007-2016 Pierre Pronchery <[email protected]> */
/* This file is part of DeforaOS System libc */
/* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef LIBC_KERNEL_OPENBSD_ERRNO_H
# define LIBC_KERNEL_OPENBSD_ERRNO_H
/* constants */
# define EPERM 1
# define ENOENT 2
# define ESRCH 3
# define EINTR 4
# define EIO 5
# define ENXIO 6
# define E2BIG 7
# define ENOEXEC 8
# define EBADF 9
# define ECHILD 10
# define ENOMEM 12
# define EACCES 13
# define EFAULT 14
# define EBUSY 16
# define EEXIST 17
# define EXDEV 18
# define ENODEV 19
# define ENOTDIR 20
# define EISDIR 21
# define EINVAL 22
# define ENOTTY 25
# define ENOSPC 28
# define ESPIPE 29
# define EROFS 30
# define EPIPE 32
# define EDOM 33
# define ERANGE 34
# define EAGAIN 35
# define EINPROGRESS 36
# define EOPNOTSUPP 45
# define EAFNOSUPPORT 47
# define EADDRINUSE 48
# define EADDRNOTAVAIL 49
# define ENOBUFS 55
# define ETIMEDOUT 60
# define ECONNREFUSED 61
# define ELOOP 62
# define ENOTEMPTY 66
# define ENOSYS 78
# define ENOTSUP 91
#endif /* !LIBC_KERNEL_OPENBSD_ERRNO_H */
| bsd-2-clause |
simphony/simphony-lammps-md | simlammps/io/tests/test_lammps_simple_data_handler.py | 2811 | import unittest
import tempfile
import shutil
import os
from simlammps.io.lammps_data_file_parser import LammpsDataFileParser
from simlammps.io.lammps_simple_data_handler import LammpsSimpleDataHandler
class TestLammpsSimpleDataHandler(unittest.TestCase):
""" Tests the data reader class
"""
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.handler = LammpsSimpleDataHandler()
self.parser = LammpsDataFileParser(handler=self.handler)
self.filename = os.path.join(self.temp_dir, "test_data.txt")
_write_example_file(self.filename, _data_file_contents)
def tear_down(self):
shutil.rmtree(self.temp_dir)
def test_number_atom_types(self):
self.parser.parse(self.filename)
self.assertEqual(3, self.handler.get_number_atom_types())
def test_masses(self):
self.parser.parse(self.filename)
masses = self.handler.get_masses()
self.assertEqual(len(masses), self.handler.get_number_atom_types())
self.assertEqual(masses[1], 3)
self.assertEqual(masses[2], 42)
self.assertEqual(masses[3], 1)
def test_atoms(self):
self.parser.parse(self.filename)
atoms = self.handler.get_atoms()
for i in range(1, 4):
self.assertTrue(i in atoms)
self.assertEqual(atoms[i][1:4], [i * 1.0, i * 1.0, i * 1.0])
def test_velocities(self):
self.parser.parse(self.filename)
velocities = self.handler.get_velocities()
for i in range(1, 4):
self.assertTrue(i in velocities)
self.assertEqual(velocities[i], [i * 1.0, i * 1.0, i * 1.0])
def _write_example_file(filename, contents):
with open(filename, "w") as text_file:
text_file.write(contents)
_data_file_contents = """LAMMPS data file via write_data, version 28 Jun 2014, timestep = 0
4 atoms
3 atom types
0.0000000000000000e+00 2.5687134504920127e+01 xlo xhi
-2.2245711031688635e-03 2.2247935602791809e+01 ylo yhi
-3.2108918131150160e-01 3.2108918131150160e-01 zlo zhi
Masses
1 3
2 42
3 1
Pair Coeffs # lj/cut
1 1 1
2 1 1
3 1 1
Atoms # atomic
1 1 1.0000000000000000e+00 1.0000000000000000e+00 1.0000000000000000e+00 0 0 0
2 2 2.0000000000000000e+00 2.0000000000000000e+00 2.0000000000000000e+00 0 0 0
3 3 3.0000000000000000e+00 3.0000000000000000e+00 3.0000000000000000e+00 0 0 0
4 2 4.0000000000000000e+00 4.0000000000000000e+00 4.0000000000000000e+00 0 0 0
Velocities
1 1.0000000000000000e+00 1.0000000000000000e+00 1.0000000000000000e+00
2 2.0000000000000000e+00 2.0000000000000000e+00 2.0000000000000000e+00
3 3.0000000000000000e+00 3.0000000000000000e+00 3.0000000000000000e+00
4 4.0000000000000000e+00 4.0000000000000000e+00 4.0000000000000000e+00"""
if __name__ == '__main__':
unittest.main()
| bsd-2-clause |
sjkingo/django-breadcrumbs3 | breadcrumbs3/middleware.py | 2010 | from django.conf import settings
class Breadcrumb(object):
"""
A single breadcrumb, which is a 1:1 mapping to a view.
This is simply a wrapper class for the template tag.
"""
def __init__(self, name, url):
self.name = name
self.url = url
class Breadcrumbs(object):
"""
The site's breadcrumbs. An instance of this class is added to each
request, and can be called to add breadcrumbs to the template context.
def some_view(request):
request.breadcrumbs('Title', request.path_info)
request.breadcrumbs('Subtitle', ...)
...
You may prevent the 'Home' link being added by setting BREADCRUMBS_ADD_HOME
to False (defaults to True).
This class supports iteration, and is used as such in the template tag.
"""
_bc = []
def __init__(self, request):
self._request = request
# We must clear the list on every request or we will get duplicates
del self._bc[:]
# By default, add a link to the homepage. This can be disabled or
# configured in the project settings.
if getattr(settings, 'BREADCRUMBS_HOME_LINK', True):
home_name = getattr(settings, 'BREADCRUMBS_HOME_LINK_NAME', 'Home')
home_url = getattr(settings, 'BREADCRUMBS_HOME_LINK_URL', '/')
self._add(home_name, home_url)
def __call__(self, *args, **kwargs):
return self._add(*args, **kwargs)
def __iter__(self):
return iter(self._bc)
def __len__(self):
return len(self._bc)
def _add(self, name, url):
self._bc.append(Breadcrumb(name, url))
class BreadcrumbMiddleware(object):
"""
Middleware to add breadcrumbs into every request.
Add 'breadcrumbs3.middleware.BreadcrumbMiddleware' to MIDDLEWARE_CLASSES
and make sure 'django.template.context_processors.request' is in
TEMPLATES.context_processors.
"""
def process_request(self, request):
request.breadcrumbs = Breadcrumbs(request)
| bsd-2-clause |
Pillowdrift/MegaDrillerMole | MegaDrillerMole/MDMWorkspace/DrillerGameAndroid/src/com/pillowdrift/drillergame/entities/menu/buttons/RecordsMenuButton.java | 600 | package com.pillowdrift.drillergame.entities.menu.buttons;
import com.pillowdrift.drillergame.framework.Scene;
/**
* Button to take you to the RecordsScene
* @author cake_cruncher_7
*
*/
public class RecordsMenuButton extends GenericMenuButton
{
//CONSTRUCTION
public RecordsMenuButton(Scene parent) {
super(parent, "Hi-Scores");
}
//FUNCTION
@Override
protected void onRelease()
{
super.onRelease();
//Activate the records scene
_parent.getOwner().getScene("RecordsScene").activate();
//Deactivate our parent scene
_parent.deactivate();
}
}
| bsd-2-clause |
open-dis/DISTutorial | javadoc/edu/nps/moves/dis/VectoringNozzleSystemData.html | 19015 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0) on Mon Jan 09 14:28:37 PST 2017 -->
<title>VectoringNozzleSystemData</title>
<meta name="date" content="2017-01-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="VectoringNozzleSystemData";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../edu/nps/moves/dis/Vector3Float.html" title="class in edu.nps.moves.dis"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../edu/nps/moves/dis/WarfareFamilyPdu.html" title="class in edu.nps.moves.dis"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?edu/nps/moves/dis/VectoringNozzleSystemData.html" target="_top">Frames</a></li>
<li><a href="VectoringNozzleSystemData.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">edu.nps.moves.dis</div>
<h2 title="Class VectoringNozzleSystemData" class="title">Class VectoringNozzleSystemData</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>edu.nps.moves.dis.VectoringNozzleSystemData</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable</dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">VectoringNozzleSystemData</span>
extends java.lang.Object
implements java.io.Serializable</pre>
<div class="block">Data about a vectoring nozzle system
Copyright (c) 2008-2016, MOVES Institute, Naval Postgraduate School. All rights reserved.
This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>DMcG</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../serialized-form.html#edu.nps.moves.dis.VectoringNozzleSystemData">Serialized Form</a></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected float</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#horizontalDeflectionAngle">horizontalDeflectionAngle</a></span></code>
<div class="block">horizontal deflection angle</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected float</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#verticalDeflectionAngle">verticalDeflectionAngle</a></span></code>
<div class="block">vertical deflection angle</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#VectoringNozzleSystemData--">VectoringNozzleSystemData</a></span>()</code>
<div class="block">Constructor</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#equals-java.lang.Object-">equals</a></span>(java.lang.Object obj)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#equalsImpl-java.lang.Object-">equalsImpl</a></span>(java.lang.Object obj)</code>
<div class="block">Compare all fields that contribute to the state, ignoring
transient and static fields, for <code>this</code> and the supplied object</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>float</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#getHorizontalDeflectionAngle--">getHorizontalDeflectionAngle</a></span>()</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#getMarshalledSize--">getMarshalledSize</a></span>()</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>float</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#getVerticalDeflectionAngle--">getVerticalDeflectionAngle</a></span>()</code> </td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#marshal-java.nio.ByteBuffer-">marshal</a></span>(java.nio.ByteBuffer buff)</code>
<div class="block">Packs a Pdu into the ByteBuffer.</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#marshal-java.io.DataOutputStream-">marshal</a></span>(java.io.DataOutputStream dos)</code> </td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#setHorizontalDeflectionAngle-float-">setHorizontalDeflectionAngle</a></span>(float pHorizontalDeflectionAngle)</code> </td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#setVerticalDeflectionAngle-float-">setVerticalDeflectionAngle</a></span>(float pVerticalDeflectionAngle)</code> </td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#unmarshal-java.nio.ByteBuffer-">unmarshal</a></span>(java.nio.ByteBuffer buff)</code>
<div class="block">Unpacks a Pdu from the underlying data.</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/nps/moves/dis/VectoringNozzleSystemData.html#unmarshal-java.io.DataInputStream-">unmarshal</a></span>(java.io.DataInputStream dis)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="horizontalDeflectionAngle">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>horizontalDeflectionAngle</h4>
<pre>protected float horizontalDeflectionAngle</pre>
<div class="block">horizontal deflection angle</div>
</li>
</ul>
<a name="verticalDeflectionAngle">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>verticalDeflectionAngle</h4>
<pre>protected float verticalDeflectionAngle</pre>
<div class="block">vertical deflection angle</div>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="VectoringNozzleSystemData--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>VectoringNozzleSystemData</h4>
<pre>public VectoringNozzleSystemData()</pre>
<div class="block">Constructor</div>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getMarshalledSize--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getMarshalledSize</h4>
<pre>public int getMarshalledSize()</pre>
</li>
</ul>
<a name="setHorizontalDeflectionAngle-float-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setHorizontalDeflectionAngle</h4>
<pre>public void setHorizontalDeflectionAngle(float pHorizontalDeflectionAngle)</pre>
</li>
</ul>
<a name="getHorizontalDeflectionAngle--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getHorizontalDeflectionAngle</h4>
<pre>public float getHorizontalDeflectionAngle()</pre>
</li>
</ul>
<a name="setVerticalDeflectionAngle-float-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setVerticalDeflectionAngle</h4>
<pre>public void setVerticalDeflectionAngle(float pVerticalDeflectionAngle)</pre>
</li>
</ul>
<a name="getVerticalDeflectionAngle--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getVerticalDeflectionAngle</h4>
<pre>public float getVerticalDeflectionAngle()</pre>
</li>
</ul>
<a name="marshal-java.io.DataOutputStream-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>marshal</h4>
<pre>public void marshal(java.io.DataOutputStream dos)</pre>
</li>
</ul>
<a name="unmarshal-java.io.DataInputStream-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>unmarshal</h4>
<pre>public void unmarshal(java.io.DataInputStream dis)</pre>
</li>
</ul>
<a name="marshal-java.nio.ByteBuffer-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>marshal</h4>
<pre>public void marshal(java.nio.ByteBuffer buff)</pre>
<div class="block">Packs a Pdu into the ByteBuffer.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>buff</code> - The ByteBuffer at the position to begin writing</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.nio.BufferOverflowException</code> - if buff is too small</dd>
<dd><code>java.nio.ReadOnlyBufferException</code> - if buff is read only</dd>
<dt><span class="simpleTagLabel">Since:</span></dt>
<dd>??</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><code>ByteBuffer</code></dd>
</dl>
</li>
</ul>
<a name="unmarshal-java.nio.ByteBuffer-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>unmarshal</h4>
<pre>public void unmarshal(java.nio.ByteBuffer buff)</pre>
<div class="block">Unpacks a Pdu from the underlying data.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>buff</code> - The ByteBuffer at the position to begin reading</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.nio.BufferUnderflowException</code> - if buff is too small</dd>
<dt><span class="simpleTagLabel">Since:</span></dt>
<dd>??</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><code>ByteBuffer</code></dd>
</dl>
</li>
</ul>
<a name="equals-java.lang.Object-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public boolean equals(java.lang.Object obj)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>equals</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="equalsImpl-java.lang.Object-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>equalsImpl</h4>
<pre>public boolean equalsImpl(java.lang.Object obj)</pre>
<div class="block">Compare all fields that contribute to the state, ignoring
transient and static fields, for <code>this</code> and the supplied object</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>obj</code> - the object to compare to</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if the objects are equal, false otherwise.</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../edu/nps/moves/dis/Vector3Float.html" title="class in edu.nps.moves.dis"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../edu/nps/moves/dis/WarfareFamilyPdu.html" title="class in edu.nps.moves.dis"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?edu/nps/moves/dis/VectoringNozzleSystemData.html" target="_top">Frames</a></li>
<li><a href="VectoringNozzleSystemData.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| bsd-2-clause |
alerque/homebrew-fonts | Casks/font-xanh-mono.rb | 418 | cask "font-xanh-mono" do
version :latest
sha256 :no_check
url "https://github.com/google/fonts/trunk/ofl/xanhmono",
verified: "github.com/google/fonts/",
using: :svn,
trust_cert: true
name "Xanh Mono"
desc "Mono-serif typeface, designed by lam bao and duy dao"
homepage "https://fonts.google.com/specimen/Xanh+Mono"
font "XanhMono-Italic.ttf"
font "XanhMono-Regular.ttf"
end
| bsd-2-clause |
imgix/levee | tests/d/test_iovec.lua | 2073 | local ffi = require("ffi")
local Iovec = require("levee").d.Iovec
return {
test_core = function()
local iov = Iovec()
local cdata, valuen, tailn, oldtailn
assert.equal(#iov, 0)
cdata, valuen = iov:value()
assert.equal(valuen, 0)
iov:ensure(4)
cdata, valuen = iov:value()
assert.equal(valuen, 0)
assert.equal(#iov, 0)
cdata, tailn = iov:tail()
assert(tailn >= 4)
assert.equal(#iov, 0)
oldtailn = tailn
iov:write("test")
cdata, valuen = iov:value()
assert.equal(valuen, 1)
assert.equal(#iov, 4)
cdata, tailn = iov:tail()
assert.equal(tailn, oldtailn-1)
end,
test_manual = function()
local iov = Iovec()
iov:ensure(4)
assert.equal(#iov, 0)
local i, n = iov:tail()
i[0].iov_base = ffi.cast("char *", "test")
i[0].iov_len = 4
i[1].iov_base = ffi.cast("char *", "value")
i[1].iov_len = 5
i[2].iov_len = 999 -- overwrite to check bump logic
iov:bump(2) -- have bump calculate the new length
assert.equal(#iov, 9)
local i, n = iov:tail()
i[0].iov_base = ffi.cast("char *", "stuff")
i[0].iov_len = 5
i[1].iov_len = 999 -- overwrite to check bump logic
iov:bump(1, 5) -- manually bump the length
assert.equal(#iov, 14)
local i, n = iov:value()
assert.equal(n, 3)
assert.equal(ffi.string(i[0].iov_base, i[0].iov_len), "test")
assert.equal(ffi.string(i[1].iov_base, i[1].iov_len), "value")
assert.equal(ffi.string(i[2].iov_base, i[2].iov_len), "stuff")
end,
test_writeinto = function()
ffi.cdef[[
struct Person {
char *first, *last;
};
size_t strlen(const char *s);
]]
local Person_mt = {}
Person_mt.__index = Person_mt
local space = " "
function Person_mt:writeinto_iovec(iov)
iov:writeraw(self.first, ffi.C.strlen(self.first))
iov:write(space)
iov:writeraw(self.last, ffi.C.strlen(self.last))
end
local Person = ffi.metatype("struct Person", Person_mt)
local andy = Person()
andy.first = ffi.cast("char *", "Andy")
andy.last = ffi.cast("char *", "Gayton")
local iov = Iovec()
iov:write(andy)
assert.equal(#iov, 11)
end,
}
| bsd-2-clause |
willscott/activist-wp-plugin | views/warning.php | 703 | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style='color:red;'>
Sorry. This page is currently unvailable because your ISP is blocking access to this site!
<br />
The site is available, but your local network is preventing you from accessing it.
You can try using a proxy, or another tool like <a href="https://www.torproject.org">Tor</a>.
Note that getting these tools may also be discouraged by your network.
<br />
You are encouraged to talk publically about this experience. It is instances
of misuse of censorship, maybe like this one, which can be used to advocate
for more transparent laws on Internet policy.
</body>
</html>
| bsd-2-clause |
trenskow/Animeteor | README.md | 24 | # README is in progress
| bsd-2-clause |
camillemonchicourt/Geotrek | geotrek/core/views.py | 6257 | # -*- coding: utf-8 -*-
import json
import logging
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import last_modified as cache_last_modified
from django.views.decorators.cache import never_cache as force_cache_validation
from django.core.cache import get_cache
from django.shortcuts import redirect
from mapentity.views import (MapEntityLayer, MapEntityList, MapEntityJsonList,
MapEntityDetail, MapEntityDocument, MapEntityCreate, MapEntityUpdate,
MapEntityDelete, MapEntityFormat,
HttpJSONResponse)
from geotrek.authent.decorators import same_structure_required
from geotrek.common.utils import classproperty
from .models import Path, Trail, Topology
from .forms import PathForm, TrailForm
from .filters import PathFilterSet, TrailFilterSet
from . import graph as graph_lib
logger = logging.getLogger(__name__)
@login_required
def last_list(request):
last = request.session.get('last_list') # set in MapEntityList
if not last:
return redirect('core:path_list')
return redirect(last)
home = last_list
class CreateFromTopologyMixin(object):
def on_topology(self):
pk = self.request.GET.get('topology')
if pk:
try:
return Topology.objects.existing().get(pk=pk)
except Topology.DoesNotExist:
logger.warning("Intervention on unknown topology %s" % pk)
return None
def get_initial(self):
initial = super(CreateFromTopologyMixin, self).get_initial()
# Create intervention with an existing topology as initial data
topology = self.on_topology()
if topology:
initial['topology'] = topology.serialize(with_pk=False)
return initial
class PathLayer(MapEntityLayer):
model = Path
properties = ['name']
class PathList(MapEntityList):
queryset = Path.objects.prefetch_related('networks').select_related('stake')
filterform = PathFilterSet
@classproperty
def columns(cls):
columns = ['id', 'name', 'networks', 'stake']
if settings.TRAIL_MODEL_ENABLED:
columns.append('trails')
return columns
def get_queryset(self):
"""
denormalize ``trail`` column from list.
"""
qs = super(PathList, self).get_queryset()
denormalized = {}
if settings.TRAIL_MODEL_ENABLED:
paths_id = qs.values_list('id', flat=True)
paths_trails = Trail.objects.filter(aggregations__path__id__in=paths_id)
by_id = dict([(trail.id, trail) for trail in paths_trails])
trails_paths_ids = paths_trails.values_list('id', 'aggregations__path__id')
for trail_id, path_id in trails_paths_ids:
denormalized.setdefault(path_id, []).append(by_id[trail_id])
for path in qs:
path_trails = denormalized.get(path.id, [])
setattr(path, '_trails', path_trails)
yield path
class PathJsonList(MapEntityJsonList, PathList):
pass
class PathFormatList(MapEntityFormat, PathList):
pass
class PathDetail(MapEntityDetail):
model = Path
def context_data(self, *args, **kwargs):
context = super(PathDetail, self).context_data(*args, **kwargs)
context['can_edit'] = self.get_object().same_structure(self.request.user)
return context
class PathDocument(MapEntityDocument):
model = Path
def get_context_data(self, *args, **kwargs):
self.get_object().prepare_elevation_chart(self.request.build_absolute_uri('/'))
return super(PathDocument, self).get_context_data(*args, **kwargs)
class PathCreate(MapEntityCreate):
model = Path
form_class = PathForm
class PathUpdate(MapEntityUpdate):
model = Path
form_class = PathForm
@same_structure_required('core:path_detail')
def dispatch(self, *args, **kwargs):
return super(PathUpdate, self).dispatch(*args, **kwargs)
class PathDelete(MapEntityDelete):
model = Path
@same_structure_required('core:path_detail')
def dispatch(self, *args, **kwargs):
return super(PathDelete, self).dispatch(*args, **kwargs)
@login_required
@cache_last_modified(lambda x: Path.latest_updated())
@force_cache_validation
def get_graph_json(request):
cache = get_cache('fat')
key = 'path_graph_json'
result = cache.get(key)
latest = Path.latest_updated()
if result and latest:
cache_latest, json_graph = result
# Not empty and still valid
if cache_latest and cache_latest >= latest:
return HttpJSONResponse(json_graph)
# cache does not exist or is not up to date
# rebuild the graph and cache the json
graph = graph_lib.graph_edges_nodes_of_qs(Path.objects.all())
json_graph = json.dumps(graph)
cache.set(key, (latest, json_graph))
return HttpJSONResponse(json_graph)
class TrailLayer(MapEntityLayer):
queryset = Trail.objects.existing()
properties = ['name']
class TrailList(MapEntityList):
queryset = Trail.objects.existing()
filterform = TrailFilterSet
columns = ['id', 'name', 'departure', 'arrival']
class TrailDetail(MapEntityDetail):
queryset = Trail.objects.existing()
def context_data(self, *args, **kwargs):
context = super(TrailDetail, self).context_data(*args, **kwargs)
context['can_edit'] = self.get_object().same_structure(self.request.user)
return context
class TrailDocument(MapEntityDocument):
queryset = Trail.objects.existing()
class TrailCreate(CreateFromTopologyMixin, MapEntityCreate):
model = Trail
form_class = TrailForm
class TrailUpdate(MapEntityUpdate):
queryset = Trail.objects.existing()
form_class = TrailForm
@same_structure_required('core:trail_detail')
def dispatch(self, *args, **kwargs):
return super(TrailUpdate, self).dispatch(*args, **kwargs)
class TrailDelete(MapEntityDelete):
queryset = Trail.objects.existing()
@same_structure_required('core:trail_detail')
def dispatch(self, *args, **kwargs):
return super(TrailDelete, self).dispatch(*args, **kwargs)
| bsd-2-clause |
PopCap/GameIdea | Engine/Source/Runtime/Engine/Private/HardwareInfo.cpp | 1215 | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
HardwareInfo.cpp: Implements the FHardwareInfo class
=============================================================================*/
#include "EnginePrivate.h"
#include "HardwareInfo.h"
static TMap< FName, FString > HardwareDetailsMap;
void FHardwareInfo::RegisterHardwareInfo( const FName SpecIdentifier, const FString& HardwareInfo )
{
// Ensure we are adding a valid identifier to the map
check( SpecIdentifier == NAME_RHI ||
SpecIdentifier == NAME_TextureFormat ||
SpecIdentifier == NAME_DeviceType );
HardwareDetailsMap.Add( SpecIdentifier, HardwareInfo );
}
const FString FHardwareInfo::GetHardwareDetailsString()
{
FString DetailsString;
int32 DetailsAdded = 0;
for( TMap< FName, FString >::TConstIterator SpecIt( HardwareDetailsMap ); SpecIt; ++SpecIt )
{
// Separate all entries with a comma
if( DetailsAdded++ > 0 )
{
DetailsString += TEXT( ", " );
}
FString SpecID = SpecIt.Key().ToString();
FString SpecValue = SpecIt.Value();
DetailsString += ( ( SpecID + TEXT( "=" ) ) + SpecValue );
}
return DetailsString;
} | bsd-2-clause |
DebVortex/panorama | index.html | 10617 | <!DOCTYPE html>
<head>
<title>panorama - a free bootstrap 3 dashboard template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="a free bootstrap 3 dashboard template">
<meta name="author" content="Max Brauer <[email protected]>">
<meta name="keywords" content="panorama, dashboard, design, responsive," />
<link rel="stylesheet" href="css/bootstrap.min.css"></link>
<link rel="stylesheet" href="css/font-awesome.min.css"></link>
<link rel="stylesheet" href="css/bootstrap-switch.min.css"></link>
<link rel="stylesheet" href="css/main.css"></link>
<link id="theme-file" rel="stylesheet" href="css/by-night.css"></link>
<script type="text/javascript" src="js/vendor/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="js/vendor/jquery.nicescroll.min.js"></script>
<script type="text/javascript" src="js/vendor/jquery.cookie.js"></script>
<script type="text/javascript" src="js/vendor/jquery-ui.custom.min.js"></script>
<script type="text/javascript" src="js/vendor/openWeather.min.js"></script>
<script type="text/javascript" src="js/vendor/bootstrap.min.js"></script>
<script type="text/javascript" src="js/vendor/bootstrap-switch.min.js"></script>
<script type="text/javascript" src="js/dashboard.js"></script>
<script type="text/javascript" src="js/parseRSS.js"></script>
<script type="text/javascript" src="js/custom.js"></script>
</head>
<body>
<!-- top-navigation -->
<nav class="navbar navbar-default navbar-fixed-top background-img" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<span class="main-brand">panorama</span>
<span class="sub-brand">by night</span>
</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Account <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#"><i class="fa fa-user"></i> Profile</a></li>
<li><a href="#"><i class="fa fa-lock"></i> Change Password</a></li>
<li class="divider"></li>
<li>
<a href="#" id="restore-widget-order">
<i class="fa fa-random"></i> Restore Widget Order
</a>
</li>
<li class="divider"></li>
<li><a href="#"><i class="fa fa-lock"></i> Logout</a></li>
</ul>
</li>
</ul>
</div>
</nav>
<!-- /top-navigation -->
<!-- side-navigation -->
<nav class="sidenav background-img">
<ul>
<li>
<i class="fa fa-dashboard active"></i>
<a href="index.html" class="app-title">Dashboard</a>
</li>
<li>
<i class="fa fa-terminal"></i>
<a href="https://github.com/DebVortex/panorama" class="app-title">Source Code</a>
</li>
<!--li>
<i class="fa fa-calendar"></i>
<a href="calendar.html" class="app-title">Calendar</a>
</li-->
<li>
<i class="fa fa-bars"></i>
<a class="app-title">Other Apps</a>
</li>
</ul>
</nav>
<!-- /side-navigation -->
<div>
<span class="pull-right">
<label id="label-theme-switcher">Theme: </label>
<input id="theme-switcher" type="checkbox" checked
data-on-label="night" data-on="night"
data-off-label="day" data-off="day">
</span>
<h1>Dashboard</h1>
</div>
<div class="row">
<div class="col-md-4 column" id="col1">
<div class="widget" id="panorama_info">
<div class="widget-header background-img">
<i class="fa fa-bookmark"></i>
<div class="collapsebutton btn-group pull-right" data-toggle="buttons-checkbox">
<button type="button"
class="btn btn-default btn-xs"
data-toggle="collapse"
data-target="#widgetcontent_panorama_info"
title="Widget einklappen">
_
</button>
</div>
panorama Info-Box
</div>
<div class="widget-content collapse in" id="widgetcontent_panorama_info">
<p>
panorama is a free, bootstrap 3 based template for your dashboard application. It comes with the possibility to rearange the widgets via drag and drop or minimize them via a click on the specific button. You also have the possibility to choose between two designes: panorama by day or panorama by nicht. All the information are stored inside of cookies.<br />
<br />
Feel free to use the template in your private or commercial applications. If you are planing to do a commercial project and want to use the weather widget, make sure you buy a licence of the images from the artist <a href="http://www.smashingapps.com/2012/05/28/40-free-weather-collection-of-weather-forecast-icon-sets.html">here</a>.
</p>
</div>
</div>
</div>
<div class="col-md-4 column" id="col2">
<div class="widget" id="rss-reader">
<div class="widget-header background-img">
<i class="fa fa-rss"></i>
<div class="collapsebutton btn-group pull-right" data-toggle="buttons-checkbox">
<button type="button"
class="btn btn-default btn-xs collapse-btn"
data-toggle="collapse"
data-target="#widgetcontent_rss-reader"
title="Widget einklappen">
_
</button>
</div>
RSS-Reader
</div>
<div class="widget-content collapse in" id="widgetcontent_rss-reader">
</div>
</div>
</div>
<div class="col-md-4 column" id="col3">
<div class="widget" id="calendar">
<div class="widget-header background-img">
<i class="fa fa-calendar"></i>
<div class="collapsebutton btn-group pull-right" data-toggle="buttons-checkbox">
<button type="button"
class="btn btn-default btn-xs"
data-toggle="collapse"
data-target="#widgetcontent_calendar"
title="Widget einklappen">
_
</button>
</div>
Calendar
</div>
<div class="widget-content collapse in" id="widgetcontent_calendar">
</div>
</div>
<div class="widget" id="weather">
<div class="widget-header background-img">
<i class="fa fa-cloud"></i>
<div class="collapsebutton btn-group pull-right" data-toggle="buttons-checkbox">
<button type="button"
class="btn btn-default btn-xs"
data-toggle="collapse"
data-target="#widgetcontent_weather"
title="Widget einklappen">
_
</button>
</div>
Weather
</div>
<div class="widget-content collapse in" id="widgetcontent_weather">
<div class="weather-icon-box">
<img class="weather-icon" alt="Weather Icon" />
</div>
<div class="weather-info-box">
<h2 class="weather-place"></h2>
<hr />
<strong>Temperature:</strong> <span class="weather-temperature"></span><br />
<strong>Description:</strong> <span class="weather-description"></span><br />
<strong>Humidity:</strong> <span class="weather-humidity"></span><br />
<strong>Wind speed:</strong> <span class="weather-wind-speed"></span><br />
<strong>Sunrise:</strong> <span class="weather-sunrise"></span><br />
<strong>Sunset:</strong> <span class="weather-sunset"></span>
</div>
<div class="icon-conrtibution">
Weather Icons made by <a href="http://merlinthered.deviantart.com/art/plain-weather-icons-157162192">MerlinTheRed</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | bsd-2-clause |
vfasky/mcore | example/cnodejs/js/pack/cnode/1.0.0/src/view.js | 394 | // Generated by CoffeeScript 1.9.3
/**
*
* @module cnode/view
* @author vfasky <[email protected]>
*/
(function() {
"use strict";
var api, mcore;
mcore = require('mcoreExt');
api = require('./api');
module.exports = mcore.View.subclass({
constructor: mcore.View.prototype.constructor,
beforeInit: function() {
return this.api = api;
}
});
}).call(this);
| bsd-2-clause |
franckcuny/franckcuny.github.io | posts/2008-06-14-how-to-use-vim-as-a-personal-wiki.md | 2302 | There is different reasons to want a personal wiki on your machine:
- privacy
- having it everywhere
I've tested a few wikis engines, like [tiddlywiki](http://tiddlywiki.com/), but I've found nothing that was really what I wanted. The main inconveniance is the need to use a webbrowser. A browser is not a text processor, so it's really painfull to use them for writing.
I've started to try to use vim as wiki. Why would I want to use something like vim for this ? well, it's plain text (easy to grep, or to write script for manipulating data), application independent, it's a real text processor, you can customize it, and most importantly, I know how to use it, ...
I've got a **wiki** directory in my home directory, with all my files in it. I use git to track versions of it (you can use svn if you prefer, there is no difference for this usage). In my .vimrc, i've added this instruction: `set exrc`.
In my wiki directory, i've got another .vimrc with some specific mapping:
``` viml
map ,I <esc>:e index.mkd <cr>
map ,T <esc>:e todo.mkd <cr>
map ,S <esc>:e someday.mkd <cr>
map ,c <esc>:s/^ /c/<cr>
map ,w <esc>:s/^ /w/<cr>
map ,x <esc>:s/^ /x/<cr>
map gf :e <cfile>.mkd<cr> " open page
map <backspace> :bp<cr>
imap \date <c-R>=strftime("%Y-%m-%d")<cr>
set tabstop=2 " Number of spaces <tab> counts for.
set shiftwidth=2 " Unify
set softtabstop=2 " Unify
```
I organize my files in directory. I've got a **work**, **lists**, **recipes**, **misc**, ... and I put my files in this directory.
I've got an index page, with links to main section. I don't have wikiword in camelcase or things like that, so if i want to put a link to a page, I just wrote the link this way **dir\_name/page\_name**, then, i juste have to hit `gf` on this link to open the page. I also use this place as a todo list manager. I've got one paragrah per day, like this :
```
2008-06-14
- [@context] task 1
- [@context] task 2
...
```
and a bunch of vim mapping for marking complete (`,c`), work in progress (`,w`) or canceled (`,x`).
If i don't have a deadline for a particular task, I use a 'someday' file, where the task is put with a context.
The good things with markdown, is that the syntax is easy to use, and it's easy to convert to HTML.
| bsd-2-clause |
ZombieHippie/cream | public/script/tablesorting.js | 100297 | // Sorting the columns
/**
* @author zhixin wen <[email protected]>
* version: 1.10.1
* https://github.com/wenzhixin/bootstrap-table/
*/
!function ($) {
'use strict';
// TOOLS DEFINITION
// ======================
var cachedWidth = null;
// it only does '%s', and return '' when arguments are undefined
var sprintf = function (str) {
var args = arguments,
flag = true,
i = 1;
str = str.replace(/%s/g, function () {
var arg = args[i++];
if (typeof arg === 'undefined') {
flag = false;
return '';
}
return arg;
});
return flag ? str : '';
};
var getPropertyFromOther = function (list, from, to, value) {
var result = '';
$.each(list, function (i, item) {
if (item[from] === value) {
result = item[to];
return false;
}
return true;
});
return result;
};
var getFieldIndex = function (columns, field) {
var index = -1;
$.each(columns, function (i, column) {
if (column.field === field) {
index = i;
return false;
}
return true;
});
return index;
};
// http://jsfiddle.net/wenyi/47nz7ez9/3/
var setFieldIndex = function (columns) {
var i, j, k,
totalCol = 0,
flag = [];
for (i = 0; i < columns[0].length; i++) {
totalCol += columns[0][i].colspan || 1;
}
for (i = 0; i < columns.length; i++) {
flag[i] = [];
for (j = 0; j < totalCol; j++) {
flag[i][j] = false;
}
}
for (i = 0; i < columns.length; i++) {
for (j = 0; j < columns[i].length; j++) {
var r = columns[i][j],
rowspan = r.rowspan || 1,
colspan = r.colspan || 1,
index = $.inArray(false, flag[i]);
if (colspan === 1) {
r.fieldIndex = index;
// when field is undefined, use index instead
if (typeof r.field === 'undefined') {
r.field = index;
}
}
for (k = 0; k < rowspan; k++) {
flag[i + k][index] = true;
}
for (k = 0; k < colspan; k++) {
flag[i][index + k] = true;
}
}
}
};
var getScrollBarWidth = function () {
if (cachedWidth === null) {
var inner = $('<p/>').addClass('fixed-table-scroll-inner'),
outer = $('<div/>').addClass('fixed-table-scroll-outer'),
w1, w2;
outer.append(inner);
$('body').append(outer);
w1 = inner[0].offsetWidth;
outer.css('overflow', 'scroll');
w2 = inner[0].offsetWidth;
if (w1 === w2) {
w2 = outer[0].clientWidth;
}
outer.remove();
cachedWidth = w1 - w2;
}
return cachedWidth;
};
var calculateObjectValue = function (self, name, args, defaultValue) {
var func = name;
if (typeof name === 'string') {
// support obj.func1.func2
var names = name.split('.');
if (names.length > 1) {
func = window;
$.each(names, function (i, f) {
func = func[f];
});
} else {
func = window[name];
}
}
if (typeof func === 'object') {
return func;
}
if (typeof func === 'function') {
return func.apply(self, args);
}
if (!func && typeof name === 'string' && sprintf.apply(this, [name].concat(args))) {
return sprintf.apply(this, [name].concat(args));
}
return defaultValue;
};
var compareObjects = function (objectA, objectB, compareLength) {
// Create arrays of property names
var objectAProperties = Object.getOwnPropertyNames(objectA),
objectBProperties = Object.getOwnPropertyNames(objectB),
propName = '';
if (compareLength) {
// If number of properties is different, objects are not equivalent
if (objectAProperties.length !== objectBProperties.length) {
return false;
}
}
for (var i = 0; i < objectAProperties.length; i++) {
propName = objectAProperties[i];
// If the property is not in the object B properties, continue with the next property
if ($.inArray(propName, objectBProperties) > -1) {
// If values of same property are not equal, objects are not equivalent
if (objectA[propName] !== objectB[propName]) {
return false;
}
}
}
// If we made it this far, objects are considered equivalent
return true;
};
var escapeHTML = function (text) {
if (typeof text === 'string') {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/`/g, '`');
}
return text;
};
var getRealHeight = function ($el) {
var height = 0;
$el.children().each(function () {
if (height < $(this).outerHeight(true)) {
height = $(this).outerHeight(true);
}
});
return height;
};
var getRealDataAttr = function (dataAttr) {
for (var attr in dataAttr) {
var auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase();
if (auxAttr !== attr) {
dataAttr[auxAttr] = dataAttr[attr];
delete dataAttr[attr];
}
}
return dataAttr;
};
var getItemField = function (item, field, escape) {
var value = item;
if (typeof field !== 'string' || item.hasOwnProperty(field)) {
return escape ? escapeHTML(item[field]) : item[field];
}
var props = field.split('.');
for (var p in props) {
value = value && value[props[p]];
}
return escape ? escapeHTML(value) : value;
};
var isIEBrowser = function () {
return !!(navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./));
};
// BOOTSTRAP TABLE CLASS DEFINITION
// ======================
var BootstrapTable = function (el, options) {
this.options = options;
this.$el = $(el);
this.$el_ = this.$el.clone();
this.timeoutId_ = 0;
this.timeoutFooter_ = 0;
this.init();
};
BootstrapTable.DEFAULTS = {
classes: 'table table-hover',
locale: undefined,
height: undefined,
undefinedText: '-',
sortName: undefined,
sortOrder: 'asc',
striped: false,
columns: [[]],
data: [],
dataField: 'rows',
method: 'get',
url: undefined,
ajax: undefined,
cache: true,
contentType: 'application/json',
dataType: 'json',
ajaxOptions: {},
queryParams: function (params) {
return params;
},
queryParamsType: 'limit', // undefined
responseHandler: function (res) {
return res;
},
pagination: false,
onlyInfoPagination: false,
sidePagination: 'client', // client or server
totalRows: 0, // server side need to set
pageNumber: 1,
pageSize: 10,
pageList: [10, 25, 50, 100],
paginationHAlign: 'right', //right, left
paginationVAlign: 'bottom', //bottom, top, both
paginationDetailHAlign: 'left', //right, left
paginationPreText: '‹',
paginationNextText: '›',
search: false,
searchOnEnterKey: false,
strictSearch: false,
searchAlign: 'right',
selectItemName: 'btSelectItem',
showHeader: true,
showFooter: false,
showColumns: false,
showPaginationSwitch: false,
showRefresh: false,
showToggle: false,
buttonsAlign: 'right',
smartDisplay: true,
escape: false,
minimumCountColumns: 1,
idField: undefined,
uniqueId: undefined,
cardView: false,
detailView: false,
detailFormatter: function (index, row) {
return '';
},
trimOnSearch: true,
clickToSelect: false,
singleSelect: false,
toolbar: undefined,
toolbarAlign: 'left',
checkboxHeader: true,
sortable: true,
silentSort: true,
maintainSelected: false,
searchTimeOut: 500,
searchText: '',
iconSize: undefined,
iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome)
icons: {
paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
refresh: 'glyphicon-refresh icon-refresh',
toggle: 'glyphicon-list-alt icon-list-alt',
columns: 'glyphicon-th icon-th',
detailOpen: 'glyphicon-plus icon-plus',
detailClose: 'glyphicon-minus icon-minus'
},
rowStyle: function (row, index) {
return {};
},
rowAttributes: function (row, index) {
return {};
},
onAll: function (name, args) {
return false;
},
onClickCell: function (field, value, row, $element) {
return false;
},
onDblClickCell: function (field, value, row, $element) {
return false;
},
onClickRow: function (item, $element) {
return false;
},
onDblClickRow: function (item, $element) {
return false;
},
onSort: function (name, order) {
return false;
},
onCheck: function (row) {
return false;
},
onUncheck: function (row) {
return false;
},
onCheckAll: function (rows) {
return false;
},
onUncheckAll: function (rows) {
return false;
},
onCheckSome: function (rows) {
return false;
},
onUncheckSome: function (rows) {
return false;
},
onLoadSuccess: function (data) {
return false;
},
onLoadError: function (status) {
return false;
},
onColumnSwitch: function (field, checked) {
return false;
},
onPageChange: function (number, size) {
return false;
},
onSearch: function (text) {
return false;
},
onToggle: function (cardView) {
return false;
},
onPreBody: function (data) {
return false;
},
onPostBody: function () {
return false;
},
onPostHeader: function () {
return false;
},
onExpandRow: function (index, row, $detail) {
return false;
},
onCollapseRow: function (index, row) {
return false;
},
onRefreshOptions: function (options) {
return false;
},
onResetView: function () {
return false;
}
};
BootstrapTable.LOCALES = [];
BootstrapTable.LOCALES['en-US'] = BootstrapTable.LOCALES['en'] = {
formatLoadingMessage: function () {
return 'Loading, please wait...';
},
formatRecordsPerPage: function (pageNumber) {
return sprintf('%s records per page', pageNumber);
},
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows);
},
formatDetailPagination: function (totalRows) {
return sprintf('Showing %s rows', totalRows);
},
formatSearch: function () {
return 'Search';
},
formatNoMatches: function () {
return 'No rooms currently available';
},
formatPaginationSwitch: function () {
return 'Hide/Show pagination';
},
formatRefresh: function () {
return 'Refresh';
},
formatToggle: function () {
return 'Toggle';
},
formatColumns: function () {
return 'Columns';
},
formatAllRows: function () {
return 'All';
}
};
$.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']);
BootstrapTable.COLUMN_DEFAULTS = {
radio: false,
checkbox: false,
checkboxEnabled: true,
field: undefined,
title: undefined,
titleTooltip: undefined,
'class': undefined,
align: undefined, // left, right, center
halign: undefined, // left, right, center
falign: undefined, // left, right, center
valign: undefined, // top, middle, bottom
width: undefined,
sortable: false,
order: 'asc', // asc, desc
visible: true,
switchable: true,
clickToSelect: true,
formatter: undefined,
footerFormatter: undefined,
events: undefined,
sorter: undefined,
sortName: undefined,
cellStyle: undefined,
searchable: true,
searchFormatter: true,
cardVisible: true
};
BootstrapTable.EVENTS = {
'all.bs.table': 'onAll',
'click-cell.bs.table': 'onClickCell',
'dbl-click-cell.bs.table': 'onDblClickCell',
'click-row.bs.table': 'onClickRow',
'dbl-click-row.bs.table': 'onDblClickRow',
'sort.bs.table': 'onSort',
'check.bs.table': 'onCheck',
'uncheck.bs.table': 'onUncheck',
'check-all.bs.table': 'onCheckAll',
'uncheck-all.bs.table': 'onUncheckAll',
'check-some.bs.table': 'onCheckSome',
'uncheck-some.bs.table': 'onUncheckSome',
'load-success.bs.table': 'onLoadSuccess',
'load-error.bs.table': 'onLoadError',
'column-switch.bs.table': 'onColumnSwitch',
'page-change.bs.table': 'onPageChange',
'search.bs.table': 'onSearch',
'toggle.bs.table': 'onToggle',
'pre-body.bs.table': 'onPreBody',
'post-body.bs.table': 'onPostBody',
'post-header.bs.table': 'onPostHeader',
'expand-row.bs.table': 'onExpandRow',
'collapse-row.bs.table': 'onCollapseRow',
'refresh-options.bs.table': 'onRefreshOptions',
'reset-view.bs.table': 'onResetView'
};
BootstrapTable.prototype.init = function () {
this.initLocale();
this.initContainer();
this.initTable();
this.initHeader();
this.initData();
this.initFooter();
this.initToolbar();
this.initPagination();
this.initBody();
this.initSearchText();
this.initServer();
};
BootstrapTable.prototype.initLocale = function () {
if (this.options.locale) {
var parts = this.options.locale.split(/-|_/);
parts[0].toLowerCase();
parts[1] && parts[1].toUpperCase();
if ($.fn.bootstrapTable.locales[this.options.locale]) {
// locale as requested
$.extend(this.options, $.fn.bootstrapTable.locales[this.options.locale]);
} else if ($.fn.bootstrapTable.locales[parts.join('-')]) {
// locale with sep set to - (in case original was specified with _)
$.extend(this.options, $.fn.bootstrapTable.locales[parts.join('-')]);
} else if ($.fn.bootstrapTable.locales[parts[0]]) {
// short locale language code (i.e. 'en')
$.extend(this.options, $.fn.bootstrapTable.locales[parts[0]]);
}
}
};
BootstrapTable.prototype.initContainer = function () {
this.$container = $([
'<div class="bootstrap-table">',
'<div class="fixed-table-toolbar"></div>',
this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
'<div class="fixed-table-pagination" style="clear: both;"></div>' :
'',
'<div class="fixed-table-container">',
'<div class="fixed-table-header"><table></table></div>',
'<div class="fixed-table-body">',
'<div class="fixed-table-loading">',
this.options.formatLoadingMessage(),
'</div>',
'</div>',
'<div class="fixed-table-footer"><table><tr></tr></table></div>',
this.options.paginationVAlign === 'bottom' || this.options.paginationVAlign === 'both' ?
'<div class="fixed-table-pagination"></div>' :
'',
'</div>',
'</div>'
].join(''));
this.$container.insertAfter(this.$el);
this.$tableContainer = this.$container.find('.fixed-table-container');
this.$tableHeader = this.$container.find('.fixed-table-header');
this.$tableBody = this.$container.find('.fixed-table-body');
this.$tableLoading = this.$container.find('.fixed-table-loading');
this.$tableFooter = this.$container.find('.fixed-table-footer');
this.$toolbar = this.$container.find('.fixed-table-toolbar');
this.$pagination = this.$container.find('.fixed-table-pagination');
this.$tableBody.append(this.$el);
this.$container.after('<div class="clearfix"></div>');
this.$el.addClass(this.options.classes);
if (this.options.striped) {
this.$el.addClass('table-striped');
}
if ($.inArray('table-no-bordered', this.options.classes.split(' ')) !== -1) {
this.$tableContainer.addClass('table-no-bordered');
}
};
BootstrapTable.prototype.initTable = function () {
var that = this,
columns = [],
data = [];
this.$header = this.$el.find('>thead');
if (!this.$header.length) {
this.$header = $('<thead></thead>').appendTo(this.$el);
}
this.$header.find('tr').each(function () {
var column = [];
$(this).find('th').each(function () {
column.push($.extend({}, {
title: $(this).html(),
'class': $(this).attr('class'),
titleTooltip: $(this).attr('title'),
rowspan: $(this).attr('rowspan') ? +$(this).attr('rowspan') : undefined,
colspan: $(this).attr('colspan') ? +$(this).attr('colspan') : undefined
}, $(this).data()));
});
columns.push(column);
});
if (!$.isArray(this.options.columns[0])) {
this.options.columns = [this.options.columns];
}
this.options.columns = $.extend(true, [], columns, this.options.columns);
this.columns = [];
setFieldIndex(this.options.columns);
$.each(this.options.columns, function (i, columns) {
$.each(columns, function (j, column) {
column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column);
if (typeof column.fieldIndex !== 'undefined') {
that.columns[column.fieldIndex] = column;
}
that.options.columns[i][j] = column;
});
});
// if options.data is setting, do not process tbody data
if (this.options.data.length) {
return;
}
this.$el.find('>tbody>tr').each(function () {
var row = {};
// save tr's id, class and data-* attributes
row._id = $(this).attr('id');
row._class = $(this).attr('class');
row._data = getRealDataAttr($(this).data());
$(this).find('td').each(function (i) {
var field = that.columns[i].field;
row[field] = $(this).html();
// save td's id, class and data-* attributes
row['_' + field + '_id'] = $(this).attr('id');
row['_' + field + '_class'] = $(this).attr('class');
row['_' + field + '_rowspan'] = $(this).attr('rowspan');
row['_' + field + '_title'] = $(this).attr('title');
row['_' + field + '_data'] = getRealDataAttr($(this).data());
});
data.push(row);
});
this.options.data = data;
};
BootstrapTable.prototype.initHeader = function () {
var that = this,
visibleColumns = {},
html = [];
this.header = {
fields: [],
styles: [],
classes: [],
formatters: [],
events: [],
sorters: [],
sortNames: [],
cellStyles: [],
searchables: []
};
$.each(this.options.columns, function (i, columns) {
html.push('<tr>');
if (i == 0 && !that.options.cardView && that.options.detailView) {
html.push(sprintf('<th class="detail" rowspan="%s"><div class="fht-cell"></div></th>',
that.options.columns.length));
}
$.each(columns, function (j, column) {
var text = '',
halign = '', // header align style
align = '', // body align style
style = '',
class_ = sprintf(' class="%s"', column['class']),
order = that.options.sortOrder || column.order,
unitWidth = 'px',
width = column.width;
if (column.width !== undefined && (!that.options.cardView)) {
if (typeof column.width === 'string') {
if (column.width.indexOf('%') !== -1) {
unitWidth = '%';
}
}
}
if (column.width && typeof column.width === 'string') {
width = column.width.replace('%', '').replace('px', '');
}
halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align);
align = sprintf('text-align: %s; ', column.align);
style = sprintf('vertical-align: %s; ', column.valign);
style += sprintf('width: %s; ', (column.checkbox || column.radio) && !width ?
'36px' : (width ? width + unitWidth : undefined));
if (typeof column.fieldIndex !== 'undefined') {
that.header.fields[column.fieldIndex] = column.field;
that.header.styles[column.fieldIndex] = align + style;
that.header.classes[column.fieldIndex] = class_;
that.header.formatters[column.fieldIndex] = column.formatter;
that.header.events[column.fieldIndex] = column.events;
that.header.sorters[column.fieldIndex] = column.sorter;
that.header.sortNames[column.fieldIndex] = column.sortName;
that.header.cellStyles[column.fieldIndex] = column.cellStyle;
that.header.searchables[column.fieldIndex] = column.searchable;
if (!column.visible) {
return;
}
if (that.options.cardView && (!column.cardVisible)) {
return;
}
visibleColumns[column.field] = column;
}
html.push('<th' + sprintf(' title="%s"', column.titleTooltip),
column.checkbox || column.radio ?
sprintf(' class="bs-checkbox %s"', column['class'] || '') :
class_,
sprintf(' style="%s"', halign + style),
sprintf(' rowspan="%s"', column.rowspan),
sprintf(' colspan="%s"', column.colspan),
sprintf(' data-field="%s"', column.field),
"tabindex='0'",
'>');
html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ?
'sortable both' : ''));
text = column.title;
if (column.checkbox) {
if (!that.options.singleSelect && that.options.checkboxHeader) {
text = '<input name="btSelectAll" type="checkbox" />';
}
that.header.stateField = column.field;
}
if (column.radio) {
text = '';
that.header.stateField = column.field;
that.options.singleSelect = true;
}
html.push(text);
html.push('</div>');
html.push('<div class="fht-cell"></div>');
html.push('</div>');
html.push('</th>');
});
html.push('</tr>');
});
this.$header.html(html.join(''));
this.$header.find('th[data-field]').each(function (i) {
$(this).data(visibleColumns[$(this).data('field')]);
});
this.$container.off('click', '.th-inner').on('click', '.th-inner', function (event) {
var target = $(this);
if (target.closest('.bootstrap-table')[0] !== that.$container[0])
return false;
if (that.options.sortable && target.parent().data().sortable) {
that.onSort(event);
}
});
this.$header.children().children().off('keypress').on('keypress', function (event) {
if (that.options.sortable && $(this).data().sortable) {
var code = event.keyCode || event.which;
if (code == 13) { //Enter keycode
that.onSort(event);
}
}
});
if (!this.options.showHeader || this.options.cardView) {
this.$header.hide();
this.$tableHeader.hide();
this.$tableLoading.css('top', 0);
} else {
this.$header.show();
this.$tableHeader.show();
this.$tableLoading.css('top', this.$header.outerHeight() + 1);
// Assign the correct sortable arrow
this.getCaret();
}
this.$selectAll = this.$header.find('[name="btSelectAll"]');
this.$selectAll.off('click').on('click', function () {
var checked = $(this).prop('checked');
that[checked ? 'checkAll' : 'uncheckAll']();
that.updateSelected();
});
};
BootstrapTable.prototype.initFooter = function () {
if (!this.options.showFooter || this.options.cardView) {
this.$tableFooter.hide();
} else {
this.$tableFooter.show();
}
};
/**
* @param data
* @param type: append / prepend
*/
BootstrapTable.prototype.initData = function (data, type) {
if (type === 'append') {
this.data = this.data.concat(data);
} else if (type === 'prepend') {
this.data = [].concat(data).concat(this.data);
} else {
this.data = data || this.options.data;
}
// Fix #839 Records deleted when adding new row on filtered table
if (type === 'append') {
this.options.data = this.options.data.concat(data);
} else if (type === 'prepend') {
this.options.data = [].concat(data).concat(this.options.data);
} else {
this.options.data = this.data;
}
if (this.options.sidePagination === 'server') {
return;
}
this.initSort();
};
BootstrapTable.prototype.initSort = function () {
var that = this,
name = this.options.sortName,
order = this.options.sortOrder === 'desc' ? -1 : 1,
index = $.inArray(this.options.sortName, this.header.fields);
if (index !== -1) {
this.data.sort(function (a, b) {
if (that.header.sortNames[index]) {
name = that.header.sortNames[index];
}
var aa = getItemField(a, name, that.options.escape),
bb = getItemField(b, name, that.options.escape),
value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]);
if (value !== undefined) {
return order * value;
}
// Fix #161: undefined or null string sort bug.
if (aa === undefined || aa === null) {
aa = '';
}
if (bb === undefined || bb === null) {
bb = '';
}
// IF both values are numeric, do a numeric comparison
if ($.isNumeric(aa) && $.isNumeric(bb)) {
// Convert numerical values form string to float.
aa = parseFloat(aa);
bb = parseFloat(bb);
if (aa < bb) {
return order * -1;
}
return order;
}
if (aa === bb) {
return 0;
}
// If value is not a string, convert to string
if (typeof aa !== 'string') {
aa = aa.toString();
}
if (aa.localeCompare(bb) === -1) {
return order * -1;
}
return order;
});
}
};
BootstrapTable.prototype.onSort = function (event) {
var $this = event.type === "keypress" ? $(event.currentTarget) : $(event.currentTarget).parent(),
$this_ = this.$header.find('th').eq($this.index());
this.$header.add(this.$header_).find('span.order').remove();
if (this.options.sortName === $this.data('field')) {
this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc';
} else {
this.options.sortName = $this.data('field');
this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
}
this.trigger('sort', this.options.sortName, this.options.sortOrder);
$this.add($this_).data('order', this.options.sortOrder);
// Assign the correct sortable arrow
this.getCaret();
if (this.options.sidePagination === 'server') {
this.initServer(this.options.silentSort);
return;
}
this.initSort();
this.initBody();
};
BootstrapTable.prototype.initToolbar = function () {
var that = this,
html = [],
timeoutId = 0,
$keepOpen,
$search,
switchableCount = 0;
if (this.$toolbar.find('.bars').children().length) {
$('body').append($(this.options.toolbar));
}
this.$toolbar.html('');
if (typeof this.options.toolbar === 'string' || typeof this.options.toolbar === 'object') {
$(sprintf('<div class="bars pull-%s"></div>', this.options.toolbarAlign))
.appendTo(this.$toolbar)
.append($(this.options.toolbar));
}
// showColumns, showToggle, showRefresh
html = [sprintf('<div class="columns columns-%s btn-group pull-%s">',
this.options.buttonsAlign, this.options.buttonsAlign)];
if (typeof this.options.icons === 'string') {
this.options.icons = calculateObjectValue(null, this.options.icons);
}
if (this.options.showPaginationSwitch) {
html.push(sprintf('<button class="btn btn-default" type="button" name="paginationSwitch" title="%s">',
this.options.formatPaginationSwitch()),
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown),
'</button>');
}
if (this.options.showRefresh) {
html.push(sprintf('<button class="btn btn-default' +
sprintf(' btn-%s', this.options.iconSize) +
'" type="button" name="refresh" title="%s">',
this.options.formatRefresh()),
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh),
'</button>');
}
if (this.options.showToggle) {
html.push(sprintf('<button class="btn btn-default' +
sprintf(' btn-%s', this.options.iconSize) +
'" type="button" name="toggle" title="%s">',
this.options.formatToggle()),
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle),
'</button>');
}
if (this.options.showColumns) {
html.push(sprintf('<div class="keep-open btn-group" title="%s">',
this.options.formatColumns()),
'<button type="button" class="btn btn-default' +
sprintf(' btn-%s', this.options.iconSize) +
' dropdown-toggle" data-toggle="dropdown">',
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns),
' <span class="caret"></span>',
'</button>',
'<ul class="dropdown-menu" role="menu">');
$.each(this.columns, function (i, column) {
if (column.radio || column.checkbox) {
return;
}
if (that.options.cardView && (!column.cardVisible)) {
return;
}
var checked = column.visible ? ' checked="checked"' : '';
if (column.switchable) {
html.push(sprintf('<li>' +
'<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' +
'</li>', column.field, i, checked, column.title));
switchableCount++;
}
});
html.push('</ul>',
'</div>');
}
html.push('</div>');
// Fix #188: this.showToolbar is for extensions
if (this.showToolbar || html.length > 2) {
this.$toolbar.append(html.join(''));
}
if (this.options.showPaginationSwitch) {
this.$toolbar.find('button[name="paginationSwitch"]')
.off('click').on('click', $.proxy(this.togglePagination, this));
}
if (this.options.showRefresh) {
this.$toolbar.find('button[name="refresh"]')
.off('click').on('click', $.proxy(this.refresh, this));
}
if (this.options.showToggle) {
this.$toolbar.find('button[name="toggle"]')
.off('click').on('click', function () {
that.toggleView();
});
}
if (this.options.showColumns) {
$keepOpen = this.$toolbar.find('.keep-open');
if (switchableCount <= this.options.minimumCountColumns) {
$keepOpen.find('input').prop('disabled', true);
}
$keepOpen.find('li').off('click').on('click', function (event) {
event.stopImmediatePropagation();
});
$keepOpen.find('input').off('click').on('click', function () {
var $this = $(this);
that.toggleColumn(getFieldIndex(that.columns,
$(this).data('field')), $this.prop('checked'), false);
that.trigger('column-switch', $(this).data('field'), $this.prop('checked'));
});
}
if (this.options.search) {
html = [];
html.push(
'<div class="pull-' + this.options.searchAlign + ' search">',
sprintf('<input class="form-control' +
sprintf(' input-%s', this.options.iconSize) +
'" type="text" placeholder="%s">',
this.options.formatSearch()),
'</div>');
this.$toolbar.append(html.join(''));
$search = this.$toolbar.find('.search input');
$search.off('keyup drop').on('keyup drop', function (event) {
if (that.options.searchOnEnterKey) {
if (event.keyCode !== 13) {
return;
}
}
clearTimeout(timeoutId); // doesn't matter if it's 0
timeoutId = setTimeout(function () {
that.onSearch(event);
}, that.options.searchTimeOut);
});
if (isIEBrowser()) {
$search.off('mouseup').on('mouseup', function (event) {
clearTimeout(timeoutId); // doesn't matter if it's 0
timeoutId = setTimeout(function () {
that.onSearch(event);
}, that.options.searchTimeOut);
});
}
}
};
BootstrapTable.prototype.onSearch = function (event) {
var text = $.trim($(event.currentTarget).val());
// trim search input
if (this.options.trimOnSearch && $(event.currentTarget).val() !== text) {
$(event.currentTarget).val(text);
}
if (text === this.searchText) {
return;
}
this.searchText = text;
this.options.searchText = text;
this.options.pageNumber = 1;
this.initSearch();
this.updatePagination();
this.trigger('search', text);
};
BootstrapTable.prototype.initSearch = function () {
var that = this;
if (this.options.sidePagination !== 'server') {
var s = this.searchText && this.searchText.toLowerCase();
var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns;
// Check filter
this.data = f ? $.grep(this.options.data, function (item, i) {
for (var key in f) {
if ($.isArray(f[key])) {
if ($.inArray(item[key], f[key]) === -1) {
return false;
}
} else if (item[key] !== f[key]) {
return false;
}
}
return true;
}) : this.options.data;
this.data = s ? $.grep(this.data, function (item, i) {
for (var key in item) {
key = $.isNumeric(key) ? parseInt(key, 10) : key;
var value = item[key],
column = that.columns[getFieldIndex(that.columns, key)],
j = $.inArray(key, that.header.fields);
// Fix #142: search use formatted data
if (column && column.searchFormatter) {
value = calculateObjectValue(column,
that.header.formatters[j], [value, item, i], value);
}
var index = $.inArray(key, that.header.fields);
if (index !== -1 && that.header.searchables[index] && (typeof value === 'string' || typeof value === 'number')) {
if (that.options.strictSearch) {
if ((value + '').toLowerCase() === s) {
return true;
}
} else {
if ((value + '').toLowerCase().indexOf(s) !== -1) {
return true;
}
}
}
}
return false;
}) : this.data;
}
};
BootstrapTable.prototype.initPagination = function () {
if (!this.options.pagination) {
this.$pagination.hide();
return;
} else {
this.$pagination.show();
}
var that = this,
html = [],
$allSelected = false,
i, from, to,
$pageList,
$first, $pre,
$next, $last,
$number,
data = this.getData();
if (this.options.sidePagination !== 'server') {
this.options.totalRows = data.length;
}
this.totalPages = 0;
if (this.options.totalRows) {
if (this.options.pageSize === this.options.formatAllRows()) {
this.options.pageSize = this.options.totalRows;
$allSelected = true;
} else if (this.options.pageSize === this.options.totalRows) {
// Fix #667 Table with pagination,
// multiple pages and a search that matches to one page throws exception
var pageLst = typeof this.options.pageList === 'string' ?
this.options.pageList.replace('[', '').replace(']', '')
.replace(/ /g, '').toLowerCase().split(',') : this.options.pageList;
if ($.inArray(this.options.formatAllRows().toLowerCase(), pageLst) > -1) {
$allSelected = true;
}
}
this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
this.options.totalPages = this.totalPages;
}
if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
this.options.pageNumber = this.totalPages;
}
this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
this.pageTo = this.options.pageNumber * this.options.pageSize;
if (this.pageTo > this.options.totalRows) {
this.pageTo = this.options.totalRows;
}
html.push(
'<div class="pull-' + this.options.paginationDetailHAlign + ' pagination-detail">',
'<span class="pagination-info">',
this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows) :
this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
'</span>');
if (!this.options.onlyInfoPagination) {
html.push('<span class="page-list">');
var pageNumber = [
sprintf('<span class="btn-group %s">',
this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
'dropdown' : 'dropup'),
'<button type="button" class="btn btn-default ' +
sprintf(' btn-%s', this.options.iconSize) +
' dropdown-toggle" data-toggle="dropdown">',
'<span class="page-size">',
$allSelected ? this.options.formatAllRows() : this.options.pageSize,
'</span>',
' <span class="caret"></span>',
'</button>',
'<ul class="dropdown-menu" role="menu">'
],
pageList = this.options.pageList;
if (typeof this.options.pageList === 'string') {
var list = this.options.pageList.replace('[', '').replace(']', '')
.replace(/ /g, '').split(',');
pageList = [];
$.each(list, function (i, value) {
pageList.push(value.toUpperCase() === that.options.formatAllRows().toUpperCase() ?
that.options.formatAllRows() : +value);
});
}
$.each(pageList, function (i, page) {
if (!that.options.smartDisplay || i === 0 || pageList[i - 1] <= that.options.totalRows) {
var active;
if ($allSelected) {
active = page === that.options.formatAllRows() ? ' class="active"' : '';
} else {
active = page === that.options.pageSize ? ' class="active"' : '';
}
pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page));
}
});
pageNumber.push('</ul></span>');
html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
html.push('</span>');
html.push('</div>',
'<div class="pull-' + this.options.paginationHAlign + ' pagination">',
'<ul class="pagination' + sprintf(' pagination-%s', this.options.iconSize) + '">',
'<li class="page-pre"><a href="javascript:void(0)">' + this.options.paginationPreText + '</a></li>');
if (this.totalPages < 5) {
from = 1;
to = this.totalPages;
} else {
from = this.options.pageNumber - 2;
to = from + 4;
if (from < 1) {
from = 1;
to = 5;
}
if (to > this.totalPages) {
to = this.totalPages;
from = to - 4;
}
}
if (this.totalPages >= 6) {
if (this.options.pageNumber >= 3) {
html.push('<li class="page-first' + (1 === this.options.pageNumber ? ' active' : '') + '">',
'<a href="javascript:void(0)">', 1, '</a>',
'</li>');
from++;
}
if (this.options.pageNumber >= 4) {
if (this.options.pageNumber == 4 || this.totalPages == 6 || this.totalPages == 7) {
from--;
} else {
html.push('<li class="page-first-separator disabled">',
'<a href="javascript:void(0)">...</a>',
'</li>');
}
to--;
}
}
if (this.totalPages >= 7) {
if (this.options.pageNumber >= (this.totalPages - 2)) {
from--;
}
}
if (this.totalPages == 6) {
if (this.options.pageNumber >= (this.totalPages - 2)) {
to++;
}
} else if (this.totalPages >= 7) {
if (this.totalPages == 7 || this.options.pageNumber >= (this.totalPages - 3)) {
to++;
}
}
for (i = from; i <= to; i++) {
html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
'<a href="javascript:void(0)">', i, '</a>',
'</li>');
}
if (this.totalPages >= 8) {
if (this.options.pageNumber <= (this.totalPages - 4)) {
html.push('<li class="page-last-separator disabled">',
'<a href="javascript:void(0)">...</a>',
'</li>');
}
}
if (this.totalPages >= 6) {
if (this.options.pageNumber <= (this.totalPages - 3)) {
html.push('<li class="page-last' + (this.totalPages === this.options.pageNumber ? ' active' : '') + '">',
'<a href="javascript:void(0)">', this.totalPages, '</a>',
'</li>');
}
}
html.push(
'<li class="page-next"><a href="javascript:void(0)">' + this.options.paginationNextText + '</a></li>',
'</ul>',
'</div>');
}
this.$pagination.html(html.join(''));
if (!this.options.onlyInfoPagination) {
$pageList = this.$pagination.find('.page-list a');
$first = this.$pagination.find('.page-first');
$pre = this.$pagination.find('.page-pre');
$next = this.$pagination.find('.page-next');
$last = this.$pagination.find('.page-last');
$number = this.$pagination.find('.page-number');
if (this.options.smartDisplay) {
if (this.totalPages <= 1) {
this.$pagination.find('div.pagination').hide();
}
if (pageList.length < 2 || this.options.totalRows <= pageList[0]) {
this.$pagination.find('span.page-list').hide();
}
// when data is empty, hide the pagination
this.$pagination[this.getData().length ? 'show' : 'hide']();
}
if ($allSelected) {
this.options.pageSize = this.options.formatAllRows();
}
$pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
$first.off('click').on('click', $.proxy(this.onPageFirst, this));
$pre.off('click').on('click', $.proxy(this.onPagePre, this));
$next.off('click').on('click', $.proxy(this.onPageNext, this));
$last.off('click').on('click', $.proxy(this.onPageLast, this));
$number.off('click').on('click', $.proxy(this.onPageNumber, this));
}
};
BootstrapTable.prototype.updatePagination = function (event) {
// Fix #171: IE disabled button can be clicked bug.
if (event && $(event.currentTarget).hasClass('disabled')) {
return;
}
if (!this.options.maintainSelected) {
this.resetRows();
}
this.initPagination();
if (this.options.sidePagination === 'server') {
this.initServer();
} else {
this.initBody();
}
this.trigger('page-change', this.options.pageNumber, this.options.pageSize);
};
BootstrapTable.prototype.onPageListChange = function (event) {
var $this = $(event.currentTarget);
$this.parent().addClass('active').siblings().removeClass('active');
this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ?
this.options.formatAllRows() : +$this.text();
this.$toolbar.find('.page-size').text(this.options.pageSize);
this.updatePagination(event);
};
BootstrapTable.prototype.onPageFirst = function (event) {
this.options.pageNumber = 1;
this.updatePagination(event);
};
BootstrapTable.prototype.onPagePre = function (event) {
if ((this.options.pageNumber - 1) == 0) {
this.options.pageNumber = this.options.totalPages;
} else {
this.options.pageNumber--;
}
this.updatePagination(event);
};
BootstrapTable.prototype.onPageNext = function (event) {
if ((this.options.pageNumber + 1) > this.options.totalPages) {
this.options.pageNumber = 1;
} else {
this.options.pageNumber++;
}
this.updatePagination(event);
};
BootstrapTable.prototype.onPageLast = function (event) {
this.options.pageNumber = this.totalPages;
this.updatePagination(event);
};
BootstrapTable.prototype.onPageNumber = function (event) {
if (this.options.pageNumber === +$(event.currentTarget).text()) {
return;
}
this.options.pageNumber = +$(event.currentTarget).text();
this.updatePagination(event);
};
BootstrapTable.prototype.initBody = function (fixedScroll) {
var that = this,
html = [],
data = this.getData();
this.trigger('pre-body', data);
this.$body = this.$el.find('>tbody');
if (!this.$body.length) {
this.$body = $('<tbody></tbody>').appendTo(this.$el);
}
//Fix #389 Bootstrap-table-flatJSON is not working
if (!this.options.pagination || this.options.sidePagination === 'server') {
this.pageFrom = 1;
this.pageTo = data.length;
}
for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
var key,
item = data[i],
style = {},
csses = [],
data_ = '',
attributes = {},
htmlAttributes = [];
style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style);
if (style && style.css) {
for (key in style.css) {
csses.push(key + ': ' + style.css[key]);
}
}
attributes = calculateObjectValue(this.options,
this.options.rowAttributes, [item, i], attributes);
if (attributes) {
for (key in attributes) {
htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key])));
}
}
if (item._data && !$.isEmptyObject(item._data)) {
$.each(item._data, function (k, v) {
// ignore data-index
if (k === 'index') {
return;
}
data_ += sprintf(' data-%s="%s"', k, v);
});
}
html.push('<tr',
sprintf(' %s', htmlAttributes.join(' ')),
sprintf(' id="%s"', $.isArray(item) ? undefined : item._id),
sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)),
sprintf(' data-index="%s"', i),
sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]),
sprintf('%s', data_),
'>'
);
if (this.options.cardView) {
html.push(sprintf('<td colspan="%s">', this.header.fields.length));
}
if (!this.options.cardView && this.options.detailView) {
html.push('<td>',
'<a class="detail-icon" href="javascript:">',
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.detailOpen),
'</a>',
'</td>');
}
$.each(this.header.fields, function (j, field) {
var text = '',
value = getItemField(item, field, that.options.escape),
type = '',
cellStyle = {},
id_ = '',
class_ = that.header.classes[j],
data_ = '',
rowspan_ = '',
title_ = '',
column = that.columns[getFieldIndex(that.columns, field)];
if (!column.visible) {
return;
}
style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
value = calculateObjectValue(column,
that.header.formatters[j], [value, item, i], value);
// handle td's id and class
if (item['_' + field + '_id']) {
id_ = sprintf(' id="%s"', item['_' + field + '_id']);
}
if (item['_' + field + '_class']) {
class_ = sprintf(' class="%s"', item['_' + field + '_class']);
}
if (item['_' + field + '_rowspan']) {
rowspan_ = sprintf(' rowspan="%s"', item['_' + field + '_rowspan']);
}
if (item['_' + field + '_title']) {
title_ = sprintf(' title="%s"', item['_' + field + '_title']);
}
cellStyle = calculateObjectValue(that.header,
that.header.cellStyles[j], [value, item, i], cellStyle);
if (cellStyle.classes) {
class_ = sprintf(' class="%s"', cellStyle.classes);
}
if (cellStyle.css) {
var csses_ = [];
for (var key in cellStyle.css) {
csses_.push(key + ': ' + cellStyle.css[key]);
}
style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; '));
}
if (item['_' + field + '_data'] && !$.isEmptyObject(item['_' + field + '_data'])) {
$.each(item['_' + field + '_data'], function (k, v) {
// ignore data-index
if (k === 'index') {
return;
}
data_ += sprintf(' data-%s="%s"', k, v);
});
}
if (column.checkbox || column.radio) {
type = column.checkbox ? 'checkbox' : type;
type = column.radio ? 'radio' : type;
text = [sprintf(that.options.cardView ?
'<div class="card-view %s">' : '<td class="bs-checkbox %s">', column['class'] || ''),
'<input' +
sprintf(' data-index="%s"', i) +
sprintf(' name="%s"', that.options.selectItemName) +
sprintf(' type="%s"', type) +
sprintf(' value="%s"', item[that.options.idField]) +
sprintf(' checked="%s"', value === true ||
(value && value.checked) ? 'checked' : undefined) +
sprintf(' disabled="%s"', !column.checkboxEnabled ||
(value && value.disabled) ? 'disabled' : undefined) +
' />',
that.header.formatters[j] && typeof value === 'string' ? value : '',
that.options.cardView ? '</div>' : '</td>'
].join('');
item[that.header.stateField] = value === true || (value && value.checked);
} else {
value = typeof value === 'undefined' || value === null ?
that.options.undefinedText : value;
text = that.options.cardView ? ['<div class="card-view">',
that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
getPropertyFromOther(that.columns, 'field', 'title', field)) : '',
sprintf('<span class="value">%s</span>', value),
'</div>'
].join('') : [sprintf('<td%s %s %s %s %s %s>', id_, class_, style, data_, rowspan_, title_),
value,
'</td>'
].join('');
// Hide empty data on Card view when smartDisplay is set to true.
if (that.options.cardView && that.options.smartDisplay && value === '') {
// Should set a placeholder for event binding correct fieldIndex
text = '<div class="card-view"></div>';
}
}
html.push(text);
});
if (this.options.cardView) {
html.push('</td>');
}
html.push('</tr>');
}
// show no records
if (!html.length) {
html.push('<tr class="no-records-found">',
sprintf('<td colspan="%s">%s</td>',
this.$header.find('th').length, this.options.formatNoMatches()),
'</tr>');
}
this.$body.html(html.join(''));
if (!fixedScroll) {
this.scrollTo(0);
}
// click to select by column
this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) {
var $td = $(this),
$tr = $td.parent(),
item = that.data[$tr.data('index')],
index = $td[0].cellIndex,
field = that.header.fields[that.options.detailView && !that.options.cardView ? index - 1 : index],
column = that.columns[getFieldIndex(that.columns, field)],
value = getItemField(item, field, that.options.escape);
if ($td.find('.detail-icon').length) {
return;
}
that.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td);
that.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr);
// if click to select - then trigger the checkbox/radio click
if (e.type === 'click' && that.options.clickToSelect && column.clickToSelect) {
var $selectItem = $tr.find(sprintf('[name="%s"]', that.options.selectItemName));
if ($selectItem.length) {
$selectItem[0].click(); // #144: .trigger('click') bug
}
}
});
this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function () {
var $this = $(this),
$tr = $this.parent().parent(),
index = $tr.data('index'),
row = data[index]; // Fix #980 Detail view, when searching, returns wrong row
// remove and update
if ($tr.next().is('tr.detail-view')) {
$this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailOpen));
$tr.next().remove();
that.trigger('collapse-row', index, row);
} else {
$this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailClose));
$tr.after(sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.find('td').length));
var $element = $tr.next().find('td');
var content = calculateObjectValue(that.options, that.options.detailFormatter, [index, row, $element], '');
if($element.length === 1) {
$element.append(content);
}
that.trigger('expand-row', index, row, $element);
}
that.resetView();
});
this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
this.$selectItem.off('click').on('click', function (event) {
event.stopImmediatePropagation();
var $this = $(this),
checked = $this.prop('checked'),
row = that.data[$this.data('index')];
if (that.options.maintainSelected && $(this).is(':radio')) {
$.each(that.options.data, function (i, row) {
row[that.header.stateField] = false;
});
}
row[that.header.stateField] = checked;
if (that.options.singleSelect) {
that.$selectItem.not(this).each(function () {
that.data[$(this).data('index')][that.header.stateField] = false;
});
that.$selectItem.filter(':checked').not(this).prop('checked', false);
}
that.updateSelected();
that.trigger(checked ? 'check' : 'uncheck', row, $this);
});
$.each(this.header.events, function (i, events) {
if (!events) {
return;
}
// fix bug, if events is defined with namespace
if (typeof events === 'string') {
events = calculateObjectValue(null, events);
}
var field = that.header.fields[i],
fieldIndex = $.inArray(field, that.getVisibleFields());
if (that.options.detailView && !that.options.cardView) {
fieldIndex += 1;
}
for (var key in events) {
that.$body.find('>tr:not(.no-records-found)').each(function () {
var $tr = $(this),
$td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(fieldIndex),
index = key.indexOf(' '),
name = key.substring(0, index),
el = key.substring(index + 1),
func = events[key];
$td.find(el).off(name).on(name, function (e) {
var index = $tr.data('index'),
row = that.data[index],
value = row[field];
func.apply(this, [e, value, row, index]);
});
});
}
});
this.updateSelected();
this.resetView();
this.trigger('post-body');
};
BootstrapTable.prototype.initServer = function (silent, query) {
var that = this,
data = {},
params = {
searchText: this.searchText,
sortName: this.options.sortName,
sortOrder: this.options.sortOrder
},
request;
if(this.options.pagination) {
params.pageSize = this.options.pageSize === this.options.formatAllRows() ?
this.options.totalRows : this.options.pageSize;
params.pageNumber = this.options.pageNumber;
}
if (!this.options.url && !this.options.ajax) {
return;
}
if (this.options.queryParamsType === 'limit') {
params = {
search: params.searchText,
sort: params.sortName,
order: params.sortOrder
};
if (this.options.pagination) {
params.limit = this.options.pageSize === this.options.formatAllRows() ?
this.options.totalRows : this.options.pageSize;
params.offset = this.options.pageSize === this.options.formatAllRows() ?
0 : this.options.pageSize * (this.options.pageNumber - 1);
}
}
if (!($.isEmptyObject(this.filterColumnsPartial))) {
params['filter'] = JSON.stringify(this.filterColumnsPartial, null);
}
data = calculateObjectValue(this.options, this.options.queryParams, [params], data);
$.extend(data, query || {});
// false to stop request
if (data === false) {
return;
}
if (!silent) {
this.$tableLoading.show();
}
request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
type: this.options.method,
url: this.options.url,
data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
JSON.stringify(data) : data,
cache: this.options.cache,
contentType: this.options.contentType,
dataType: this.options.dataType,
success: function (res) {
res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
that.load(res);
that.trigger('load-success', res);
if (!silent) that.$tableLoading.hide();
},
error: function (res) {
that.trigger('load-error', res.status, res);
if (!silent) that.$tableLoading.hide();
}
});
if (this.options.ajax) {
calculateObjectValue(this, this.options.ajax, [request], null);
} else {
$.ajax(request);
}
};
BootstrapTable.prototype.initSearchText = function () {
if (this.options.search) {
if (this.options.searchText !== '') {
var $search = this.$toolbar.find('.search input');
$search.val(this.options.searchText);
this.onSearch({currentTarget: $search});
}
}
};
BootstrapTable.prototype.getCaret = function () {
var that = this;
$.each(this.$header.find('th'), function (i, th) {
$(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === that.options.sortName ? that.options.sortOrder : 'both');
});
};
BootstrapTable.prototype.updateSelected = function () {
var checkAll = this.$selectItem.filter(':enabled').length &&
this.$selectItem.filter(':enabled').length ===
this.$selectItem.filter(':enabled').filter(':checked').length;
this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
this.$selectItem.each(function () {
$(this).closest('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
});
};
BootstrapTable.prototype.updateRows = function () {
var that = this;
this.$selectItem.each(function () {
that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked');
});
};
BootstrapTable.prototype.resetRows = function () {
var that = this;
$.each(this.data, function (i, row) {
that.$selectAll.prop('checked', false);
that.$selectItem.prop('checked', false);
if (that.header.stateField) {
row[that.header.stateField] = false;
}
});
};
BootstrapTable.prototype.trigger = function (name) {
var args = Array.prototype.slice.call(arguments, 1);
name += '.bs.table';
this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
this.$el.trigger($.Event(name), args);
this.options.onAll(name, args);
this.$el.trigger($.Event('all.bs.table'), [name, args]);
};
BootstrapTable.prototype.resetHeader = function () {
// fix #61: the hidden table reset header bug.
// fix bug: get $el.css('width') error sometime (height = 500)
clearTimeout(this.timeoutId_);
this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0);
};
BootstrapTable.prototype.fitHeader = function () {
var that = this,
fixedBody,
scrollWidth,
focused,
focusedTemp;
if (that.$el.is(':hidden')) {
that.timeoutId_ = setTimeout($.proxy(that.fitHeader, that), 100);
return;
}
fixedBody = this.$tableBody.get(0);
scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
getScrollBarWidth() : 0;
this.$el.css('margin-top', -this.$header.outerHeight());
focused = $(':focus');
if (focused.length > 0) {
var $th = focused.parents('th');
if ($th.length > 0) {
var dataField = $th.attr('data-field');
if (dataField !== undefined) {
var $headerTh = this.$header.find("[data-field='" + dataField + "']");
if ($headerTh.length > 0) {
$headerTh.find(":input").addClass("focus-temp");
}
}
}
}
this.$header_ = this.$header.clone(true, true);
this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
this.$tableHeader.css({
'margin-right': scrollWidth
}).find('table').css('width', this.$el.outerWidth())
.html('').attr('class', this.$el.attr('class'))
.append(this.$header_);
focusedTemp = $('.focus-temp:visible:eq(0)');
if (focusedTemp.length > 0) {
focusedTemp.focus();
this.$header.find('.focus-temp').removeClass('focus-temp');
}
// fix bug: $.data() is not working as expected after $.append()
this.$header.find('th[data-field]').each(function (i) {
that.$header_.find(sprintf('th[data-field="%s"]', $(this).data('field'))).data($(this).data());
});
var visibleFields = this.getVisibleFields();
this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
var $this = $(this),
index = i;
if (that.options.detailView && !that.options.cardView) {
if (i === 0) {
that.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth());
}
index = i - 1;
}
that.$header_.find(sprintf('th[data-field="%s"]', visibleFields[index]))
.find('.fht-cell').width($this.innerWidth());
});
// horizontal scroll event
// TODO: it's probably better improving the layout than binding to scroll event
this.$tableBody.off('scroll').on('scroll', function () {
that.$tableHeader.scrollLeft($(this).scrollLeft());
if (that.options.showFooter && !that.options.cardView) {
that.$tableFooter.scrollLeft($(this).scrollLeft());
}
});
that.trigger('post-header');
};
BootstrapTable.prototype.resetFooter = function () {
var that = this,
data = that.getData(),
html = [];
if (!this.options.showFooter || this.options.cardView) { //do nothing
return;
}
if (!this.options.cardView && this.options.detailView) {
html.push('<td><div class="th-inner"> </div><div class="fht-cell"></div></td>');
}
$.each(this.columns, function (i, column) {
var falign = '', // footer align style
style = '',
class_ = sprintf(' class="%s"', column['class']);
if (!column.visible) {
return;
}
if (that.options.cardView && (!column.cardVisible)) {
return;
}
falign = sprintf('text-align: %s; ', column.falign ? column.falign : column.align);
style = sprintf('vertical-align: %s; ', column.valign);
html.push('<td', class_, sprintf(' style="%s"', falign + style), '>');
html.push('<div class="th-inner">');
html.push(calculateObjectValue(column, column.footerFormatter, [data], ' ') || ' ');
html.push('</div>');
html.push('<div class="fht-cell"></div>');
html.push('</div>');
html.push('</td>');
});
this.$tableFooter.find('tr').html(html.join(''));
clearTimeout(this.timeoutFooter_);
this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this),
this.$el.is(':hidden') ? 100 : 0);
};
BootstrapTable.prototype.fitFooter = function () {
var that = this,
$footerTd,
elWidth,
scrollWidth;
clearTimeout(this.timeoutFooter_);
if (this.$el.is(':hidden')) {
this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100);
return;
}
elWidth = this.$el.css('width');
scrollWidth = elWidth > this.$tableBody.width() ? getScrollBarWidth() : 0;
this.$tableFooter.css({
'margin-right': scrollWidth
}).find('table').css('width', elWidth)
.attr('class', this.$el.attr('class'));
$footerTd = this.$tableFooter.find('td');
this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
var $this = $(this);
$footerTd.eq(i).find('.fht-cell').width($this.innerWidth());
});
};
BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
if (index === -1) {
return;
}
this.columns[index].visible = checked;
this.initHeader();
this.initSearch();
this.initPagination();
this.initBody();
if (this.options.showColumns) {
var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
if (needUpdate) {
$items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
}
if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
$items.filter(':checked').prop('disabled', true);
}
}
};
BootstrapTable.prototype.toggleRow = function (index, uniqueId, visible) {
if (index === -1) {
return;
}
this.$body.find(typeof index !== 'undefined' ?
sprintf('tr[data-index="%s"]', index) :
sprintf('tr[data-uniqueid="%s"]', uniqueId))
[visible ? 'show' : 'hide']();
};
BootstrapTable.prototype.getVisibleFields = function () {
var that = this,
visibleFields = [];
$.each(this.header.fields, function (j, field) {
var column = that.columns[getFieldIndex(that.columns, field)];
if (!column.visible) {
return;
}
visibleFields.push(field);
});
return visibleFields;
};
// PUBLIC FUNCTION DEFINITION
// =======================
BootstrapTable.prototype.resetView = function (params) {
var padding = 0;
if (params && params.height) {
this.options.height = params.height;
}
this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
this.$selectItem.length === this.$selectItem.filter(':checked').length);
if (this.options.height) {
var toolbarHeight = getRealHeight(this.$toolbar),
paginationHeight = getRealHeight(this.$pagination),
height = this.options.height - toolbarHeight - paginationHeight;
this.$tableContainer.css('height', height + 'px');
}
if (this.options.cardView) {
// remove the element css
this.$el.css('margin-top', '0');
this.$tableContainer.css('padding-bottom', '0');
return;
}
if (this.options.showHeader && this.options.height) {
this.$tableHeader.show();
this.resetHeader();
padding += this.$header.outerHeight();
} else {
this.$tableHeader.hide();
this.trigger('post-header');
}
if (this.options.showFooter) {
this.resetFooter();
if (this.options.height) {
padding += this.$tableFooter.outerHeight() + 1;
}
}
// Assign the correct sortable arrow
this.getCaret();
this.$tableContainer.css('padding-bottom', padding + 'px');
this.trigger('reset-view');
};
BootstrapTable.prototype.getData = function (useCurrentPage) {
return (this.searchText || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) ?
(useCurrentPage ? this.data.slice(this.pageFrom - 1, this.pageTo) : this.data) :
(useCurrentPage ? this.options.data.slice(this.pageFrom - 1, this.pageTo) : this.options.data);
};
BootstrapTable.prototype.load = function (data) {
var fixedScroll = false;
// #431: support pagination
if (this.options.sidePagination === 'server') {
this.options.totalRows = data.total;
fixedScroll = data.fixedScroll;
data = data[this.options.dataField];
} else if (!$.isArray(data)) { // support fixedScroll
fixedScroll = data.fixedScroll;
data = data.data;
}
this.initData(data);
this.initSearch();
this.initPagination();
this.initBody(fixedScroll);
};
BootstrapTable.prototype.append = function (data) {
this.initData(data, 'append');
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.prepend = function (data) {
this.initData(data, 'prepend');
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.remove = function (params) {
var len = this.options.data.length,
i, row;
if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
return;
}
for (i = len - 1; i >= 0; i--) {
row = this.options.data[i];
if (!row.hasOwnProperty(params.field)) {
continue;
}
if ($.inArray(row[params.field], params.values) !== -1) {
this.options.data.splice(i, 1);
}
}
if (len === this.options.data.length) {
return;
}
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.removeAll = function () {
if (this.options.data.length > 0) {
this.options.data.splice(0, this.options.data.length);
this.initSearch();
this.initPagination();
this.initBody(true);
}
};
BootstrapTable.prototype.getRowByUniqueId = function (id) {
var uniqueId = this.options.uniqueId,
len = this.options.data.length,
dataRow = null,
i, row, rowUniqueId;
for (i = len - 1; i >= 0; i--) {
row = this.options.data[i];
if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
rowUniqueId = row[uniqueId];
} else if(row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
rowUniqueId = row._data[uniqueId];
} else {
continue;
}
if (typeof rowUniqueId === 'string') {
id = id.toString();
} else if (typeof rowUniqueId === 'number') {
if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
id = parseInt(id);
} else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
id = parseFloat(id);
}
}
if (rowUniqueId === id) {
dataRow = row;
break;
}
}
return dataRow;
};
BootstrapTable.prototype.removeByUniqueId = function (id) {
var len = this.options.data.length,
row = this.getRowByUniqueId(id);
if (row) {
this.options.data.splice(this.options.data.indexOf(row), 1);
}
if (len === this.options.data.length) {
return;
}
this.initSearch();
this.initPagination();
this.initBody(true);
};
BootstrapTable.prototype.updateByUniqueId = function (params) {
var rowId;
if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
return;
}
rowId = $.inArray(this.getRowByUniqueId(params.id), this.options.data);
if (rowId === -1) {
return;
}
$.extend(this.data[rowId], params.row);
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.insertRow = function (params) {
if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
return;
}
this.data.splice(params.index, 0, params.row);
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.updateRow = function (params) {
if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
return;
}
$.extend(this.data[params.index], params.row);
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.showRow = function (params) {
if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) {
return;
}
this.toggleRow(params.index, params.uniqueId, true);
};
BootstrapTable.prototype.hideRow = function (params) {
if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) {
return;
}
this.toggleRow(params.index, params.uniqueId, false);
};
BootstrapTable.prototype.getRowsHidden = function (show) {
var rows = $(this.$body[0]).children().filter(':hidden'),
i = 0;
if (show) {
for (; i < rows.length; i++) {
$(rows[i]).show();
}
}
return rows;
};
BootstrapTable.prototype.mergeCells = function (options) {
var row = options.index,
col = $.inArray(options.field, this.getVisibleFields()),
rowspan = options.rowspan || 1,
colspan = options.colspan || 1,
i, j,
$tr = this.$body.find('>tr'),
$td;
if (this.options.detailView && !this.options.cardView) {
col += 1;
}
$td = $tr.eq(row).find('>td').eq(col);
if (row < 0 || col < 0 || row >= this.data.length) {
return;
}
for (i = row; i < row + rowspan; i++) {
for (j = col; j < col + colspan; j++) {
$tr.eq(i).find('>td').eq(j).hide();
}
}
$td.attr('rowspan', rowspan).attr('colspan', colspan).show();
};
BootstrapTable.prototype.updateCell = function (params) {
if (!params.hasOwnProperty('index') ||
!params.hasOwnProperty('field') ||
!params.hasOwnProperty('value')) {
return;
}
this.data[params.index][params.field] = params.value;
if (params.reinit === false) {
return;
}
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.getOptions = function () {
return this.options;
};
BootstrapTable.prototype.getSelections = function () {
var that = this;
return $.grep(this.data, function (row) {
return row[that.header.stateField];
});
};
BootstrapTable.prototype.getAllSelections = function () {
var that = this;
return $.grep(this.options.data, function (row) {
return row[that.header.stateField];
});
};
BootstrapTable.prototype.checkAll = function () {
this.checkAll_(true);
};
BootstrapTable.prototype.uncheckAll = function () {
this.checkAll_(false);
};
BootstrapTable.prototype.checkInvert = function () {
var that = this;
var rows = that.$selectItem.filter(':enabled');
var checked = rows.filter(':checked');
rows.each(function() {
$(this).prop('checked', !$(this).prop('checked'));
});
that.updateRows();
that.updateSelected();
that.trigger('uncheck-some', checked);
checked = that.getSelections();
that.trigger('check-some', checked);
};
BootstrapTable.prototype.checkAll_ = function (checked) {
var rows;
if (!checked) {
rows = this.getSelections();
}
this.$selectAll.add(this.$selectAll_).prop('checked', checked);
this.$selectItem.filter(':enabled').prop('checked', checked);
this.updateRows();
if (checked) {
rows = this.getSelections();
}
this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
};
BootstrapTable.prototype.check = function (index) {
this.check_(true, index);
};
BootstrapTable.prototype.uncheck = function (index) {
this.check_(false, index);
};
BootstrapTable.prototype.check_ = function (checked, index) {
var $el = this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
this.data[index][this.header.stateField] = checked;
this.updateSelected();
this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el);
};
BootstrapTable.prototype.checkBy = function (obj) {
this.checkBy_(true, obj);
};
BootstrapTable.prototype.uncheckBy = function (obj) {
this.checkBy_(false, obj);
};
BootstrapTable.prototype.checkBy_ = function (checked, obj) {
if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
return;
}
var that = this,
rows = [];
$.each(this.options.data, function (index, row) {
if (!row.hasOwnProperty(obj.field)) {
return false;
}
if ($.inArray(row[obj.field], obj.values) !== -1) {
var $el = that.$selectItem.filter(':enabled')
.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
row[that.header.stateField] = checked;
rows.push(row);
that.trigger(checked ? 'check' : 'uncheck', row, $el);
}
});
this.updateSelected();
this.trigger(checked ? 'check-some' : 'uncheck-some', rows);
};
BootstrapTable.prototype.destroy = function () {
this.$el.insertBefore(this.$container);
$(this.options.toolbar).insertBefore(this.$el);
this.$container.next().remove();
this.$container.remove();
this.$el.html(this.$el_.html())
.css('margin-top', '0')
.attr('class', this.$el_.attr('class') || ''); // reset the class
};
BootstrapTable.prototype.showLoading = function () {
this.$tableLoading.show();
};
BootstrapTable.prototype.hideLoading = function () {
this.$tableLoading.hide();
};
BootstrapTable.prototype.togglePagination = function () {
this.options.pagination = !this.options.pagination;
var button = this.$toolbar.find('button[name="paginationSwitch"] i');
if (this.options.pagination) {
button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown);
} else {
button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp);
}
this.updatePagination();
};
BootstrapTable.prototype.refresh = function (params) {
if (params && params.url) {
this.options.url = params.url;
this.options.pageNumber = 1;
}
this.initServer(params && params.silent, params && params.query);
};
BootstrapTable.prototype.resetWidth = function () {
if (this.options.showHeader && this.options.height) {
this.fitHeader();
}
if (this.options.showFooter) {
this.fitFooter();
}
};
BootstrapTable.prototype.showColumn = function (field) {
this.toggleColumn(getFieldIndex(this.columns, field), true, true);
};
BootstrapTable.prototype.hideColumn = function (field) {
this.toggleColumn(getFieldIndex(this.columns, field), false, true);
};
BootstrapTable.prototype.getHiddenColumns = function () {
return $.grep(this.columns, function (column) {
return !column.visible;
});
};
BootstrapTable.prototype.filterBy = function (columns) {
this.filterColumns = $.isEmptyObject(columns) ? {} : columns;
this.options.pageNumber = 1;
this.initSearch();
this.updatePagination();
};
BootstrapTable.prototype.scrollTo = function (value) {
if (typeof value === 'string') {
value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0;
}
if (typeof value === 'number') {
this.$tableBody.scrollTop(value);
}
if (typeof value === 'undefined') {
return this.$tableBody.scrollTop();
}
};
BootstrapTable.prototype.getScrollPosition = function () {
return this.scrollTo();
};
BootstrapTable.prototype.selectPage = function (page) {
if (page > 0 && page <= this.options.totalPages) {
this.options.pageNumber = page;
this.updatePagination();
}
};
BootstrapTable.prototype.prevPage = function () {
if (this.options.pageNumber > 1) {
this.options.pageNumber--;
this.updatePagination();
}
};
BootstrapTable.prototype.nextPage = function () {
if (this.options.pageNumber < this.options.totalPages) {
this.options.pageNumber++;
this.updatePagination();
}
};
BootstrapTable.prototype.toggleView = function () {
this.options.cardView = !this.options.cardView;
this.initHeader();
// Fixed remove toolbar when click cardView button.
//that.initToolbar();
this.initBody();
this.trigger('toggle', this.options.cardView);
};
BootstrapTable.prototype.refreshOptions = function (options) {
//If the objects are equivalent then avoid the call of destroy / init methods
if (compareObjects(this.options, options, true)) {
return;
}
this.options = $.extend(this.options, options);
this.trigger('refresh-options', this.options);
this.destroy();
this.init();
};
BootstrapTable.prototype.resetSearch = function (text) {
var $search = this.$toolbar.find('.search input');
$search.val(text || '');
this.onSearch({currentTarget: $search});
};
BootstrapTable.prototype.expandRow_ = function (expand, index) {
var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', index));
if ($tr.next().is('tr.detail-view') === (expand ? false : true)) {
$tr.find('> td > .detail-icon').click();
}
};
BootstrapTable.prototype.expandRow = function (index) {
this.expandRow_(true, index);
};
BootstrapTable.prototype.collapseRow = function (index) {
this.expandRow_(false, index);
};
BootstrapTable.prototype.expandAllRows = function (isSubTable) {
if (isSubTable) {
var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', 0)),
that = this,
detailIcon = null,
executeInterval = false,
idInterval = -1;
if (!$tr.next().is('tr.detail-view')) {
$tr.find('> td > .detail-icon').click();
executeInterval = true;
} else if (!$tr.next().next().is('tr.detail-view')) {
$tr.next().find(".detail-icon").click();
executeInterval = true;
}
if (executeInterval) {
try {
idInterval = setInterval(function () {
detailIcon = that.$body.find("tr.detail-view").last().find(".detail-icon");
if (detailIcon.length > 0) {
detailIcon.click();
} else {
clearInterval(idInterval);
}
}, 1);
} catch (ex) {
clearInterval(idInterval);
}
}
} else {
var trs = this.$body.children();
for (var i = 0; i < trs.length; i++) {
this.expandRow_(true, $(trs[i]).data("index"));
}
}
};
BootstrapTable.prototype.collapseAllRows = function (isSubTable) {
if (isSubTable) {
this.expandRow_(false, 0);
} else {
var trs = this.$body.children();
for (var i = 0; i < trs.length; i++) {
this.expandRow_(false, $(trs[i]).data("index"));
}
}
};
BootstrapTable.prototype.updateFormatText = function (name, text) {
if (this.options[sprintf('format%s', name)]) {
if (typeof text === 'string') {
this.options[sprintf('format%s', name)] = function () {
return text;
};
} else if (typeof text === 'function') {
this.options[sprintf('format%s', name)] = text;
}
}
this.initToolbar();
this.initPagination();
this.initBody();
};
// BOOTSTRAP TABLE PLUGIN DEFINITION
// =======================
var allowedMethods = [
'getOptions',
'getSelections', 'getAllSelections', 'getData',
'load', 'append', 'prepend', 'remove', 'removeAll',
'insertRow', 'updateRow', 'updateCell', 'updateByUniqueId', 'removeByUniqueId',
'getRowByUniqueId', 'showRow', 'hideRow', 'getRowsHidden',
'mergeCells',
'checkAll', 'uncheckAll', 'checkInvert',
'check', 'uncheck',
'checkBy', 'uncheckBy',
'refresh',
'resetView',
'resetWidth',
'destroy',
'showLoading', 'hideLoading',
'showColumn', 'hideColumn', 'getHiddenColumns',
'filterBy',
'scrollTo',
'getScrollPosition',
'selectPage', 'prevPage', 'nextPage',
'togglePagination',
'toggleView',
'refreshOptions',
'resetSearch',
'expandRow', 'collapseRow', 'expandAllRows', 'collapseAllRows',
'updateFormatText'
];
$.fn.bootstrapTable = function (option) {
var value,
args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
var $this = $(this),
data = $this.data('bootstrap.table'),
options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
typeof option === 'object' && option);
if (typeof option === 'string') {
if ($.inArray(option, allowedMethods) < 0) {
throw new Error("Unknown method: " + option);
}
if (!data) {
return;
}
value = data[option].apply(data, args);
if (option === 'destroy') {
$this.removeData('bootstrap.table');
}
}
if (!data) {
$this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
}
});
return typeof value === 'undefined' ? this : value;
};
$.fn.bootstrapTable.Constructor = BootstrapTable;
$.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
$.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
$.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
$.fn.bootstrapTable.methods = allowedMethods;
$.fn.bootstrapTable.utils = {
sprintf: sprintf,
getFieldIndex: getFieldIndex,
compareObjects: compareObjects,
calculateObjectValue: calculateObjectValue
};
// BOOTSTRAP TABLE INIT
// =======================
$(function () {
$('[data-toggle="table"]').bootstrapTable();
});
}(jQuery);
| bsd-2-clause |
ess-dmsc/event-formation-unit | src/common/DumpFile.h | 5793 | // Copyright (C) 2016-2020 European Spallation Source, ERIC. See LICENSE file
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Template based class for dumping data to HDF5 files
//===----------------------------------------------------------------------===//
#pragma once
#include <vector>
#include <memory>
#include <common/Version.h>
#include <fmt/format.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#pragma GCC diagnostic ignored "-Wpedantic"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <h5cpp/hdf5.hpp>
#pragma GCC diagnostic pop
#define H5_COMPOUND_DEFINE_TYPE(x) using Type = x; using TypeClass = Compound; static TypeClass create(const Type & = Type())
#define H5_COMPOUND_INIT auto type = datatype::Compound::create(sizeof(Type))
#define H5_COMPOUND_INSERT_MEMBER(member) type.insert(STRINGIFY(member), offsetof(Type, member), datatype::create<decltype(Type::member)>())
#define H5_COMPOUND_RETURN return type
// \todo improve reading for multiple files
template<typename T>
class DumpFile {
public:
~DumpFile();
static std::unique_ptr<DumpFile>
create(const boost::filesystem::path &FilePath, size_t MaxMB = 0);
static std::unique_ptr<DumpFile>
open(const boost::filesystem::path &FilePath);
size_t count() const;
void push(const T& Hit);
template<typename Container> void push(const Container& Hits);
void readAt(size_t Index, size_t Count);
static void read(const boost::filesystem::path &FilePath,
std::vector<T> &ExternalData);
/// \todo 9000 is MTU? Correct size is <= 8972 else packet
/// fragmentation will occur.
static constexpr size_t ChunkSize{9000 / sizeof(T)};
boost::filesystem::path get_full_path() const;
void flush();
void rotate();
std::vector<T> Data;
private:
DumpFile(const boost::filesystem::path &file_path, size_t max_Mb);
hdf5::file::File File;
hdf5::datatype::Datatype DataType;
hdf5::node::Dataset DataSet;
hdf5::dataspace::Hyperslab Slab{{0}, {ChunkSize}};
boost::filesystem::path PathBase{};
size_t MaxSize{0};
size_t SequenceNumber{0};
void openRW();
void openR();
void write();
};
template<typename T>
DumpFile<T>::~DumpFile() {
if (Data.size() && File.is_valid() &&
(File.intent() != hdf5::file::AccessFlags::READONLY)) {
flush();
}
}
template<typename T>
DumpFile<T>::DumpFile(const boost::filesystem::path& file_path, size_t max_Mb) {
DataType = hdf5::datatype::create<T>();
MaxSize = max_Mb * 1000000 / sizeof(T);
PathBase = file_path;
}
template<typename T>
std::unique_ptr<DumpFile<T>> DumpFile<T>::create(const boost::filesystem::path& FilePath, size_t MaxMB) {
auto Ret = std::unique_ptr<DumpFile>(new DumpFile(FilePath, MaxMB));
Ret->openRW();
return Ret;
}
template<typename T>
std::unique_ptr<DumpFile<T>> DumpFile<T>::open(const boost::filesystem::path& FilePath) {
auto Ret = std::unique_ptr<DumpFile>(new DumpFile(FilePath, 0));
Ret->openR();
return Ret;
}
template<typename T>
boost::filesystem::path DumpFile<T>::get_full_path() const {
auto Ret = PathBase;
Ret += ("_" + fmt::format("{:0>5}", SequenceNumber) + ".h5");
return Ret;
}
template<typename T>
void DumpFile<T>::openRW() {
using namespace hdf5;
File = file::create(get_full_path(), file::AccessFlags::TRUNCATE);
property::DatasetCreationList dcpl;
dcpl.layout(property::DatasetLayout::CHUNKED);
dcpl.chunk({ChunkSize});
DataSet = File.root().create_dataset(T::DatasetName(), DataType,
dataspace::Simple({0}, {dataspace::Simple::UNLIMITED}), dcpl);
DataSet.attributes.create_from("format_version", T::FormatVersion());
DataSet.attributes.create_from("EFU_version", efu_version());
DataSet.attributes.create_from("EFU_build_string", efu_buildstr());
}
template<typename T>
void DumpFile<T>::rotate() {
SequenceNumber++;
openRW();
}
template<typename T>
void DumpFile<T>::openR() {
using namespace hdf5;
auto Path = PathBase;
Path += ".h5";
File = file::open(Path, file::AccessFlags::READONLY);
DataSet = File.root().get_dataset(T::DatasetName());
// if not initial version, expect it to be well formed
if (T::FormatVersion() > 0) {
uint16_t ver {0};
DataSet.attributes["format_version"].read(ver);
if (ver != T::FormatVersion()) {
throw std::runtime_error("DumpFile version mismatch");
}
}
}
template<typename T>
size_t DumpFile<T>::count() const {
return hdf5::dataspace::Simple(DataSet.dataspace()).current_dimensions().at(0);
}
template<typename T>
void DumpFile<T>::write() {
Slab.offset(0, count());
Slab.block(0, Data.size());
DataSet.extent({count() + Data.size()});
DataSet.write(Data, Slab);
}
template<typename T>
void DumpFile<T>::flush() {
write();
Data.clear();
}
template<typename T>
void DumpFile<T>::readAt(size_t Index, size_t Count) {
Slab.offset(0, Index);
Slab.block(0, Count);
Data.resize(Count);
DataSet.read(Data, Slab);
}
template<typename T>
void DumpFile<T>::read(const boost::filesystem::path &FilePath, std::vector<T> &ExternalData) {
auto TempFile = DumpFile::open(FilePath);
TempFile->readAt(0, TempFile->count());
ExternalData = std::move(TempFile->Data);
}
template<typename T>
void DumpFile<T>::push(const T& Hit) {
Data.push_back(Hit);
if (Data.size() >= ChunkSize) {
flush();
if (MaxSize && (count() >= MaxSize)) {
rotate();
}
}
}
template<typename T>
template<typename Container>
void DumpFile<T>::push(const Container& Hits) {
Data.insert(Data.end(), Hits.begin(), Hits.end());
if (Data.size() >= ChunkSize) {
flush();
if (MaxSize && (count() >= MaxSize)) {
rotate();
}
}
}
| bsd-2-clause |
randombit/botan | src/lib/misc/zfec/zfec_vperm/zfec_vperm.cpp | 51390 | /*
* (C) 2011 Billy Brumley ([email protected])
* (C) 2021 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/zfec.h>
#include <botan/internal/simd_32.h>
#if defined(BOTAN_SIMD_USE_SSE2)
#include <tmmintrin.h>
#endif
namespace Botan {
namespace {
/*
* these tables are for the linear map bx^4 + a -> y(bx^4 + a)
* implemented as two maps:
* a -> y(a)
* b -> y(bx^4)
* and the final output is the sum of these two outputs.
*/
alignas(256) const uint8_t GFTBL[256*32] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0,
0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e,
0x00, 0x20, 0x40, 0x60, 0x80, 0xa0, 0xc0, 0xe0, 0x1d, 0x3d, 0x5d, 0x7d, 0x9d, 0xbd, 0xdd, 0xfd,
0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11,
0x00, 0x30, 0x60, 0x50, 0xc0, 0xf0, 0xa0, 0x90, 0x9d, 0xad, 0xfd, 0xcd, 0x5d, 0x6d, 0x3d, 0x0d,
0x00, 0x04, 0x08, 0x0c, 0x10, 0x14, 0x18, 0x1c, 0x20, 0x24, 0x28, 0x2c, 0x30, 0x34, 0x38, 0x3c,
0x00, 0x40, 0x80, 0xc0, 0x1d, 0x5d, 0x9d, 0xdd, 0x3a, 0x7a, 0xba, 0xfa, 0x27, 0x67, 0xa7, 0xe7,
0x00, 0x05, 0x0a, 0x0f, 0x14, 0x11, 0x1e, 0x1b, 0x28, 0x2d, 0x22, 0x27, 0x3c, 0x39, 0x36, 0x33,
0x00, 0x50, 0xa0, 0xf0, 0x5d, 0x0d, 0xfd, 0xad, 0xba, 0xea, 0x1a, 0x4a, 0xe7, 0xb7, 0x47, 0x17,
0x00, 0x06, 0x0c, 0x0a, 0x18, 0x1e, 0x14, 0x12, 0x30, 0x36, 0x3c, 0x3a, 0x28, 0x2e, 0x24, 0x22,
0x00, 0x60, 0xc0, 0xa0, 0x9d, 0xfd, 0x5d, 0x3d, 0x27, 0x47, 0xe7, 0x87, 0xba, 0xda, 0x7a, 0x1a,
0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d,
0x00, 0x70, 0xe0, 0x90, 0xdd, 0xad, 0x3d, 0x4d, 0xa7, 0xd7, 0x47, 0x37, 0x7a, 0x0a, 0x9a, 0xea,
0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58, 0x60, 0x68, 0x70, 0x78,
0x00, 0x80, 0x1d, 0x9d, 0x3a, 0xba, 0x27, 0xa7, 0x74, 0xf4, 0x69, 0xe9, 0x4e, 0xce, 0x53,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0x04, 0x8a, 0x05, 0x8b, 0x06, 0x88, 0x07, 0x89,
0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58, 0x60, 0x68, 0x70, 0x78,
0x00, 0x8f, 0x03, 0x8c, 0x06, 0x89, 0x05, 0x8a, 0x0c, 0x83, 0x0f, 0x80, 0x0a, 0x85, 0x09, 0x86,
0x00, 0x18, 0x30, 0x28, 0x60, 0x78, 0x50, 0x48, 0xc0, 0xd8, 0xf0, 0xe8, 0xa0, 0xb8, 0x90, 0x88,
0x00, 0x90, 0x3d, 0xad, 0x7a, 0xea, 0x47, 0xd7, 0xf4, 0x64, 0xc9, 0x59, 0x8e, 0x1e, 0xb3, 0x23,
0x00, 0xf5, 0xf7, 0x02, 0xf3, 0x06, 0x04, 0xf1, 0xfb, 0x0e, 0x0c, 0xf9, 0x08, 0xfd, 0xff, 0x0a,
0x00, 0x91, 0x3f, 0xae, 0x7e, 0xef, 0x41, 0xd0, 0xfc, 0x6d, 0xc3, 0x52, 0x82, 0x13, 0xbd, 0x2c,
0x00, 0xe5, 0xd7, 0x32, 0xb3, 0x56, 0x64, 0x81, 0x7b, 0x9e, 0xac, 0x49, 0xc8, 0x2d, 0x1f, 0xfa,
0x00, 0x92, 0x39, 0xab, 0x72, 0xe0, 0x4b, 0xd9, 0xe4, 0x76, 0xdd, 0x4f, 0x96, 0x04, 0xaf, 0x3d,
0x00, 0xd5, 0xb7, 0x62, 0x73, 0xa6, 0xc4, 0x11, 0xe6, 0x33, 0x51, 0x84, 0x95, 0x40, 0x22, 0xf7,
0x00, 0x93, 0x3b, 0xa8, 0x76, 0xe5, 0x4d, 0xde, 0xec, 0x7f, 0xd7, 0x44, 0x9a, 0x09, 0xa1, 0x32,
0x00, 0xc5, 0x97, 0x52, 0x33, 0xf6, 0xa4, 0x61, 0x66, 0xa3, 0xf1, 0x34, 0x55, 0x90, 0xc2, 0x07,
0x00, 0x94, 0x35, 0xa1, 0x6a, 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98, 0x81, 0x7d,
0x00, 0x7b, 0xf6, 0x8d, 0xf1, 0x8a, 0x07, 0x7c, 0xff, 0x84, 0x09, 0x72, 0x0e, 0x75, 0xf8, 0x83,
0x00, 0xfd, 0xe7, 0x1a, 0xd3, 0x2e, 0x34, 0xc9, 0xbb, 0x46, 0x5c, 0xa1, 0x68, 0x95, 0x8f, 0x72,
0x00, 0x6b, 0xd6, 0xbd, 0xb1, 0xda, 0x67, 0x0c, 0x7f, 0x14, 0xa9, 0xc2, 0xce, 0xa5, 0x18, 0x73,
0x00, 0xfe, 0xe1, 0x1f, 0xdf, 0x21, 0x3e, 0xc0, 0xa3, 0x5d, 0x42, 0xbc, 0x7c, 0x82, 0x9d, 0x63,
0x00, 0x5b, 0xb6, 0xed, 0x71, 0x2a, 0xc7, 0x9c, 0xe2, 0xb9, 0x54, 0x0f, 0x93, 0xc8, 0x25, 0x7e,
0x00, 0xff, 0xe3, 0x1c, 0xdb, 0x24, 0x38, 0xc7, 0xab, 0x54, 0x48, 0xb7, 0x70, 0x8f, 0x93, 0x6c,
0x00, 0x4b, 0x96, 0xdd, 0x31, 0x7a, 0xa7, 0xec, 0x62, 0x29, 0xf4, 0xbf, 0x53, 0x18, 0xc5, 0x8e };
inline SIMD_4x32 BOTAN_FUNC_ISA(BOTAN_VPERM_ISA) table_lookup(SIMD_4x32 t, SIMD_4x32 v)
{
#if defined(BOTAN_SIMD_USE_SSE2)
return SIMD_4x32(_mm_shuffle_epi8(t.raw(), v.raw()));
#elif defined(BOTAN_SIMD_USE_NEON)
const uint8x16_t tbl = vreinterpretq_u8_u32(t.raw());
const uint8x16_t idx = vreinterpretq_u8_u32(v.raw());
#if defined(BOTAN_TARGET_ARCH_IS_ARM32)
const uint8x8x2_t tbl2 = { vget_low_u8(tbl), vget_high_u8(tbl) };
return SIMD_4x32(vreinterpretq_u32_u8(
vcombine_u8(vtbl2_u8(tbl2, vget_low_u8(idx)),
vtbl2_u8(tbl2, vget_high_u8(idx)))));
#else
return SIMD_4x32(vreinterpretq_u32_u8(vqtbl1q_u8(tbl, idx)));
#endif
#endif
}
}
BOTAN_FUNC_ISA(BOTAN_VPERM_ISA)
size_t ZFEC::addmul_vperm(uint8_t z[], const uint8_t x[], uint8_t y, size_t size)
{
const auto mask = SIMD_4x32::splat_u8(0x0F);
// fetch the lookup tables for the given y
const auto t_lo = SIMD_4x32::load_le(GFTBL + 32*y);
const auto t_hi = SIMD_4x32::load_le(GFTBL + 32*y + 16);
const size_t orig_size = size;
while(size >= 16)
{
const auto x_1 = SIMD_4x32::load_le(x);
auto z_1 = SIMD_4x32::load_le(z);
// mask to get LO nibble for LO LUT input
const auto x_lo = x_1 & mask;
// mask to get HI nibble for HI LUT input
const auto x_hi = x_1.shr<4>() & mask;
// 16x parallel lookups
const auto r_lo = table_lookup(t_lo, x_lo);
const auto r_hi = table_lookup(t_hi, x_hi);
// sum the outputs.
z_1 ^= r_lo;
z_1 ^= r_hi;
z_1.store_le(z);
x += 16;
z += 16;
size -= 16;
}
return orig_size - size;
}
}
| bsd-2-clause |
effectweb/effectweb-v1.8.5 | src/modules/header/css/SpryTabbedPanels.css | 8742 | @charset "UTF-8";
/* SpryTabbedPanels.css - version 0.6 - Spry Pre-Release 1.6.1 */
/* Copyright (c) 2006. Adobe Systems Incorporated. All rights reserved. */
/* Horizontal Tabbed Panels
*
* The default style for a TabbedPanels widget places all tab buttons
* (left aligned) above the content panel.
*/
/* This is the selector for the main TabbedPanels container. For our
* default style, this container does not contribute anything visually,
* but it is floated left to make sure that any floating or clearing done
* with any of its child elements are contained completely within the
* TabbedPanels container, to minimize any impact or undesireable
* interaction with other floated elements on the page that may be used
* for layout.
*
* If you want to constrain the width of the TabbedPanels widget, set a
* width on the TabbedPanels container. By default, the TabbedPanels widget
* expands horizontally to fill up available space.
*
* The name of the class ("TabbedPanels") used in this selector is not
* necessary to make the widget function. You can use any class name you
* want to style the TabbedPanels container.
*/
#TabbedPanels1
{
color: #000;
}
.TabbedPanels {
overflow: hidden;
margin: 0px;
padding: 0px;
clear: none;
width: 100%; /* IE Hack to force proper layout when preceded by a paragraph. (hasLayout Bug)*/
color: #000;
}
/* This is the selector for the TabGroup. The TabGroup container houses
* all of the tab buttons for each tabbed panel in the widget. This container
* does not contribute anything visually to the look of the widget for our
* default style.
*
* The name of the class ("TabbedPanelsTabGroup") used in this selector is not
* necessary to make the widget function. You can use any class name you
* want to style the TabGroup container.
*/
.TabbedPanelsTabGroup {
margin: 0px;
padding: 0px;
}
/* This is the selector for the TabbedPanelsTab. This container houses
* the title for the panel. This is also the tab "button" that the user clicks
* on to activate the corresponding content panel so that it appears on top
* of the other tabbed panels contained in the widget.
*
* For our default style, each tab is positioned relatively 1 pixel down from
* where it wold normally render. This allows each tab to overlap the content
* panel that renders below it. Each tab is rendered with a 1 pixel bottom
* border that has a color that matches the top border of the current content
* panel. This gives the appearance that the tab is being drawn behind the
* content panel.
*
* The name of the class ("TabbedPanelsTab") used in this selector is not
* necessary to make the widget function. You can use any class name you want
* to style this tab container.
*/
.TabbedPanelsTab {
top: 1px;
float: left;
padding: 4px 10px;
margin: 0px 1px 0px 0px;
font: bold 0.7em sans-serif;
background-color: #DDD;
list-style: none;
border-left: solid 1px #CCC;
border-bottom: solid 1px #999;
border-top: solid 1px #999;
border-right: solid 1px #999;
-moz-user-select: none;
-khtml-user-select: none;
cursor: pointer;
}
/* This selector is an example of how to change the appearnce of a tab button
* container as the mouse enters it. The class "TabbedPanelsTabHover" is
* programatically added and removed from the tab element as the mouse enters
* and exits the container.
*/
.TabbedPanelsTabHover {
background-color: #CCC;
}
/* This selector is an example of how to change the appearance of a tab button
* container after the user has clicked on it to activate a content panel.
* The class "TabbedPanelsTabSelected" is programatically added and removed
* from the tab element as the user clicks on the tab button containers in
* the widget.
*
* As mentioned above, for our default style, tab buttons are positioned
* 1 pixel down from where it would normally render. When the tab button is
* selected, we change its bottom border to match the background color of the
* content panel so that it looks like the tab is part of the content panel.
*/
.TabbedPanelsTabSelected {
background-color: #EEE;
border-bottom: 1px solid #EEE;
}
/* This selector is an example of how to make a link inside of a tab button
* look like normal text. Users may want to use links inside of a tab button
* so that when it gets focus, the text *inside* the tab button gets a focus
* ring around it, instead of the focus ring around the entire tab.
*/
.TabbedPanelsTab a {
color: black;
text-decoration: none;
}
/* This is the selector for the ContentGroup. The ContentGroup container houses
* all of the content panels for each tabbed panel in the widget. For our
* default style, this container provides the background color and borders that
* surround the content.
*
* The name of the class ("TabbedPanelsContentGroup") used in this selector is
* not necessary to make the widget function. You can use any class name you
* want to style the ContentGroup container.
*/
.TabbedPanelsContentGroup {
clear: both;
border-left: solid 1px #CCC;
border-bottom: solid 1px #CCC;
border-top: solid 1px #999;
border-right: solid 1px #999;
background-color: #EEE;
}
/* This is the selector for the Content panel. The Content panel holds the
* content for a single tabbed panel. For our default style, this container
* provides some padding, so that the content is not pushed up against the
* widget borders.
*
* The name of the class ("TabbedPanelsContent") used in this selector is
* not necessary to make the widget function. You can use any class name you
* want to style the Content container.
*/
.TabbedPanelsContent {
overflow: hidden;
padding: 4px;
}
/* This selector is an example of how to change the appearnce of the currently
* active container panel. The class "TabbedPanelsContentVisible" is
* programatically added and removed from the content element as the panel
* is activated/deactivated.
*/
.TabbedPanelsContentVisible {
}
/* Vertical Tabbed Panels
*
* The following rules override some of the default rules above so that the
* TabbedPanels widget renders with its tab buttons along the left side of
* the currently active content panel.
*
* With the rules defined below, the only change that will have to be made
* to switch a horizontal tabbed panels widget to a vertical tabbed panels
* widget, is to use the "VTabbedPanels" class on the top-level widget
* container element, instead of "TabbedPanels".
*/
.VTabbedPanels {
overflow: hidden;
zoom: 1;
}
/* This selector floats the TabGroup so that the tab buttons it contains
* render to the left of the active content panel. A border is drawn around
* the group container to make it look like a list container.
*/
.VTabbedPanels .TabbedPanelsTabGroup {
float: left;
width: 10em;
height: 20em;
background-color: #EEE;
position: relative;
border-top: solid 1px #999;
border-right: solid 1px #999;
border-left: solid 1px #CCC;
border-bottom: solid 1px #CCC;
}
/* This selector disables the float property that is placed on each tab button
* by the default TabbedPanelsTab selector rule above. It also draws a bottom
* border for the tab. The tab button will get its left and right border from
* the TabGroup, and its top border from the TabGroup or tab button above it.
*/
.VTabbedPanels .TabbedPanelsTab {
float: none;
margin: 0px;
border-top: none;
border-left: none;
border-right: none;
}
/* This selector disables the float property that is placed on each tab button
* by the default TabbedPanelsTab selector rule above. It also draws a bottom
* border for the tab. The tab button will get its left and right border from
* the TabGroup, and its top border from the TabGroup or tab button above it.
*/
.VTabbedPanels .TabbedPanelsTabSelected {
background-color: #EEE;
border-bottom: solid 1px #999;
}
/* This selector floats the content panels for the widget so that they
* render to the right of the tabbed buttons.
*/
.VTabbedPanels .TabbedPanelsContentGroup {
clear: none;
float: left;
padding: 0px;
width: 30em;
height: 20em;
}
/* Styles for Printing */
@media print {
.TabbedPanels {
overflow: visible !important;
}
.TabbedPanelsContentGroup {
display: block !important;
overflow: visible !important;
height: auto !important;
}
.TabbedPanelsContent {
overflow: visible !important;
display: block !important;
clear:both !important;
}
.TabbedPanelsTab {
overflow: visible !important;
display: block !important;
clear:both !important;
}
} | bsd-2-clause |
Astralix/ethernut32 | nut/hwtest/cm3/stm/trampoline/Makefile | 2103 | #
# Copyright (C) 2001-2006 by egnite Software GmbH. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. All advertising materials mentioning features or use of this
# software must display the following acknowledgement:
#
# This product includes software developed by egnite Software GmbH
# and its contributors.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# For additional information see http://www.ethernut.de/
#
PROJ = trampoline
include ../Makedefs
SRCS = $(PROJ).c
OBJS = $(SRCS:.c=.o)
TARG = $(PROJ).hex
all: $(OBJS) $(TARG) $(ITARG) $(DTARG)
include ../Makerules
clean:
-rm -f $(OBJS)
-rm -f $(TARG) $(ITARG) $(DTARG)
-rm -f $(PROJ).eep
-rm -f $(PROJ).obj
-rm -f $(PROJ).map
-rm -f $(PROJ).dbg
-rm -f $(PROJ).cof
-rm -f $(PROJ).mp
-rm -f $(SRCS:.c=.lst)
-rm -f $(SRCS:.c=.lis)
-rm -f $(SRCS:.c=.s)
-rm -f $(SRCS:.c=.bak)
-rm -f $(SRCS:.c=.i)
| bsd-2-clause |
marcotcr/lime | lime/exceptions.py | 55 | class LimeError(Exception):
"""Raise for errors"""
| bsd-2-clause |
xythobuz/yasab | bootloader/util.c | 2158 | /*
* spm.c
*
* Copyright (c) 2012, Thomas Buck <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <avr/io.h>
#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include "global.h"
void set(uint8_t *d, uint8_t c, uint16_t l) {
uint16_t i;
for (i = 0; i < l; i++) {
d[i] = c;
}
}
void gotoApplication(void) __attribute__ ((noreturn));
void gotoApplication(void) {
void (*app)(void) = 0x0000;
// Free Hardware Resources
for (uint8_t i = 0; i < serialAvailable(); i++) {
serialClose(i);
}
cli();
TCRA = TCRB = TIMS = 0; // Reset timer
// Fix Interrupt Vectors
uint8_t t = INTERRUPTMOVE;
INTERRUPTMOVE = t | (1 << IVCE);
INTERRUPTMOVE = t & ~(1 << IVSEL);
// Call main program
#ifdef EIND
EIND = 0; // Bug in gcc for Flash > 128KB
#endif
app();
}
| bsd-2-clause |
laeotropic/HTTP-Proxy | deps/asio-1.10.1/doc/asio/reference/basic_serial_port/lowest_layer/overload2.html | 3764 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_serial_port::lowest_layer (2 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Asio">
<link rel="up" href="../lowest_layer.html" title="basic_serial_port::lowest_layer">
<link rel="prev" href="overload1.html" title="basic_serial_port::lowest_layer (1 of 2 overloads)">
<link rel="next" href="../lowest_layer_type.html" title="basic_serial_port::lowest_layer_type">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../lowest_layer.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../lowest_layer_type.html"><img src="../../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="asio.reference.basic_serial_port.lowest_layer.overload2"></a><a class="link" href="overload2.html" title="basic_serial_port::lowest_layer (2 of 2 overloads)">basic_serial_port::lowest_layer
(2 of 2 overloads)</a>
</h5></div></div></div>
<p>
Get a const reference to the lowest layer.
</p>
<pre class="programlisting"><span class="keyword">const</span> <span class="identifier">lowest_layer_type</span> <span class="special">&</span> <span class="identifier">lowest_layer</span><span class="special">()</span> <span class="keyword">const</span><span class="special">;</span>
</pre>
<p>
This function returns a const reference to the lowest layer in a stack
of layers. Since a <a class="link" href="../../basic_serial_port.html" title="basic_serial_port"><code class="computeroutput"><span class="identifier">basic_serial_port</span></code></a> cannot contain
any further layers, it simply returns a reference to itself.
</p>
<h6>
<a name="asio.reference.basic_serial_port.lowest_layer.overload2.h0"></a>
<span><a name="asio.reference.basic_serial_port.lowest_layer.overload2.return_value"></a></span><a class="link" href="overload2.html#asio.reference.basic_serial_port.lowest_layer.overload2.return_value">Return
Value</a>
</h6>
<p>
A const reference to the lowest layer in the stack of layers. Ownership
is not transferred to the caller.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2013 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../lowest_layer.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../lowest_layer_type.html"><img src="../../../../next.png" alt="Next"></a>
</div>
</body>
</html>
| bsd-2-clause |
ahocevar/ol3 | src/ol/layer/MapboxVector.js | 18944 | /**
* @module ol/layer/MapboxVector
*/
import BaseEvent from '../events/Event.js';
import EventType from '../events/EventType.js';
import GeometryType from '../geom/GeometryType.js';
import MVT from '../format/MVT.js';
import RenderFeature from '../render/Feature.js';
import SourceState from '../source/State.js';
import TileEventType from '../source/TileEventType.js';
import VectorTileLayer from '../layer/VectorTile.js';
import VectorTileSource from '../source/VectorTile.js';
import {Fill, Style} from '../style.js';
import {applyStyle, setupVectorSource} from 'ol-mapbox-style';
import {fromExtent} from '../geom/Polygon.js';
import {getValue} from 'ol-mapbox-style/dist/stylefunction.js';
const mapboxBaseUrl = 'https://api.mapbox.com';
/**
* Gets the path from a mapbox:// URL.
* @param {string} url The Mapbox URL.
* @return {string} The path.
* @private
*/
export function getMapboxPath(url) {
const startsWith = 'mapbox://';
if (url.indexOf(startsWith) !== 0) {
return '';
}
return url.slice(startsWith.length);
}
/**
* Turns mapbox:// sprite URLs into resolvable URLs.
* @param {string} url The sprite URL.
* @param {string} token The access token.
* @return {string} A resolvable URL.
* @private
*/
export function normalizeSpriteUrl(url, token) {
const mapboxPath = getMapboxPath(url);
if (!mapboxPath) {
return url;
}
const startsWith = 'sprites/';
if (mapboxPath.indexOf(startsWith) !== 0) {
throw new Error(`unexpected sprites url: ${url}`);
}
const sprite = mapboxPath.slice(startsWith.length);
return `${mapboxBaseUrl}/styles/v1/${sprite}/sprite?access_token=${token}`;
}
/**
* Turns mapbox:// glyphs URLs into resolvable URLs.
* @param {string} url The glyphs URL.
* @param {string} token The access token.
* @return {string} A resolvable URL.
* @private
*/
export function normalizeGlyphsUrl(url, token) {
const mapboxPath = getMapboxPath(url);
if (!mapboxPath) {
return url;
}
const startsWith = 'fonts/';
if (mapboxPath.indexOf(startsWith) !== 0) {
throw new Error(`unexpected fonts url: ${url}`);
}
const font = mapboxPath.slice(startsWith.length);
return `${mapboxBaseUrl}/fonts/v1/${font}/0-255.pbf?access_token=${token}`;
}
/**
* Turns mapbox:// style URLs into resolvable URLs.
* @param {string} url The style URL.
* @param {string} token The access token.
* @return {string} A resolvable URL.
* @private
*/
export function normalizeStyleUrl(url, token) {
const mapboxPath = getMapboxPath(url);
if (!mapboxPath) {
return url;
}
const startsWith = 'styles/';
if (mapboxPath.indexOf(startsWith) !== 0) {
throw new Error(`unexpected style url: ${url}`);
}
const style = mapboxPath.slice(startsWith.length);
return `${mapboxBaseUrl}/styles/v1/${style}?&access_token=${token}`;
}
/**
* Turns mapbox:// source URLs into vector tile URL templates.
* @param {string} url The source URL.
* @param {string} token The access token.
* @param {string} tokenParam The access token key.
* @return {string} A vector tile template.
* @private
*/
export function normalizeSourceUrl(url, token, tokenParam) {
const mapboxPath = getMapboxPath(url);
if (!mapboxPath) {
if (!token) {
return url;
}
const urlObject = new URL(url, location.href);
urlObject.searchParams.set(tokenParam, token);
return decodeURI(urlObject.href);
}
return `https://{a-d}.tiles.mapbox.com/v4/${mapboxPath}/{z}/{x}/{y}.vector.pbf?access_token=${token}`;
}
/**
* @classdesc
* Event emitted on configuration or loading error.
*/
class ErrorEvent extends BaseEvent {
/**
* @param {Error} error error object.
*/
constructor(error) {
super(EventType.ERROR);
/**
* @type {Error}
*/
this.error = error;
}
}
/**
* @typedef {Object} StyleObject
* @property {Object<string, SourceObject>} sources The style sources.
* @property {string} sprite The sprite URL.
* @property {string} glyphs The glyphs URL.
* @property {Array<LayerObject>} layers The style layers.
*/
/**
* @typedef {Object} SourceObject
* @property {string} url The source URL.
* @property {SourceType} type The source type.
* @property {Array<string>} [tiles] TileJSON tiles.
*/
/**
* The Mapbox source type.
* @enum {string}
*/
const SourceType = {
VECTOR: 'vector',
};
/**
* @typedef {Object} LayerObject
* @property {string} id The layer id.
* @property {string} type The layer type.
* @property {string} source The source id.
* @property {Object} layout The layout.
* @property {Object} paint The paint.
*/
/**
* @typedef {Object} Options
* @property {string} styleUrl The URL of the Mapbox style object to use for this layer. For a
* style created with Mapbox Studio and hosted on Mapbox, this will look like
* 'mapbox://styles/you/your-style'.
* @property {string} [accessToken] The access token for your Mapbox style. This has to be provided
* for `mapbox://` style urls. For `https://` and other urls, any access key must be the last query
* parameter of the style url.
* @property {string} [source] If your style uses more than one source, you need to use either the
* `source` property or the `layers` property to limit rendering to a single vector source. The
* `source` property corresponds to the id of a vector source in your Mapbox style.
* @property {Array<string>} [layers] Limit rendering to the list of included layers. All layers
* must share the same vector source. If your style uses more than one source, you need to use
* either the `source` property or the `layers` property to limit rendering to a single vector
* source.
* @property {boolean} [declutter=true] Declutter images and text. Decluttering is applied to all
* image and text styles of all Vector and VectorTile layers that have set this to `true`. The priority
* is defined by the z-index of the layer, the `zIndex` of the style and the render order of features.
* Higher z-index means higher priority. Within the same z-index, a feature rendered before another has
* higher priority.
* @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
* @property {number} [opacity=1] Opacity (0, 1).
* @property {boolean} [visible=true] Visibility.
* @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering. The layer will not be
* rendered outside of this extent.
* @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers
* will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
* for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
* method was used.
* @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
* visible.
* @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
* be visible.
* @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
* visible.
* @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
* be visible.
* @property {import("../render.js").OrderFunction} [renderOrder] Render order. Function to be used when sorting
* features before rendering. By default features are drawn in the order that they are created. Use
* `null` to avoid the sort, but get an undefined draw order.
* @property {number} [renderBuffer=100] The buffer in pixels around the tile extent used by the
* renderer when getting features from the vector tile for the rendering or hit-detection.
* Recommended value: Vector tiles are usually generated with a buffer, so this value should match
* the largest possible buffer of the used tiles. It should be at least the size of the largest
* point symbol or line width.
* @property {import("./VectorTileRenderType.js").default|string} [renderMode='hybrid'] Render mode for vector tiles:
* * `'hybrid'`: Polygon and line elements are rendered as images, so pixels are scaled during zoom
* animations. Point symbols and texts are accurately rendered as vectors and can stay upright on
* rotated views.
* * `'vector'`: Everything is rendered as vectors. Use this mode for improved performance on vector
* tile layers with only a few rendered features (e.g. for highlighting a subset of features of
* another layer with the same source).
* @property {import("../PluggableMap.js").default} [map] Sets the layer as overlay on a map. The map will not manage
* this layer in its layers collection, and the layer will be rendered on top. This is useful for
* temporary layers. The standard way to add a layer to a map and have it managed by the map is to
* use {@link import("../PluggableMap.js").default#addLayer map.addLayer()}.
* @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will be
* recreated during animations. This means that no vectors will be shown clipped, but the setting
* will have a performance impact for large amounts of vector data. When set to `false`, batches
* will be recreated when no animation is active.
* @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will be
* recreated during interactions. See also `updateWhileAnimating`.
* @property {number} [preload=0] Preload. Load low-resolution tiles up to `preload` levels. `0`
* means no preloading.
* @property {boolean} [useInterimTilesOnError=true] Use interim tiles on error.
* @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
*/
/**
* @classdesc
* A vector tile layer based on a Mapbox style that uses a single vector source. Configure
* the layer with the `styleUrl` and `accessToken` shown in Mapbox Studio's share panel.
* If the style uses more than one source, use the `source` property to choose a single
* vector source. If you want to render a subset of the layers in the style, use the `layers`
* property (all layers must share the same vector source). See the constructor options for
* more detail.
*
* var map = new Map({
* view: new View({
* center: [0, 0],
* zoom: 1
* }),
* layers: [
* new MapboxVectorLayer({
* styleUrl: 'mapbox://styles/mapbox/bright-v9',
* accessToken: 'your-mapbox-access-token-here'
* })
* ],
* target: 'map'
* });
*
* On configuration or loading error, the layer will trigger an `'error'` event. Listeners
* will receive an object with an `error` property that can be used to diagnose the problem.
*
* @param {Options} options Options.
* @extends {VectorTileLayer}
* @fires module:ol/events/Event~BaseEvent#event:error
* @api
*/
class MapboxVectorLayer extends VectorTileLayer {
/**
* @param {Options} options Layer options. At a minimum, `styleUrl` and `accessToken`
* must be provided.
*/
constructor(options) {
const declutter = 'declutter' in options ? options.declutter : true;
const source = new VectorTileSource({
state: SourceState.LOADING,
format: new MVT(),
});
super({
source: source,
declutter: declutter,
className: options.className,
opacity: options.opacity,
visible: options.visible,
zIndex: options.zIndex,
minResolution: options.minResolution,
maxResolution: options.maxResolution,
minZoom: options.minZoom,
maxZoom: options.maxZoom,
renderOrder: options.renderOrder,
renderBuffer: options.renderBuffer,
renderMode: options.renderMode,
map: options.map,
updateWhileAnimating: options.updateWhileAnimating,
updateWhileInteracting: options.updateWhileInteracting,
preload: options.preload,
useInterimTilesOnError: options.useInterimTilesOnError,
properties: options.properties,
});
this.sourceId = options.source;
this.layers = options.layers;
if (options.accessToken) {
this.accessToken = options.accessToken;
} else {
const url = new URL(options.styleUrl, location.href);
// The last search parameter is the access token
url.searchParams.forEach((value, key) => {
this.accessToken = value;
this.accessTokenParam_ = key;
});
}
this.fetchStyle(options.styleUrl);
}
/**
* Fetch the style object.
* @param {string} styleUrl The URL of the style to load.
* @protected
*/
fetchStyle(styleUrl) {
const url = normalizeStyleUrl(styleUrl, this.accessToken);
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(
`unexpected response when fetching style: ${response.status}`
);
}
return response.json();
})
.then((style) => {
this.onStyleLoad(style);
})
.catch((error) => {
this.handleError(error);
});
}
/**
* Handle the loaded style object.
* @param {StyleObject} style The loaded style.
* @protected
*/
onStyleLoad(style) {
let sourceId;
let sourceIdOrLayersList;
if (this.layers) {
// confirm all layers share the same source
const lookup = {};
for (let i = 0; i < style.layers.length; ++i) {
const layer = style.layers[i];
if (layer.source) {
lookup[layer.id] = layer.source;
}
}
let firstSource;
for (let i = 0; i < this.layers.length; ++i) {
const candidate = lookup[this.layers[i]];
if (!candidate) {
this.handleError(
new Error(`could not find source for ${this.layers[i]}`)
);
return;
}
if (!firstSource) {
firstSource = candidate;
} else if (firstSource !== candidate) {
this.handleError(
new Error(
`layers can only use a single source, found ${firstSource} and ${candidate}`
)
);
return;
}
}
sourceId = firstSource;
sourceIdOrLayersList = this.layers;
} else {
sourceId = this.sourceId;
sourceIdOrLayersList = sourceId;
}
if (!sourceIdOrLayersList) {
// default to the first source in the style
sourceId = Object.keys(style.sources)[0];
sourceIdOrLayersList = sourceId;
}
if (style.sprite) {
style.sprite = normalizeSpriteUrl(style.sprite, this.accessToken);
}
if (style.glyphs) {
style.glyphs = normalizeGlyphsUrl(style.glyphs, this.accessToken);
}
const styleSource = style.sources[sourceId];
if (styleSource.type !== SourceType.VECTOR) {
this.handleError(
new Error(`only works for vector sources, found ${styleSource.type}`)
);
return;
}
const source = this.getSource();
if (styleSource.url && styleSource.url.indexOf('mapbox://') === 0) {
// Tile source url, handle it directly
source.setUrl(
normalizeSourceUrl(
styleSource.url,
this.accessToken,
this.accessTokenParam_
)
);
applyStyle(this, style, sourceIdOrLayersList)
.then(() => {
this.configureSource(source, style);
})
.catch((error) => {
this.handleError(error);
});
} else {
// TileJSON url, let ol-mapbox-style handle it
if (styleSource.tiles) {
styleSource.tiles = styleSource.tiles.map((url) =>
normalizeSourceUrl(url, this.accessToken, this.accessTokenParam_)
);
}
setupVectorSource(
styleSource,
styleSource.url
? normalizeSourceUrl(
styleSource.url,
this.accessToken,
this.accessTokenParam_
)
: undefined
).then((source) => {
applyStyle(this, style, sourceIdOrLayersList)
.then(() => {
this.configureSource(source, style);
})
.catch((error) => {
this.configureSource(source, style);
this.handleError(error);
});
});
}
}
/**
* Applies configuration from the provided source to this layer's source,
* and reconfigures the loader to add a feature that renders the background,
* if the style is configured with a background.
* @param {import("../source/VectorTile.js").default} source The source to configure from.
* @param {StyleObject} style The style to configure the background from.
*/
configureSource(source, style) {
const targetSource = this.getSource();
if (source !== targetSource) {
targetSource.setAttributions(source.getAttributions());
targetSource.setTileUrlFunction(source.getTileUrlFunction());
targetSource.setTileLoadFunction(source.getTileLoadFunction());
targetSource.tileGrid = source.tileGrid;
}
const background = style.layers.find(
(layer) => layer.type === 'background'
);
if (
background &&
(!background.layout || background.layout.visibility !== 'none')
) {
const style = new Style({
fill: new Fill(),
});
targetSource.addEventListener(TileEventType.TILELOADEND, (event) => {
const tile = /** @type {import("../VectorTile.js").default} */ (
/** @type {import("../source/Tile.js").TileSourceEvent} */ (event)
.tile
);
const styleFuntion = () => {
const opacity =
/** @type {number} */ (
getValue(
background,
'paint',
'background-opacity',
tile.tileCoord[0]
)
) || 1;
const color = /** @type {*} */ (
getValue(background, 'paint', 'background-color', tile.tileCoord[0])
);
style
.getFill()
.setColor([
color.r * 255,
color.g * 255,
color.b * 255,
color.a * opacity,
]);
return style;
};
const extentGeometry = fromExtent(
targetSource.tileGrid.getTileCoordExtent(tile.tileCoord)
);
const renderFeature = new RenderFeature(
GeometryType.POLYGON,
extentGeometry.getFlatCoordinates(),
extentGeometry.getEnds(),
{layer: background.id},
undefined
);
renderFeature.styleFunction = styleFuntion;
tile.getFeatures().unshift(renderFeature);
});
}
targetSource.setState(SourceState.READY);
}
/**
* Handle configuration or loading error.
* @param {Error} error The error.
* @protected
*/
handleError(error) {
this.dispatchEvent(new ErrorEvent(error));
const source = this.getSource();
source.setState(SourceState.ERROR);
}
}
export default MapboxVectorLayer;
| bsd-2-clause |
laeotropic/HTTP-Proxy | deps/asio-1.10.1/src/examples/cpp03/porthopper/protocol.hpp | 4270 | //
// protocol.hpp
// ~~~~~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef PORTHOPPER_PROTOCOL_HPP
#define PORTHOPPER_PROTOCOL_HPP
#include <boost/array.hpp>
#include <asio.hpp>
#include <cstring>
#include <iomanip>
#include <string>
#include <strstream>
// This request is sent by the client to the server over a TCP connection.
// The client uses it to perform three functions:
// - To request that data start being sent to a given port.
// - To request that data is no longer sent to a given port.
// - To change the target port to another.
class control_request
{
public:
// Construct an empty request. Used when receiving.
control_request()
{
}
// Create a request to start sending data to a given port.
static const control_request start(unsigned short port)
{
return control_request(0, port);
}
// Create a request to stop sending data to a given port.
static const control_request stop(unsigned short port)
{
return control_request(port, 0);
}
// Create a request to change the port that data is sent to.
static const control_request change(
unsigned short old_port, unsigned short new_port)
{
return control_request(old_port, new_port);
}
// Get the old port. Returns 0 for start requests.
unsigned short old_port() const
{
std::istrstream is(data_, encoded_port_size);
unsigned short port = 0;
is >> std::setw(encoded_port_size) >> std::hex >> port;
return port;
}
// Get the new port. Returns 0 for stop requests.
unsigned short new_port() const
{
std::istrstream is(data_ + encoded_port_size, encoded_port_size);
unsigned short port = 0;
is >> std::setw(encoded_port_size) >> std::hex >> port;
return port;
}
// Obtain buffers for reading from or writing to a socket.
boost::array<asio::mutable_buffer, 1> to_buffers()
{
boost::array<asio::mutable_buffer, 1> buffers
= { { asio::buffer(data_) } };
return buffers;
}
private:
// Construct with specified old and new ports.
control_request(unsigned short old_port_number,
unsigned short new_port_number)
{
std::ostrstream os(data_, control_request_size);
os << std::setw(encoded_port_size) << std::hex << old_port_number;
os << std::setw(encoded_port_size) << std::hex << new_port_number;
}
// The length in bytes of a control_request and its components.
enum
{
encoded_port_size = 4, // 16-bit port in hex.
control_request_size = encoded_port_size * 2
};
// The encoded request data.
char data_[control_request_size];
};
// This frame is sent from the server to subscribed clients over UDP.
class frame
{
public:
// The maximum allowable length of the payload.
enum { payload_size = 32 };
// Construct an empty frame. Used when receiving.
frame()
{
}
// Construct a frame with specified frame number and payload.
frame(unsigned long frame_number, const std::string& payload_data)
{
std::ostrstream os(data_, frame_size);
os << std::setw(encoded_number_size) << std::hex << frame_number;
os << std::setw(payload_size)
<< std::setfill(' ') << payload_data.substr(0, payload_size);
}
// Get the frame number.
unsigned long number() const
{
std::istrstream is(data_, encoded_number_size);
unsigned long frame_number = 0;
is >> std::setw(encoded_number_size) >> std::hex >> frame_number;
return frame_number;
}
// Get the payload data.
const std::string payload() const
{
return std::string(data_ + encoded_number_size, payload_size);
}
// Obtain buffers for reading from or writing to a socket.
boost::array<asio::mutable_buffer, 1> to_buffers()
{
boost::array<asio::mutable_buffer, 1> buffers
= { { asio::buffer(data_) } };
return buffers;
}
private:
// The length in bytes of a frame and its components.
enum
{
encoded_number_size = 8, // Frame number in hex.
frame_size = encoded_number_size + payload_size
};
// The encoded frame data.
char data_[frame_size];
};
#endif // PORTHOPPER_PROTOCOL_HPP
| bsd-2-clause |
asmodehn/WkCore | depends/tinycthread/test/Makefile | 2642 | #-----------------------------------------------------------------------------------------
# Makefile for GCC & gmake (Linux, Windows/MinGW, OpenSolaris, etc).
#-----------------------------------------------------------------------------------------
# Copyright (c) 2012 Marcus Geelnard
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
#-----------------------------------------------------------------------------------------
# A simple hack to check if we are on Windows or not (i.e. are we using mingw32-make?)
ifeq ($(findstring mingw32, $(MAKE)), mingw32)
WINDOWS=1
endif
# Compiler settings
CC = gcc
CFLAGS = -W -std=c99 -pedantic -O3 -c -I../source
# CFLAGS = -W -O3 -c -I../source
LFLAGS =
LIBS =
# Non-windows systems need pthread and rt
ifndef WINDOWS
LIBS += -lpthread -lrt
endif
# MinGW32 GCC 4.5 link problem fix
ifdef WINDOWS
ifeq ($(findstring 4.5.,$(shell g++ -dumpversion)), 4.5.)
LFLAGS += -static-libgcc
endif
endif
# Misc. system commands
ifdef WINDOWS
RM = del /Q
else
RM = rm -f
endif
# File endings
ifdef WINDOWS
EXE = .exe
else
EXE =
endif
# Object files for the hello program
HELLO_OBJS = hello.o
# Object files for the test program
TEST_OBJS = test.o
# TinyCThread object files
TINYCTHREAD_OBJS = tinycthread.o
all: hello$(EXE) test$(EXE)
clean:
$(RM) hello$(EXE) test$(EXE) $(HELLO_OBJS) $(TEST_OBJS) $(TINYCTHREAD_OBJS)
test$(EXE): $(TEST_OBJS) $(TINYCTHREAD_OBJS)
$(CC) $(LFLAGS) -o $@ $(TEST_OBJS) $(TINYCTHREAD_OBJS) $(LIBS)
hello$(EXE): $(HELLO_OBJS) $(TINYCTHREAD_OBJS)
$(CC) $(LFLAGS) -o $@ $(HELLO_OBJS) $(TINYCTHREAD_OBJS) $(LIBS)
%.o: %.cpp
$(CC) $(CFLAGS) $<
%.o: ../source/%.c
$(CC) $(CFLAGS) $<
# Dependencies
hello.o: hello.c ../source/tinycthread.h
test.o: test.c ../source/tinycthread.h
tinycthread.o: ../source/tinycthread.c ../source/tinycthread.h
| bsd-2-clause |
alexander-t/selenium-samples | src/test/java/se/tarnowski/sample/async/ImplicitWaitTest.java | 2200 | /*
* Copyright (c) 2012, Alexander Tarnowski
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package se.tarnowski.sample.async;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import se.tarnowski.sample.page.TestPage;
import java.util.concurrent.TimeUnit;
/**
* Demonstrates the use of implicit waits - the simples way forward if you don't care about Ajax.
*/
public class ImplicitWaitTest {
@Test
public void run() {
WebDriver webDriver = new HtmlUnitDriver(true);
webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
webDriver.get("http://localhost:8080/delayed_elements.html");
TestPage page = new TestPage(webDriver);
page.clickDelayedDivButton();
System.err.println("Clicking...");
System.err.println(page.getDelayedDiv().getText());
System.err.println("Done!");
}
}
| bsd-2-clause |
zmwangx/homebrew-core | Formula/fdclone.rb | 1604 | class Fdclone < Formula
desc "Console-based file manager"
homepage "https://hp.vector.co.jp/authors/VA012337/soft/fd/"
url "http://www.unixusers.net/src/fdclone/FD-3.01h.tar.gz"
sha256 "24be8af52faa48cd6f123d55cfca45d21e5fd1dc16bed24f6686497429f3e2cf"
bottle do
sha256 "84cacf0bc5a76449dc1e0a00999424eed4e580367ff018c26a82a5fd78315896" => :catalina
sha256 "d312c649a0a3691eee27febe3c579250fda9851ae7fe800712b28dfcbd8a6beb" => :mojave
sha256 "58aa669b9e490b8d744bb22948f1ef37549a35bbff0cbbd216ee76251d4511d9" => :high_sierra
sha256 "0fd727178f488ed0c7f32f5b89aa6d38385ebe8377dc2c8abca84ce9777e6cae" => :sierra
sha256 "c890b9824129c9a4ac969ff4930532841de0cce4f11274f9631029af290561ba" => :el_capitan
end
depends_on "nkf" => :build
uses_from_macos "ncurses"
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/86107cf/fdclone/3.01b.patch"
sha256 "c4159db3052d7e4abec57ca719ff37f5acff626654ab4c1b513d7879dcd1eb78"
end
def install
ENV.deparallelize
system "make", "PREFIX=#{prefix}", "all"
system "make", "MANTOP=#{man}", "install"
%w[README FAQ HISTORY LICENSES TECHKNOW ToAdmin].each do |file|
system "nkf", "-w", "--overwrite", file
prefix.install "#{file}.eng" => file
prefix.install file => "#{file}.ja"
end
pkgshare.install "_fdrc" => "fd2rc.dist"
end
def caveats; <<~EOS
To install the initial config file:
install -c -m 0644 #{opt_pkgshare}/fd2rc.dist ~/.fd2rc
To set application messages to Japanese, edit your .fd2rc:
MESSAGELANG="ja"
EOS
end
end
| bsd-2-clause |
maxim-belkin/homebrew-core | Formula/acpica.rb | 1231 | class Acpica < Formula
desc "OS-independent implementation of the ACPI specification"
homepage "https://www.acpica.org/"
url "https://acpica.org/sites/acpica/files/acpica-unix-20200717.tar.gz"
sha256 "cb99903ef240732f395af40c23b9b19c7899033f48840743544eebb6da72a828"
license any_of: ["Intel-ACPI", "GPL-2.0-only", "BSD-3-Clause"]
head "https://github.com/acpica/acpica.git"
livecheck do
url "https://acpica.org/downloads"
regex(/current release of ACPICA is version <strong>v?(\d{6,8}) </i)
end
bottle do
cellar :any_skip_relocation
sha256 "e32d0376e072bbe080c114842b0a19b300ad8bd844a046fdd4eeb3894363672f" => :catalina
sha256 "4c61d40a957465fd9d3a90caff51051458beeccf5bac1371c3d1974d0dfeddeb" => :mojave
sha256 "3a1b395d0c4085f054626a808d059317d23614eec01fb011981a9f546366e438" => :high_sierra
sha256 "bac4acbdf59883f7921ebe2467822bfc9228e635735e2c46e07c02ea726f9d5d" => :x86_64_linux
end
uses_from_macos "bison" => :build
uses_from_macos "flex" => :build
uses_from_macos "m4" => :build
def install
ENV.deparallelize
system "make", "PREFIX=#{prefix}"
system "make", "install", "PREFIX=#{prefix}"
end
test do
system "#{bin}/acpihelp", "-u"
end
end
| bsd-2-clause |
cmptrgeekken/evething | templates/pgsus/seedlist.html | 1469 | {% extends "web_template.html" %}
{% import 'macros/common.html' as common %}
{% block title %}Seeding{% endblock %}
{% block content %}
<section class="bg-19 bg-center bg-cover">
<div>
<div class="container section-sm">
<h1 class="top-title">Seeding</h1>
</div>
</div>
</section>
<section class="container section-md">
<div class="row">
<div class="col-lg-12">
<h3>Your lists:</h3>
{% if has_lists %}
<ul>
{% for list in seed_lists %}
<li>{{ list.name }} <i>({% if list.is_private %}Private{% else %}Public{% endif %})</i> <a href="{{url('pgsus.views.seededit')}}?id={{list.id}}">Edit</a> | <a href="{{url('pgsus.views.seedview')}}?id={{list.id}}">View</a></li>
{% endfor %}
</ul>
{% else %}
<i>You haven't defined any seeding lists!</i>
{% endif %}
<div>
<a href="{{ url('pgsus.views.seededit') }}">Add List!</a>
</div>
<h3>Public Lists:</h3>
{% if public_lists|length > 0 %}
<ul>
{% for list in public_lists %}
<li><a href="{{url('pgsus.views.seedview')}}?id={{list.id}}">{{ list.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<i>None currently shared!</i>
{% endif %}
</div>
</div>
</section>
{% endblock %}
| bsd-2-clause |
wartur/yii-sorter | widgets/SorterDropDownColumn.php | 6834 | <?php
/**
* SorterDropDownColumn class file.
*
* @author Krivtsov Artur (wartur) <[email protected]> | Made in Russia
* @copyright Krivtsov Artur © 2014
* @link https://github.com/wartur/yii-sorter-behavior
* @license New BSD license
*/
Yii::import('zii.widgets.grid.CGridColumn', true);
Yii::import('sorter.components.SorterAbstractMoveAction');
/**
* Dropdown column for simple work with SorterActiveRecordBehavior
*
* @author Krivtsov Artur (wartur) <[email protected]> | Made in Russia
* @since v1.0.0
*/
class SorterDropDownColumn extends CGridColumn {
const ALGO_MOVE_TO_MODEL = 'sorterMoveToModel';
const ALGO_MOVE_TO_POSITION = 'sorterMoveToPosition';
/**
* @var integer алгоритм работы
*/
public $algo = self::ALGO_MOVE_TO_POSITION;
/**
* @var integer
*/
public $direction = 'up';
/**
* @var array
* Default: array((0), 1, 2, 3, 4, 5, 6, 7, 8, 9);
*/
public $sortValues = null;
/**
* @var string
*/
public $cssDropdownClassPart = null;
/**
* @var type
*/
public $emptyText = null;
/**
* @var string
*/
public $onErrorMoveJsExpression = null;
/**
*
* @var type
*/
public $packToLink = true;
/**
* @var type
*/
protected $renderClass = null;
/**
* @var type
*/
protected $topDivRenderId = null;
/**
* @var type
*/
protected $dropDownRenderId = null;
public function init() {
if ($this->sortValues === null) {
if ($this->algo == self::ALGO_MOVE_TO_MODEL) {
throw new CException(Yii::t('SorterDropDownColumn', 'sortValues is reqired if select algo == ({algo})', array('{algo}' => self::ALGO_MOVE_TO_MODEL)));
} else {
if ($this->direction == SorterAbstractMoveAction::DIRECTION_UP) {
$combine = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
} else {
$combine = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
}
$this->sortValues = array_combine($combine, $combine);
}
}
// only head for optimize css
$this->headerHtmlOptions = CMap::mergeArray(array('style' => 'width: 160px;'), $this->headerHtmlOptions);
if (empty($this->cssDropdownClassPart)) {
$this->cssDropdownClassPart = 'moveDropdown';
}
// set csrf
if (Yii::app()->request->enableCsrfValidation) {
$csrfTokenName = Yii::app()->request->csrfTokenName;
$csrfToken = Yii::app()->request->csrfToken;
$csrf = ", '$csrfTokenName':'$csrfToken'";
} else {
$csrf = '';
}
$paramConst = SorterAbstractMoveAction::PARAM;
$dataParams = "\n\t\tdata:{ '{$paramConst}': $(this).val() {$csrf} },";
$onErrorMoveMessage = isset($this->onErrorMoveMessage) ? $this->onErrorMoveMessage : Yii::t('SorterButtonColumn', 'Move error');
$jsOnChange = <<<EOD
function() {
jQuery('#{$this->grid->id}').yiiGridView('update', {
type: 'POST',
url: $(this).data('url'),$dataParams
success: function(data) {
jQuery('#{$this->grid->id}').yiiGridView('update');
return false;
},
error: function(XHR) {
return '{$onErrorMoveMessage}';
}
});
$(this).attr('disabled', 'disabled');
return false;
}
EOD;
$class = preg_replace('/\s+/', '.', $this->cssDropdownClassPart);
$this->renderClass = "{$class}_{$this->id}";
$this->dropDownRenderId = "dropDown_{$this->id}";
$resultJs = "jQuery(document).on('change','#{$this->grid->id} select.{$this->renderClass}',$jsOnChange);";
if ($this->packToLink) {
$resultJs .= "\n";
$this->topDivRenderId = "topDiv_{$class}_{$this->id}";
$resultJs .= <<<EOD
jQuery(document).on('mousedown','#{$this->grid->id} a.{$this->renderClass}',function() {
_select = $($('#{$this->topDivRenderId}').html()).attr('data-url', $(this).attr("href"));
$(this).after(_select);
$(this).hide();
_select.simulate('mousedown');
return false;
});\n
EOD;
$resultJs .= <<<EOD
jQuery(document).on('focusout','#{$this->grid->id} select.{$this->renderClass}',function(){
$(this).parent().find('a.{$this->renderClass}').show();
$(this).remove();
return false;
});
EOD;
// зарегистриуем либу для поддержки автовыпадения селекта
$am = Yii::app()->assetManager; /* @var $am CAssetManager */
$cs = Yii::app()->clientScript; /* @var $cs CClientScript */
$path = $am->publish(Yii::getPathOfAlias('sorter.assets') . "/jquery.simulate.js");
$cs->registerScriptFile($path);
}
// инициализировать выпадающий список
Yii::app()->getClientScript()->registerScript(__CLASS__ . '#' . $this->id, $resultJs);
}
protected function renderHeaderCellContent() {
parent::renderHeaderCellContent();
if($this->packToLink) {
// расположим динамические данные в хедар
$dropDownHtml = CHtml::dropDownList($this->dropDownRenderId, null, $this->sortValues, array(
'class' => $this->renderClass,
'empty' => $this->getRealEmptyText(),
));
echo CHtml::tag('div', array('style' => 'display: none;', 'id' => $this->topDivRenderId), $dropDownHtml);
}
}
protected function renderDataCellContent($row, $data) {
if ($this->packToLink) {
// тут вывести линк с доп данными которые далее будут резолвиться в селект
echo CHtml::link($this->getRealEmptyText(), Yii::app()->controller->createUrl($this->algo, array('id' => $data->getPrimaryKey(), 'd' => $this->direction)), array(
'class' => $this->renderClass
));
} else {
echo CHtml::dropDownList("{$this->dropDownRenderId}_{$row}", null, $this->sortValues, array(
'class' => $this->renderClass,
'empty' => $this->getRealEmptyText(),
'data-url' => Yii::app()->controller->createUrl($this->algo, array('id' => $data->getPrimaryKey(), 'd' => $this->direction))
));
}
}
public function getRealEmptyText() {
$result = null;
if ($this->algo == self::ALGO_MOVE_TO_MODEL) {
if ($this->direction == 'up') {
$result = isset($this->emptyText) ? $this->emptyText : Yii::t('SorterDropDownColumn', '(move before model)');
} else {
$result = isset($this->emptyText) ? $this->emptyText : Yii::t('SorterDropDownColumn', '(move after model)');
}
} else if ($this->algo == self::ALGO_MOVE_TO_POSITION) {
if ($this->direction == 'up') {
$result = isset($this->emptyText) ? $this->emptyText : Yii::t('SorterDropDownColumn', '(move before position)');
} else {
$result = isset($this->emptyText) ? $this->emptyText : Yii::t('SorterDropDownColumn', '(move after position)');
}
} else {
throw new CException(Yii::t('SorterDropDownColumn', 'Unexpected algo == ({algo})', array('{algo}' => $this->algo)));
}
return $result;
}
}
| bsd-2-clause |
Devronium/ConceptApplicationServer | core/server/Samples/CIDE/Help/standard.net.sip.osip_authorization_set_nonce_count.html | 2680 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>standard.net.sip.osip_authorization_set_nonce_count</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
</head>
<body bgcolor="#ffffff">
<table border="0" width="100%" bgcolor="#F0F0FF">
<tr>
<td>Concept Framework 2.2 documentation</td>
<td align="right"><a href="index.html">Contents</a> | <a href="index_fun.html">Index</a></td>
</tr>
</table>
<h2><a href="standard.net.sip.html">standard.net.sip</a>.osip_authorization_set_nonce_count</h2>
<table border="0" cellspacing="0" cellpadding="0" width="500" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr bgcolor="#f0f0f0">
<td><i>Name</i></td>
<td><i>Version</i></td>
<td><i>Deprecated</i></td>
</tr>
<tr bgcolor="#fafafa">
<td><b>osip_authorization_set_nonce_count</b></td>
<td>version 2</td>
<td>no</td>
</tr>
</table>
<br />
<b>Prototype:</b><br />
<table bgcolor="#F0F0F0" width="100%" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"><tr><td><b>number osip_authorization_set_nonce_count(handler oParam1, string szParam2);</b></td></tr></table>
<br />
<b>Parameters:</b><br />
<table bgcolor="#FFFFFF" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr>
<td>
<i>oParam1</i>
</td>
<td>
handler
</td>
</tr>
<tr>
<td>
<i>szParam2</i>
</td>
<td>
string
</td>
</tr>
</table>
<br />
<b>Description:</b><br />
<table width="100%" bgcolor="#FAFAFF" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr><td>
TODO: Document this
</td></tr>
</table>
<br />
<b>Returns:</b><br />
Return number
<br />
<br />
<!--
<p>
<a href="http://validator.w3.org/check?uri=referer"><img
src="http://www.w3.org/Icons/valid-html40"
alt="Valid HTML 4.0 Transitional" height="31" width="88" border="0"></a>
<a href="http://jigsaw.w3.org/css-validator/">
<img style="border:0;width:88px;height:31px"
src="http://jigsaw.w3.org/css-validator/images/vcss"
alt="Valid CSS!" border="0"/>
</a>
</p>
-->
<table bgcolor="#F0F0F0" width="100%"><tr><td>Documented by Devronium Autodocumenter Alpha, generation time: Sun Jan 27 18:15:38 2013
GMT</td><td align="right">(c)2013 <a href="http://www.devronium.com">Devronium Applications</a></td></tr></table>
</body>
</html> | bsd-2-clause |
zhangjunfang/eclipse-dir | spark/examples/src/main/scala/org/apache/spark/streaming/examples/NetworkWordCount.scala | 2561 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.streaming.examples
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.StreamingContext._
import org.apache.spark.storage.StorageLevel
// scalastyle:off
/**
* Counts words in text encoded with UTF8 received from the network every second.
*
* Usage: NetworkWordCount <master> <hostname> <port>
* <master> is the Spark master URL. In local mode, <master> should be 'local[n]' with n > 1.
* <hostname> and <port> describe the TCP server that Spark Streaming would connect to receive data.
*
* To run this on your local machine, you need to first run a Netcat server
* `$ nc -lk 9999`
* and then run the example
* `$ ./bin/run-example org.apache.spark.streaming.examples.NetworkWordCount local[2] localhost 9999`
*/
// scalastyle:on
object NetworkWordCount {
def main(args: Array[String]) {
if (args.length < 3) {
System.err.println("Usage: NetworkWordCount <master> <hostname> <port>\n" +
"In local mode, <master> should be 'local[n]' with n > 1")
System.exit(1)
}
StreamingExamples.setStreamingLogLevels()
// Create the context with a 1 second batch size
val ssc = new StreamingContext(args(0), "NetworkWordCount", Seconds(1),
System.getenv("SPARK_HOME"), StreamingContext.jarOfClass(this.getClass).toSeq)
// Create a NetworkInputDStream on target ip:port and count the
// words in input stream of \n delimited text (eg. generated by 'nc')
val lines = ssc.socketTextStream(args(1), args(2).toInt, StorageLevel.MEMORY_ONLY_SER)
val words = lines.flatMap(_.split(" "))
val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)
wordCounts.print()
ssc.start()
ssc.awaitTermination()
}
}
| bsd-2-clause |
sergeScherbakov/bgfx | src/config.h | 9109 | /*
* Copyright 2011-2015 Branimir Karadzic. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
#ifndef BGFX_CONFIG_H_HEADER_GUARD
#define BGFX_CONFIG_H_HEADER_GUARD
#include <bx/config.h>
#ifndef BGFX_CONFIG_DEBUG
# define BGFX_CONFIG_DEBUG 0
#endif // BGFX_CONFIG_DEBUG
#if !defined(BGFX_CONFIG_RENDERER_DIRECT3D9) \
&& !defined(BGFX_CONFIG_RENDERER_DIRECT3D11) \
&& !defined(BGFX_CONFIG_RENDERER_DIRECT3D12) \
&& !defined(BGFX_CONFIG_RENDERER_METAL) \
&& !defined(BGFX_CONFIG_RENDERER_OPENGL) \
&& !defined(BGFX_CONFIG_RENDERER_OPENGLES) \
&& !defined(BGFX_CONFIG_RENDERER_VULKAN) \
&& !defined(BGFX_CONFIG_RENDERER_NULL)
# ifndef BGFX_CONFIG_RENDERER_DIRECT3D9
# define BGFX_CONFIG_RENDERER_DIRECT3D9 (0 \
|| BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_XBOX360 \
? 1 : 0)
# endif // BGFX_CONFIG_RENDERER_DIRECT3D9
# ifndef BGFX_CONFIG_RENDERER_DIRECT3D11
# define BGFX_CONFIG_RENDERER_DIRECT3D11 (0 \
|| BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_WINRT \
? 1 : 0)
# endif // BGFX_CONFIG_RENDERER_DIRECT3D11
# ifndef BGFX_CONFIG_RENDERER_DIRECT3D12
# define BGFX_CONFIG_RENDERER_DIRECT3D12 (0 \
|| BX_PLATFORM_WINDOWS \
? 1 : 0)
# endif // BGFX_CONFIG_RENDERER_DIRECT3D12
//TODO: should check if iOS8 or greater
# ifndef BGFX_CONFIG_RENDERER_METAL
# define BGFX_CONFIG_RENDERER_METAL (0 \
|| BX_PLATFORM_IOS \
? 1 : 0)
# endif // BGFX_CONFIG_RENDERER_METAL
# ifndef BGFX_CONFIG_RENDERER_OPENGL
# define BGFX_CONFIG_RENDERER_OPENGL (0 \
|| BX_PLATFORM_FREEBSD \
|| BX_PLATFORM_LINUX \
|| BX_PLATFORM_OSX \
|| BX_PLATFORM_WINDOWS \
? 1 : 0)
# endif // BGFX_CONFIG_RENDERER_OPENGL
# ifndef BGFX_CONFIG_RENDERER_OPENGLES
# define BGFX_CONFIG_RENDERER_OPENGLES (0 \
|| BX_PLATFORM_ANDROID \
|| BX_PLATFORM_EMSCRIPTEN \
|| BX_PLATFORM_IOS \
|| BX_PLATFORM_NACL \
|| BX_PLATFORM_QNX \
|| BX_PLATFORM_RPI \
? 1 : 0)
# endif // BGFX_CONFIG_RENDERER_OPENGLES
# ifndef BGFX_CONFIG_RENDERER_VULKAN
# define BGFX_CONFIG_RENDERER_VULKAN 0
# endif // BGFX_CONFIG_RENDERER_VULKAN
# ifndef BGFX_CONFIG_RENDERER_NULL
# define BGFX_CONFIG_RENDERER_NULL (!(0 \
|| BGFX_CONFIG_RENDERER_DIRECT3D9 \
|| BGFX_CONFIG_RENDERER_DIRECT3D11 \
|| BGFX_CONFIG_RENDERER_DIRECT3D12 \
|| BGFX_CONFIG_RENDERER_OPENGL \
|| BGFX_CONFIG_RENDERER_OPENGLES \
? 1 : 0) )
# endif // BGFX_CONFIG_RENDERER_NULL
#else
# ifndef BGFX_CONFIG_RENDERER_DIRECT3D9
# define BGFX_CONFIG_RENDERER_DIRECT3D9 0
# endif // BGFX_CONFIG_RENDERER_DIRECT3D9
# ifndef BGFX_CONFIG_RENDERER_DIRECT3D11
# define BGFX_CONFIG_RENDERER_DIRECT3D11 0
# endif // BGFX_CONFIG_RENDERER_DIRECT3D11
# ifndef BGFX_CONFIG_RENDERER_DIRECT3D12
# define BGFX_CONFIG_RENDERER_DIRECT3D12 0
# endif // BGFX_CONFIG_RENDERER_DIRECT3D12
# ifndef BGFX_CONFIG_RENDERER_METAL
# define BGFX_CONFIG_RENDERER_METAL 0
# endif // BGFX_CONFIG_RENDERER_METAL
# ifndef BGFX_CONFIG_RENDERER_OPENGL
# define BGFX_CONFIG_RENDERER_OPENGL 0
# endif // BGFX_CONFIG_RENDERER_OPENGL
# ifndef BGFX_CONFIG_RENDERER_OPENGLES
# define BGFX_CONFIG_RENDERER_OPENGLES 0
# endif // BGFX_CONFIG_RENDERER_OPENGLES
# ifndef BGFX_CONFIG_RENDERER_VULKAN
# define BGFX_CONFIG_RENDERER_VULKAN 0
# endif // BGFX_CONFIG_RENDERER_VULKAN
# ifndef BGFX_CONFIG_RENDERER_NULL
# define BGFX_CONFIG_RENDERER_NULL 0
# endif // BGFX_CONFIG_RENDERER_NULL
#endif // !defined...
#if BGFX_CONFIG_RENDERER_OPENGL && BGFX_CONFIG_RENDERER_OPENGL < 21
# undef BGFX_CONFIG_RENDERER_OPENGL
# define BGFX_CONFIG_RENDERER_OPENGL 21
#endif // BGFX_CONFIG_RENDERER_OPENGL && BGFX_CONFIG_RENDERER_OPENGL < 21
#if BGFX_CONFIG_RENDERER_OPENGLES && BGFX_CONFIG_RENDERER_OPENGLES < 20
# undef BGFX_CONFIG_RENDERER_OPENGLES
# define BGFX_CONFIG_RENDERER_OPENGLES 20
#endif // BGFX_CONFIG_RENDERER_OPENGLES && BGFX_CONFIG_RENDERER_OPENGLES < 20
#if BGFX_CONFIG_RENDERER_OPENGL && BGFX_CONFIG_RENDERER_OPENGLES
# error "Can't define both BGFX_CONFIG_RENDERER_OPENGL and BGFX_CONFIG_RENDERER_OPENGLES"
#endif // BGFX_CONFIG_RENDERER_OPENGL && BGFX_CONFIG_RENDERER_OPENGLES
/// Enable use of extensions.
#ifndef BGFX_CONFIG_RENDERER_USE_EXTENSIONS
# define BGFX_CONFIG_RENDERER_USE_EXTENSIONS 1
#endif // BGFX_CONFIG_RENDERER_USE_EXTENSIONS
/// Enable use of tinystl.
#ifndef BGFX_CONFIG_USE_TINYSTL
# define BGFX_CONFIG_USE_TINYSTL 1
#endif // BGFX_CONFIG_USE_TINYSTL
/// Enable OculusVR integration.
#ifndef BGFX_CONFIG_USE_OVR
# define BGFX_CONFIG_USE_OVR 0
#endif // BGFX_CONFIG_USE_OVR
/// Enable nVidia PerfHUD integration.
#ifndef BGFX_CONFIG_DEBUG_PERFHUD
# define BGFX_CONFIG_DEBUG_PERFHUD 0
#endif // BGFX_CONFIG_DEBUG_NVPERFHUD
/// Enable PIX markers.
#ifndef BGFX_CONFIG_DEBUG_PIX
# define BGFX_CONFIG_DEBUG_PIX BGFX_CONFIG_DEBUG
#endif // BGFX_CONFIG_DEBUG_PIX
/// Enable DX11 object names.
#ifndef BGFX_CONFIG_DEBUG_OBJECT_NAME
# define BGFX_CONFIG_DEBUG_OBJECT_NAME BGFX_CONFIG_DEBUG
#endif // BGFX_CONFIG_DEBUG_OBJECT_NAME
/// Enable Metal markers.
#ifndef BGFX_CONFIG_DEBUG_MTL
# define BGFX_CONFIG_DEBUG_MTL BGFX_CONFIG_DEBUG
#endif // BGFX_CONFIG_DEBUG_MTL
#ifndef BGFX_CONFIG_MULTITHREADED
# define BGFX_CONFIG_MULTITHREADED ( (!BGFX_CONFIG_RENDERER_NULL)&&(0 \
|| BX_PLATFORM_ANDROID \
|| BX_PLATFORM_FREEBSD \
|| BX_PLATFORM_LINUX \
|| BX_PLATFORM_IOS \
|| BX_PLATFORM_NACL \
|| BX_PLATFORM_OSX \
|| BX_PLATFORM_QNX \
|| BX_PLATFORM_RPI \
|| BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_WINRT \
|| BX_PLATFORM_XBOX360 \
? 1 : 0) )
#endif // BGFX_CONFIG_MULTITHREADED
#ifndef BGFX_CONFIG_MAX_DRAW_CALLS
# define BGFX_CONFIG_MAX_DRAW_CALLS ( (64<<10)-1)
#endif // BGFX_CONFIG_MAX_DRAW_CALLS
#ifndef BGFX_CONFIG_MAX_MATRIX_CACHE
# define BGFX_CONFIG_MAX_MATRIX_CACHE (BGFX_CONFIG_MAX_DRAW_CALLS+1)
#endif // BGFX_CONFIG_MAX_MATRIX_CACHE
#ifndef BGFX_CONFIG_MAX_RECT_CACHE
# define BGFX_CONFIG_MAX_RECT_CACHE (4<<10)
#endif // BGFX_CONFIG_MAX_RECT_CACHE
#ifndef BGFX_CONFIG_MAX_VIEWS
// Do not change. Must be power of 2.
# define BGFX_CONFIG_MAX_VIEWS 256
#endif // BGFX_CONFIG_MAX_VIEWS
#define BGFX_CONFIG_MAX_VIEW_NAME_RESERVED 6
#ifndef BGFX_CONFIG_MAX_VIEW_NAME
# define BGFX_CONFIG_MAX_VIEW_NAME 256
#endif // BGFX_CONFIG_MAX_VIEW_NAME
#ifndef BGFX_CONFIG_MAX_VERTEX_DECLS
# define BGFX_CONFIG_MAX_VERTEX_DECLS 64
#endif // BGFX_CONFIG_MAX_VERTEX_DECLS
#ifndef BGFX_CONFIG_MAX_INDEX_BUFFERS
# define BGFX_CONFIG_MAX_INDEX_BUFFERS (4<<10)
#endif // BGFX_CONFIG_MAX_INDEX_BUFFERS
#ifndef BGFX_CONFIG_MAX_VERTEX_BUFFERS
# define BGFX_CONFIG_MAX_VERTEX_BUFFERS (4<<10)
#endif // BGFX_CONFIG_MAX_VERTEX_BUFFERS
#ifndef BGFX_CONFIG_MAX_DYNAMIC_INDEX_BUFFERS
# define BGFX_CONFIG_MAX_DYNAMIC_INDEX_BUFFERS (4<<10)
#endif // BGFX_CONFIG_MAX_DYNAMIC_INDEX_BUFFERS
#ifndef BGFX_CONFIG_MAX_DYNAMIC_VERTEX_BUFFERS
# define BGFX_CONFIG_MAX_DYNAMIC_VERTEX_BUFFERS (4<<10)
#endif // BGFX_CONFIG_MAX_DYNAMIC_VERTEX_BUFFERS
#ifndef BGFX_CONFIG_DYNAMIC_INDEX_BUFFER_SIZE
# define BGFX_CONFIG_DYNAMIC_INDEX_BUFFER_SIZE (1<<20)
#endif // BGFX_CONFIG_DYNAMIC_INDEX_BUFFER_SIZE
#ifndef BGFX_CONFIG_DYNAMIC_VERTEX_BUFFER_SIZE
# define BGFX_CONFIG_DYNAMIC_VERTEX_BUFFER_SIZE (3<<20)
#endif // BGFX_CONFIG_DYNAMIC_VERTEX_BUFFER_SIZE
#ifndef BGFX_CONFIG_MAX_SHADERS
# define BGFX_CONFIG_MAX_SHADERS 512
#endif // BGFX_CONFIG_MAX_FRAGMENT_SHADERS
#ifndef BGFX_CONFIG_MAX_PROGRAMS
// Must be power of 2.
# define BGFX_CONFIG_MAX_PROGRAMS 512
#endif // BGFX_CONFIG_MAX_PROGRAMS
#ifndef BGFX_CONFIG_MAX_TEXTURES
# define BGFX_CONFIG_MAX_TEXTURES (4<<10)
#endif // BGFX_CONFIG_MAX_TEXTURES
#ifndef BGFX_CONFIG_MAX_TEXTURE_SAMPLERS
# define BGFX_CONFIG_MAX_TEXTURE_SAMPLERS 16
#endif // BGFX_CONFIG_MAX_TEXTURE_SAMPLERS
#ifndef BGFX_CONFIG_MAX_FRAME_BUFFERS
# define BGFX_CONFIG_MAX_FRAME_BUFFERS 64
#endif // BGFX_CONFIG_MAX_FRAME_BUFFERS
#ifndef BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS
# define BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS 8
#endif // BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS
#ifndef BGFX_CONFIG_MAX_UNIFORMS
# define BGFX_CONFIG_MAX_UNIFORMS 512
#endif // BGFX_CONFIG_MAX_CONSTANTS
#ifndef BGFX_CONFIG_MAX_COMMAND_BUFFER_SIZE
# define BGFX_CONFIG_MAX_COMMAND_BUFFER_SIZE (64<<10)
#endif // BGFX_CONFIG_MAX_COMMAND_BUFFER_SIZE
#ifndef BGFX_CONFIG_TRANSIENT_VERTEX_BUFFER_SIZE
# define BGFX_CONFIG_TRANSIENT_VERTEX_BUFFER_SIZE (6<<20)
#endif // BGFX_CONFIG_TRANSIENT_VERTEX_BUFFER_SIZE
#ifndef BGFX_CONFIG_TRANSIENT_INDEX_BUFFER_SIZE
# define BGFX_CONFIG_TRANSIENT_INDEX_BUFFER_SIZE (2<<20)
#endif // BGFX_CONFIG_TRANSIENT_INDEX_BUFFER_SIZE
#ifndef BGFX_CONFIG_MAX_CONSTANT_BUFFER_SIZE
# define BGFX_CONFIG_MAX_CONSTANT_BUFFER_SIZE (512<<10)
#endif // BGFX_CONFIG_MAX_CONSTANT_BUFFER_SIZE
#ifndef BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT
# define BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT 5
#endif // BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT
#ifndef BGFX_CONFIG_MAX_CLEAR_COLOR_PALETTE
# define BGFX_CONFIG_MAX_CLEAR_COLOR_PALETTE 16
#endif // BGFX_CONFIG_MAX_CLEAR_COLOR_PALETTE
#define BGFX_CONFIG_DRAW_INDIRECT_STRIDE 32
#endif // BGFX_CONFIG_H_HEADER_GUARD
| bsd-2-clause |
NorwegianRockCat/pc-networkmanager | src/wificonfig/i18n/wificonfig_et.ts | 14175 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
<name>dialogWPAPersonal</name>
<message>
<source>WPA Personal Config</source>
<translation>WPA-Personal seadistus</translation>
</message>
<message>
<source>&Close</source>
<translation>&Sulge</translation>
</message>
<message>
<source>Alt+C</source>
<translation>Alt+S</translation>
</message>
<message>
<source>Network Key</source>
<translation>Võrgu võti</translation>
</message>
<message>
<source>Network Key (Repeat)</source>
<translation>Võrgu võti (korrata)</translation>
</message>
<message>
<source>Show Key</source>
<translation>Näita võtit</translation>
</message>
<message>
<source>WPA Personal Configuration</source>
<translation>WPA-Personal seadistus</translation>
</message>
</context>
<context>
<name>wepConfig</name>
<message>
<source>WEP Configuration</source>
<translation>WEP konfiguratsioon</translation>
</message>
<message>
<source>Network Key</source>
<translation>Võrgu võti</translation>
</message>
<message>
<source>Network Key (Repeat)</source>
<translation>Võrgu võti (korrata)</translation>
</message>
<message>
<source>Key Index</source>
<translation>Võtme indeks</translation>
</message>
<message>
<source>&Close</source>
<translation>&Sulge</translation>
</message>
<message>
<source>Alt+C</source>
<translation>Alt+S</translation>
</message>
<message>
<source>Hex Key</source>
<translation>Heksadetsimaalarv</translation>
</message>
<message>
<source>Plaintext</source>
<translation>Lihttekst</translation>
</message>
<message>
<source>Show Key</source>
<translation>Näita võtit</translation>
</message>
<message>
<source>Wireless Network Key</source>
<translation>Traadita võrgu võti</translation>
</message>
</context>
<context>
<name>wificonfigwidgetbase</name>
<message>
<source>Wireless Configuration</source>
<translation>Wi-Fi seadistus</translation>
</message>
<message>
<source>&General</source>
<translation>Ü&ldine</translation>
</message>
<message>
<source>O&btain IP automatically (DHCP)</source>
<translation>Seadista &IP-aadress automaatselt (DHCP)</translation>
</message>
<message>
<source>Alt+B</source>
<translation>Alt+I</translation>
</message>
<message>
<source>Alt+S</source>
<translation>Alt+V</translation>
</message>
<message>
<source>Assign static IP address</source>
<translation>Seadista püsiv IP-aadress</translation>
</message>
<message>
<source>IP:</source>
<translation>IP:</translation>
</message>
<message>
<source>Netmask:</source>
<translation>Võrgumask:</translation>
</message>
<message>
<source>999\.999\.999\.999; </source>
<translation>999\.999\.999\.999;</translation>
</message>
<message>
<source>Advanced</source>
<translation>Täpsemad valikud</translation>
</message>
<message>
<source>Use hardware defau&lt MAC address</source>
<translation>Kasuta võrgukaardi &vaikimisi MAC-aadressi</translation>
</message>
<message>
<source>Alt+L</source>
<translation>Alt+V</translation>
</message>
<message>
<source>Custom MAC address</source>
<translation>Kohandatud MAC-aadress</translation>
</message>
<message>
<source>Info</source>
<translation>Info</translation>
</message>
<message>
<source>Configuration info</source>
<translation>Seadistuse info</translation>
</message>
<message>
<source>Mac/Ether:</source>
<translation>MAC-aadress:</translation>
</message>
<message>
<source>Gateway:</source>
<translation>Lüüs:</translation>
</message>
<message>
<source>IPv6:</source>
<translation>IPv6:</translation>
</message>
<message>
<source>Status:</source>
<translation>Olek:</translation>
</message>
<message>
<source>Media:</source>
<translation>Meedia:</translation>
</message>
<message>
<source>Traffic info</source>
<translation>Võrguliiklus</translation>
</message>
<message>
<source>Packets:</source>
<translation>Pakette:</translation>
</message>
<message>
<source>Errors:</source>
<translation>Vigu:</translation>
</message>
<message>
<source>In:</source>
<translation>Sisse:</translation>
</message>
<message>
<source>Out:</source>
<translation>Välja:</translation>
</message>
<message>
<source>Close</source>
<translation>Sulge</translation>
</message>
<message>
<source>Disable this wireless device</source>
<translation>Lülitada see traadita seade välja</translation>
</message>
<message>
<source>&Apply</source>
<translation>&Rakenda</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+R</translation>
</message>
<message>
<source>&OK</source>
<translation>&Olgu</translation>
</message>
<message>
<source>Alt+O</source>
<translation>Alt+O</translation>
</message>
<message>
<source>Missing Fields</source>
<translation>Puuduvad väljad</translation>
</message>
<message>
<source>You must enter an IP and Netmask to continue!
</source>
<translation>Jätkamiseks on vajalikud on IP-aadress ja võrgumask!
</translation>
</message>
<message>
<source>Warning</source>
<translation>Hoiatus</translation>
</message>
<message>
<source>IP Address is out of range! (</source>
<translation>IP-aadress ei ole lubatud piirides! (</translation>
</message>
<message>
<source>) Fields must be between 0-255.</source>
<translation>) Väljad peavad olema vahemikus 0–255.</translation>
</message>
<message>
<source>Netmask is out of range! (</source>
<translation>Võrgumask ei ole lubatud piirides! (</translation>
</message>
<message>
<source>Remove</source>
<translation>Eemalda</translation>
</message>
<message>
<source>Error</source>
<translation>Viga</translation>
</message>
<message>
<source>You already have a wireless network with this SSID! Please remove it first.
</source>
<translation>Sellise SSID-ga traadita võrk on juba olemas! Palun eemalda see kõigepealt.
</translation>
</message>
<message>
<source>Edit</source>
<translation>Muuda</translation>
</message>
<message>
<source>Unknown Wireless Device</source>
<translation>Tundmatu traadita seade</translation>
</message>
<message>
<source>(Higher connections are given priority)</source>
<translation>(Kõrgematele ühendustele antakse suurem prioriteet)</translation>
</message>
<message>
<source>Available Wireless Networks</source>
<translation>Saadaval traadita võrgud</translation>
</message>
<message>
<source>Scan</source>
<translation>Skaneeri</translation>
</message>
<message>
<source>Add Selected</source>
<translation>Lisa valitud</translation>
</message>
<message>
<source>Add Hidden</source>
<translation>Lisa peidetud võrk</translation>
</message>
<message>
<source>Network Name</source>
<translation>Võrgu nimi</translation>
</message>
<message>
<source>Please enter the name of the network you wish to add</source>
<translation>Palun sisesta võrgu nimi, mille soovid lisada </translation>
</message>
<message>
<source>Configured Network Profiles</source>
<translation>Seadistatud võrguprofiilid</translation>
</message>
<message>
<source>Add &network</source>
<translation>&Lisa võrk</translation>
</message>
<message>
<source>WPA Configuration</source>
<translation>WPA seadistus</translation>
</message>
<message>
<source>Set Country Code</source>
<translation>Määra maakood</translation>
</message>
</context>
<context>
<name>wifiscanssid</name>
<message>
<source>Scan for Wireless networks</source>
<translation>Otsi traadita võrke</translation>
</message>
<message>
<source>Available wireless networks</source>
<translation>Kättesaadavad WiFi võrgud</translation>
</message>
<message>
<source>&Rescan</source>
<translation>Skanee&ri uuesti</translation>
</message>
<message>
<source>Alt+R</source>
<translation>Alt+R</translation>
</message>
<message>
<source>Select</source>
<translation>Vali</translation>
</message>
<message>
<source>Alt+C</source>
<translation>Alt+C</translation>
</message>
<message>
<source>Cancel</source>
<translation>Katkesta</translation>
</message>
<message>
<source>Scanning for wireless networks...</source>
<translation>Wi-Fi võrkude skaneerimine...</translation>
</message>
<message>
<source>Select a wireless network to connect.</source>
<translation>Vali traadita võrk, millega soovid ühenduda.</translation>
</message>
<message>
<source>No wireless networks found!</source>
<translation>Ühtegi traadita võrku ei leitud!</translation>
</message>
<message>
<source>No selection</source>
<translation>Valik puudub</translation>
</message>
<message>
<source>Error: You must select a network to connect!
</source>
<translation>Viga: valige võrk, millega liituda!</translation>
</message>
</context>
<context>
<name>wifiselectiondialog</name>
<message>
<source>Select Wireless Network</source>
<translation>Vali traadita võrk</translation>
</message>
<message>
<source>Alt+C</source>
<translation>Alt+N</translation>
</message>
<message>
<source>Cancel</source>
<translation>Katkesta</translation>
</message>
<message>
<source>Selected Wireless Network</source>
<translation>Valitud traadita võrk</translation>
</message>
<message>
<source>Scan</source>
<translation>Skaneeri</translation>
</message>
<message>
<source>Using BSSID</source>
<translation>Kasutatakse BSSID-d</translation>
</message>
<message>
<source>Disabled</source>
<translation>Keelatud</translation>
</message>
<message>
<source>WEP</source>
<translation>WEP</translation>
</message>
<message>
<source>WPA Personal</source>
<translation>WPA-Personal</translation>
</message>
<message>
<source>WPA Enterprise</source>
<translation>WPA-Enterprise</translation>
</message>
<message>
<source>Configure</source>
<translation>Seadista</translation>
</message>
<message>
<source>Add</source>
<translation>Lisa</translation>
</message>
<message>
<source>No SSID!</source>
<translation>SSID puudub!</translation>
</message>
<message>
<source>Error: You must select a wireless network to connect!
</source>
<translation>Viga: tuleb valida traadita võrk, millega ühenduda!
</translation>
</message>
<message>
<source>Invalid BSSID!</source>
<translation>Vigane BSSID!</translation>
</message>
<message>
<source>Error: The specified BSSID appears invalid. It must be in the format xx:xx:xx:xx:xx:xx
</source>
<translation>Viga: valitud BSSID paistab olevat vigane! See peab olema kujul xx:xx:xx:xx:xx:xx
</translation>
</message>
<message>
<source>Warning</source>
<translation>Hoiatus</translation>
</message>
<message>
<source>WEP is selected, but not configured!
Please configure your WEP key before saving!</source>
<translation>WEP on valitud, kuid ei ole seadistatud! Palume seadistada WEP võti enne salvestamist!</translation>
</message>
<message>
<source>WPA-Personal is selected, but not configured!
Please configure your WPA key before saving!</source>
<translation>WPA-Personal on valitud, kuid ei ole seadistatud! Palume seadistada WPA võti enne salvestamist!</translation>
</message>
<message>
<source>WPA-Enterprise is selected, but not configured!
Please configure your WPA settings before saving!</source>
<translation>WPA-Enterprise on valitud, kuid ei ole seadistatud! Palume seadistada WPA võti enne salvestamist!</translation>
</message>
<message>
<source>WEP (Configured)</source>
<translation>WEP (seadistatud)</translation>
</message>
<message>
<source>WPA Personal (Configured)</source>
<translation>WPA-Personal (seadistatud)</translation>
</message>
<message>
<source>WPA Enterprise (Configured)</source>
<translation>WPA-Enterprise (seadistatud)</translation>
</message>
<message>
<source>Save</source>
<translation>Salvesta</translation>
</message>
<message>
<source>Network Security</source>
<translation>Võrgu turvalisus</translation>
</message>
</context>
</TS>
| bsd-2-clause |
penberg/hornet | mps/protli.c | 6529 | /* protli.c: PROTECTION FOR LINUX (INTEL 386)
*
* $Id: //info.ravenbrook.com/project/mps/version/1.113/code/protli.c#1 $
* Copyright (c) 2001 Ravenbrook Limited. See end of file for license.
*
* SOURCES
*
* .source.i486: Intel486 Microprocessor Family Programmer's
* Reference Manual
*
* .source.linux.kernel: Linux kernel source files.
*/
#include "prmcix.h"
#ifndef MPS_OS_LI
#error "protli.c is Linux-specific, but MPS_OS_LI is not set"
#endif
#ifndef PROTECTION
#error "protli.c implements protection, but PROTECTION is not set"
#endif
#include <limits.h>
#include <stddef.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
SRCID(protli, "$Id: //info.ravenbrook.com/project/mps/version/1.113/code/protli.c#1 $");
/* The previously-installed signal action, as returned by */
/* sigaction(3). See ProtSetup. */
static struct sigaction sigNext;
/* sigHandle -- protection signal handler
*
* This is the signal handler installed by ProtSetup to deal with
* protection faults. It is installed on the SIGSEGV signal.
* It decodes the protection fault details from the signal context
* and passes them to ArenaAccess, which attempts to handle the
* fault and remove its cause. If the fault is handled, then
* the handler returns and execution resumes. If it isn't handled,
* then sigHandle does its best to pass the signal on to the
* previously installed signal handler (sigNext).
*
* .sigh.context: We check si_code for being a memory access
* si_addr gives the fault address. See
* .source.linux.kernel (linux/arch/i386/mm/fault.c and
* linux/arch/x86/mm/fault.c).
*
* .sigh.addr: We assume that the OS decodes the address to something
* sensible
*/
/* This is defined here to keep the sources closer to those in protsgix.c
* They can't be merged yet because protsgix doesn't pass the context to
* ArenaAccess */
#define PROT_SIGNAL SIGSEGV
static void sigHandle(int sig, siginfo_t *info, void *context) /* .sigh.args */
{
int e;
/* sigset renamed to asigset due to clash with global on Darwin. */
sigset_t asigset, oldset;
struct sigaction sa;
AVER(sig == PROT_SIGNAL);
if(info->si_code == SEGV_ACCERR) { /* .sigh.context */
AccessSet mode;
Addr base;
ucontext_t *ucontext;
MutatorFaultContextStruct mfContext;
ucontext = (ucontext_t *)context;
mfContext.ucontext = ucontext;
mfContext.info = info;
/* on linux we used to be able to tell whether this was a read or a write */
mode = AccessREAD | AccessWRITE;
/* We assume that the access is for one word at the address. */
base = (Addr)info->si_addr; /* .sigh.addr */
/* limit = AddrAdd(base, (Size)sizeof(Addr)); */
/* Offer each protection structure the opportunity to handle the */
/* exception. If it succeeds, then allow the mutator to continue. */
if(ArenaAccess(base, mode, &mfContext))
return;
}
/* The exception was not handled by any known protection structure, */
/* so throw it to the previously installed handler. That handler won't */
/* get an accurate context (the MPS would fail if it were the second in */
/* line) but it's the best we can do. */
e = sigaction(PROT_SIGNAL, &sigNext, &sa);
AVER(e == 0);
sigemptyset(&asigset);
sigaddset(&asigset, PROT_SIGNAL);
e = sigprocmask(SIG_UNBLOCK, &asigset, &oldset);
AVER(e == 0);
kill(getpid(), PROT_SIGNAL);
e = sigprocmask(SIG_SETMASK, &oldset, NULL);
AVER(e == 0);
e = sigaction(PROT_SIGNAL, &sa, NULL);
AVER(e == 0);
}
/* ProtSetup -- global protection setup
*
* Under Linux, the global setup involves installing a signal handler
* on SIGSEGV to catch and handle page faults (see sigHandle).
* The previous handler is recorded so that it can be reached from
* sigHandle if it fails to handle the fault.
*
* NOTE: There are problems with this approach:
* 1. we can't honor the sa_flags for the previous handler,
* 2. what if this thread is suspended just after calling signal(3)?
* The sigNext variable will never be initialized!
*/
void ProtSetup(void)
{
struct sigaction sa;
int result;
sa.sa_sigaction = sigHandle;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
result = sigaction(PROT_SIGNAL, &sa, &sigNext);
AVER(result == 0);
}
/* C. COPYRIGHT AND LICENSE
*
* Copyright (C) 2001-2002 Ravenbrook Limited <http://www.ravenbrook.com/>.
* All rights reserved. This is an open source license. Contact
* Ravenbrook for commercial licensing options.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Redistributions in any form must be accompanied by information on how
* to obtain complete source code for this software and any accompanying
* software that uses this software. The source code must either be
* included in the distribution or be available for no more than the cost
* of distribution plus a nominal fee, and must be freely redistributable
* under reasonable conditions. For an executable file, complete source
* code means the source code for all modules it contains. It does not
* include source code for modules or files that typically accompany the
* major components of the operating system on which the executable file
* runs.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
| bsd-2-clause |
haskell/haddock | html-test/src/DuplicateRecordFields.hs | 767 | {-# LANGUAGE Haskell2010 #-}
{-# LANGUAGE DuplicateRecordFields #-}
module DuplicateRecordFields (RawReplay(..)) where
import Prelude hiding (Int)
data Int = Int
data RawReplay = RawReplay
{ headerSize :: Int
-- ^ The byte size of the first section.
, headerCRC :: Int
-- ^ The CRC of the first section.
, header :: Int
-- ^ The first section.
, contentSize :: Int
-- ^ The byte size of the second section.
, contentCRC :: Int
-- ^ The CRC of the second section.
, content :: Int
-- ^ The second section.
, footer :: Int
-- ^ Arbitrary data after the second section. In replays generated by
-- Rocket League, this is always empty. However it is not technically
-- invalid to put something here.
} | bsd-2-clause |
WinterWind/WinterWind | src/core/amqp/connection.cpp | 9314 | /*
* Copyright (c) 2017, Loic Blot <[email protected]>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "amqp/connection.h"
#include <iostream>
#include <cstring>
#include "utils/log.h"
#include "amqp/exception.h"
#include "amqp/channel.h"
#include "amqp/envelope.h"
#include "amqp/log.h"
#include "amqp/message.h"
namespace winterwind
{
namespace amqp
{
Connection::Connection(const std::string &url, uint64_t wait_timeout) :
m_wait_timeout_ms(wait_timeout)
{
amqp_connection_info info{};
amqp_default_connection_info(&info);
if (!url.empty()) {
char url_buf[1024];
memset(url_buf, 0, sizeof(url_buf));
memcpy(url_buf, url.data(), url.size());
if (amqp_parse_url(url_buf, &info) != AMQP_STATUS_OK) {
throw amqp::exception("Unable to parse AMQP URL.");
}
}
connect(info.host, (uint16_t) info.port, info.user, info.password, info.vhost);
}
Connection::Connection(const std::string &host, uint16_t port,
const std::string &username, const std::string &password, const std::string &vhost,
int32_t frame_max, uint64_t wait_timeout) :
m_frame_max(frame_max),
m_wait_timeout_ms(wait_timeout)
{
connect(host.c_str(), port, username.c_str(), password.c_str(), vhost.c_str());
}
Connection::~Connection()
{
// Invalidate channels
for (auto &channel: m_channels) {
channel.second->invalidate();
}
amqp_connection_close(m_conn, AMQP_REPLY_SUCCESS);
if (amqp_destroy_connection(m_conn) != AMQP_STATUS_OK) {
log_error(amqp_log, "Failed to destroy AMQP connection.");
}
}
void Connection::connect(const char *host, uint16_t port,
const char *username, const char *password, const char *vhost)
{
m_conn = amqp_new_connection();
if (!m_conn) {
log_error(amqp_log, "Unable to allocate a new AMQP connection.");
throw amqp::exception("Unable to allocate a new AMQP connection.");
}
socket = amqp_tcp_socket_new(m_conn);
if (!socket) {
log_error(amqp_log, "Unable to allocate a new AMQP socket.");
throw amqp::exception("Unable to allocate a new AMQP socket.");
}
if (!open(host, port)) {
throw amqp::exception("Unable to open AMQP connection");
}
if (!login(username, password, vhost, m_frame_max)) {
throw amqp::exception("Unable to login to AMQP connection");
}
}
bool Connection::open(const char *host, uint16_t port)
{
int status = amqp_socket_open(socket, host, port);
if (status != AMQP_STATUS_OK) {
log_error(amqp_log, "Failed to open AMQP connection (code: " +
std::to_string(status) + ")");
return false;
}
return true;
}
bool Connection::login(const std::string &user, const std::string &password,
const std::string &vhost, int32_t frame_max)
{
amqp_rpc_reply_t result = amqp_login(m_conn, vhost.c_str(), 0, frame_max,
m_heartbeat_interval, AMQP_SASL_METHOD_PLAIN, user.c_str(), password.c_str());
if (result.reply_type != AMQP_RESPONSE_NORMAL) {
std::stringstream ss;
ss << "login failure (reply_type: " << result.reply_type << ").";
if (result.reply_type == AMQP_RESPONSE_SERVER_EXCEPTION) {
auto login_exception = (amqp_channel_close_t *)result.reply.decoded;
ss << " Reply ID: " << result.reply.id << ", exception was: "
<< std::string((const char *) login_exception->reply_text.bytes,
login_exception->reply_text.len) << std::endl;
}
log_error(amqp_log, ss.str());
}
return result.reply_type == AMQP_RESPONSE_NORMAL;
}
bool Connection::set_heartbeat_interval(uint32_t interval)
{
if (amqp_tune_connection(m_conn, 0, m_frame_max, interval) != AMQP_STATUS_OK) {
return false;
}
m_heartbeat_interval = interval;
return true;
}
int32_t Connection::get_channel_max()
{
return amqp_get_channel_max(m_conn);
}
std::shared_ptr<Channel> Connection::create_channel()
{
if (m_channels.size() == get_channel_max()) {
log_error(amqp_log, "Unable to open AMQP channel: max channel reached");
return nullptr;
}
// @TODO handle offsets properly
++m_next_channel_id;
std::shared_ptr<Channel> new_channel = std::make_shared<Channel>(m_next_channel_id,
shared_from_this());
m_channels[m_next_channel_id] = new_channel;
return new_channel;
}
void Connection::destroy_channel(std::shared_ptr<Channel> channel)
{
auto channel_it = m_channels.find(channel->m_id);
if (channel_it != m_channels.end()) {
m_channels.erase(channel_it);
}
channel->close();
}
std::shared_ptr<Channel> Connection::find_channel(uint16_t channel_id)
{
auto channel_it = m_channels.find(channel_id);
if (channel_it == m_channels.end()) {
return nullptr;
}
return channel_it->second;
}
bool Connection::start_consuming()
{
while (!m_stop) {
if (!consume_one()) {
return false;
}
}
return true;
}
bool Connection::consume_one()
{
amqp_frame_t frame{};
amqp_envelope_t envelope{};
amqp_rpc_reply_t ret;
amqp_maybe_release_buffers(m_conn);
if (m_wait_timeout_ms) {
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = m_wait_timeout_ms;
ret = amqp_consume_message(m_conn, &envelope, &tv, 0);
}
else {
ret = amqp_consume_message(m_conn, &envelope, nullptr, 0);
}
if (AMQP_RESPONSE_NORMAL != ret.reply_type) {
if (AMQP_RESPONSE_LIBRARY_EXCEPTION == ret.reply_type &&
AMQP_STATUS_UNEXPECTED_STATE == ret.library_error) {
if (AMQP_STATUS_OK != amqp_simple_wait_frame(m_conn, &frame)) {
log_error(amqp_log, "amqp_simple_wait_frame consuming error")
return false;
}
if (AMQP_FRAME_METHOD == frame.frame_type) {
switch (frame.payload.method.id) {
case AMQP_BASIC_ACK_METHOD:
/*
* if we've turned publisher confirms on, and we've published a message
* here is a message being confirmed
*/
// @TODO callback the ack
break;
case AMQP_BASIC_RETURN_METHOD: {
/*
* if a published message couldn't be routed and the mandatory flag was set
* this is what would be returned. The message then needs to be read.
*/
amqp_message_t raw_message{};
ret = amqp_read_message(m_conn, frame.channel, &raw_message, 0);
if (AMQP_RESPONSE_NORMAL != ret.reply_type) {
return false;
}
std::shared_ptr<Channel> channel = find_channel(frame.channel);
if (channel == nullptr) {
log_error(amqp_log, "failed to reroute unsent message to "
"channel id " + std::to_string(frame.channel))
return false;
}
// Request channel to handle unsent message
channel->on_unsent_message(std::make_shared<Message>(&raw_message));
amqp_destroy_message(&raw_message);
break;
}
case AMQP_CHANNEL_CLOSE_METHOD:
/*
* a channel.close method happens when a channel exception occurs, this
* can happen by publishing to an exchange that doesn't exist for example
*
* In this case you would need to open another channel redeclare any queues
* that were declared auto-delete, and restart any consumers that were attached
* to the previous channel
*/
return false;
case AMQP_CONNECTION_CLOSE_METHOD:
/*
* a connection.close method happens when a connection exception occurs,
* this can happen by trying to use a channel that isn't open for example.
*
* In this case the whole connection must be restarted.
*/
return false;
default:
log_error(amqp_log, "An unexpected method was received "
+ std::to_string(frame.payload.method.id));
return false;
}
}
}
} else {
std::stringstream ss;
ss << "Message received on channel " << envelope.channel << std::endl;
log_info(amqp_log, ss.str())
distribute_envelope(std::make_shared<Envelope>(&envelope), envelope.channel);
amqp_destroy_envelope(&envelope);
}
return true;
}
bool Connection::distribute_envelope(EnvelopePtr envelope, uint16_t channel_id)
{
std::shared_ptr<Channel> channel = find_channel(channel_id);
if (channel == nullptr) {
log_error(amqp_log, "failed to distribute envelope to channel id "
+ std::to_string(channel_id))
return false;
}
return channel->on_envelope_received(std::move(envelope));
}
}
}
| bsd-2-clause |
dimylik/mean | server/config/mongoose.js | 850 | var mongoose = require('mongoose');
module.exports = function (config) {
mongoose.connect(config.db);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error...'));
db.once('open', function callBack() {
console.log('multivision is opened');
});
var userSchema = mongoose.Schema({
firstName: String,
lastName: String,
username: String
});
var User = mongoose.model('User', userSchema);
User.find({}).exec(function (err, collection) {
if (collection.length === 0) {
User.create({firstName: 'Joe', lastName: 'Eames', username: 'joe'});
User.create({firstName: 'John', lastName: 'Papa', username: 'john'});
User.create({firstName: 'Dan', lastName: 'Wahlin', username: 'dan'});
}
});
};
| bsd-2-clause |
sebastienros/jint | Jint/Runtime/JavaScriptException.cs | 4591 | #nullable enable
using System;
using Esprima;
using Jint.Native;
using Jint.Native.Error;
using Jint.Native.Object;
using Jint.Pooling;
namespace Jint.Runtime
{
public class JavaScriptException : JintException
{
private string? _callStack;
public JavaScriptException(ErrorConstructor errorConstructor) : base("")
{
Error = errorConstructor.Construct(Arguments.Empty);
}
public JavaScriptException(ErrorConstructor errorConstructor, string? message, Exception? innerException)
: base(message, innerException)
{
Error = errorConstructor.Construct(new JsValue[] { message });
}
public JavaScriptException(ErrorConstructor errorConstructor, string? message)
: base(message)
{
Error = errorConstructor.Construct(new JsValue[] { message });
}
public JavaScriptException(JsValue error)
{
Error = error;
}
// Copy constructors
public JavaScriptException(JavaScriptException exception, Exception? innerException) : base(exception.Message, exception.InnerException)
{
Error = exception.Error;
Location = exception.Location;
}
public JavaScriptException(JavaScriptException exception) : base(exception.Message)
{
Error = exception.Error;
Location = exception.Location;
}
internal JavaScriptException SetLocation(Location location)
{
Location = location;
return this;
}
internal JavaScriptException SetCallstack(Engine engine, Location location)
{
Location = location;
var value = engine.CallStack.BuildCallStackString(location);
_callStack = value;
if (Error.IsObject())
{
Error.AsObject()
.FastAddProperty(CommonProperties.Stack, new JsString(value), false, false, false);
}
return this;
}
private string? GetErrorMessage()
{
if (Error is ObjectInstance oi)
{
return oi.Get(CommonProperties.Message).ToString();
}
return null;
}
public JsValue Error { get; }
public override string Message => GetErrorMessage() ?? TypeConverter.ToString(Error);
/// <summary>
/// Returns the call stack of the exception. Requires that engine was built using
/// <see cref="Options.CollectStackTrace"/>.
/// </summary>
public override string? StackTrace
{
get
{
if (_callStack is not null)
{
return _callStack;
}
if (Error is not ObjectInstance oi)
{
return null;
}
var callstack = oi.Get(CommonProperties.Stack, Error);
return callstack.IsUndefined()
? null
: callstack.AsString();
}
}
public Location Location { get; protected set; }
public int LineNumber => Location.Start.Line;
public int Column => Location.Start.Column;
public override string ToString()
{
// adapted custom version as logic differs between full framework and .NET Core
var className = GetType().ToString();
var message = Message;
var innerExceptionString = InnerException?.ToString() ?? "";
const string endOfInnerExceptionResource = "--- End of inner exception stack trace ---";
var stackTrace = StackTrace;
using var rent = StringBuilderPool.Rent();
var sb = rent.Builder;
sb.Append(className);
if (!string.IsNullOrEmpty(message))
{
sb.Append(": ");
sb.Append(message);
}
if (InnerException != null)
{
sb.Append(Environment.NewLine);
sb.Append(" ---> ");
sb.Append(innerExceptionString);
sb.Append(Environment.NewLine);
sb.Append(" ");
sb.Append(endOfInnerExceptionResource);
}
if (stackTrace != null)
{
sb.Append(Environment.NewLine);
sb.Append(stackTrace);
}
return rent.ToString();
}
}
} | bsd-2-clause |
AsherGlick/Olympus-Server-Management | SourceServer/Backend/src/charprint.h | 491 | void charprint (std::string output) {
for (unsigned int i = 0; i < output.size(); i++) {
if (output[i] >= 33 && output[i] <= 126) {
std::cout << output[i];
}
else {
std::cout << '(' << int(output[i]) << ')';
}
}
std::cout << std::endl;
}
std::string asciiOnly (std::string input) {
std::string output;
for (unsigned int i = 0; i < input.size(); i++) {
if (input[i] >= 33 && input[i] <= 126) {
output += input[i];
}
}
return output;
}
| bsd-2-clause |
internaut/mastersthesis-mobile-gpgpu | ClAudio/src/net/mkonrad/claudio/cl_audioJNI.java | 952 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package net.mkonrad.claudio;
public class cl_audioJNI {
static {
try {
System.load("/system/vendor/lib/egl/libGLES_mali.so");
java.lang.System.loadLibrary("cl_audio");
} catch (UnsatisfiedLinkError e) {
java.lang.System.err.println("native code library failed to load.\n" + e);
java.lang.System.exit(1);
}
}
public final static native void start_process();
public final static native void stop_process();
public final static native void create_cl_kernel_from_src(String jarg1);
public final static native void cleanup();
}
| bsd-2-clause |
back-to/streamlink | src/streamlink/plugins/skai.py | 889 | import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
YOUTUBE_URL = "https://www.youtube.com/watch?v={0}"
_url_re = re.compile(r'http(s)?://www\.skai.gr/.*')
_youtube_id = re.compile(r'<span\s+itemprop="contentUrl"\s+href="(.*)"></span>', re.MULTILINE)
_youtube_url_schema = validate.Schema(
validate.all(
validate.transform(_youtube_id.search),
validate.any(
None,
validate.all(
validate.get(1),
validate.text
)
)
)
)
class Skai(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
channel_id = self.session.http.get(self.url, schema=_youtube_url_schema)
if channel_id:
return self.session.streams(YOUTUBE_URL.format(channel_id))
__plugin__ = Skai
| bsd-2-clause |
runelite/runelite | runelite-client/src/main/java/net/runelite/client/plugins/worldmap/TransportationPointLocation.java | 15466 | /*
* Copyright (c) 2019, Kyle Sergio <https://github.com/ksergio39>
* Copyright (c) 2019, Bryce Altomare <https://github.com/Twinkiel0ver>
* Copyright (c) 2019, Kyle Stead <http://github.com/kyle1elyk>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.worldmap;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.runelite.api.coords.WorldPoint;
import javax.annotation.Nullable;
@Getter
@AllArgsConstructor
enum TransportationPointLocation
{
//Ships
ARDOUGNE_TO_BRIMHAVEN("Ship to Brimhaven / Rimmington", new WorldPoint(2675, 3275, 0)),
ARDOUGNE_TO_FISHINGPLAT("Ship to Fishing Platform", new WorldPoint(2722, 3304, 0), new WorldPoint(2779, 3271, 0)),
BRIMHAVEN_TO_ARDOUGNE("Ship to Ardougne / Rimmington", new WorldPoint(2772, 3234, 0)),
RIMMINGTON_TO_ARDOUGNE("Ship to Ardougne / Brimhaven", new WorldPoint(2915, 3224, 0)),
CATHERBY_TO_KEEP_LE_FAYE("Ship to Keep Le Faye", new WorldPoint(2804, 3421, 0), new WorldPoint(2769, 3402, 0)),
CORSAIR_TO_RIMMINGTON("Ship to Rimmington", new WorldPoint(2577, 2839, 0), new WorldPoint(2909, 3227, 0 )),
DRAGONTOOTH_TO_PHASMATYS("Ship to Port Phasmatys", new WorldPoint(3791, 3561, 0), new WorldPoint(3703, 3487, 0)),
DIGSITE_TO_FOSSIL("Ship to Fossil Island", new WorldPoint(3361, 3448, 0), new WorldPoint(3723, 3807, 0)),
ENTRANA_TO_PORTSARIM("Ship to Port Sarim", new WorldPoint(2833, 3334, 0), new WorldPoint(3046, 3233, 0)),
FISHINGPLAT_TO_ARDOUGNE("Ship to Ardougne", new WorldPoint(2779, 3271, 0), new WorldPoint(2722, 3304, 0)),
HARMLESS_TO_PORT_PHASMATYS("Ship to Port Phasmatys", new WorldPoint(3682, 2951, 0), new WorldPoint(3709, 3497, 0)),
ICEBERG_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2657, 3988, 0), new WorldPoint(2707, 3735, 0)),
ISLAND_OF_STONE_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2470, 3994, 0), new WorldPoint(2621, 3692, 0)),
ISLAND_TO_APE_ATOLL("Ship to Ape Atoll", new WorldPoint(2891, 2726, 0), new WorldPoint(2802, 2706, 0)),
JATIZSO_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2420, 3780, 0), new WorldPoint(2639, 3710, 0)),
KARAMJA_TO_PORT_SARIM("Ship to Port Sarim", new WorldPoint(2955, 3145, 0), new WorldPoint(3029, 3218, 0)),
KARAMJA_TO_PORT_KHAZARD("Ship to Port Khazard", new WorldPoint(2763, 2957, 0), new WorldPoint(2653, 3166, 0)),
LANDSEND_TO_PORTSARIM_PORTPISCARILIUS("Ship to Port Sarim/Port Piscarilius", new WorldPoint(1503, 3398, 0)),
LUNAR_ISLE_TO_PIRATES_COVE("Ship to Pirates' Cove", new WorldPoint(2137, 3899, 0), new WorldPoint(2223, 3796, 0)),
MISCELLANIA_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2579, 3846, 0), new WorldPoint(2627, 3692, 0)),
NEITIZNOT_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2310, 3779, 0), new WorldPoint(2639, 3710, 0)),
PESTCONTROL_TO_PORTSARIM("Ship to Port Sarim", new WorldPoint(2659, 2675, 0), new WorldPoint(3039, 3201, 0)),
PIRATES_COVE_TO_LUNAR_ISLE("Ship to Lunar Isle", new WorldPoint(2223, 3796, 0), new WorldPoint(2137, 3899, 0)),
PIRATES_COVE_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2212, 3794, 0), new WorldPoint(2620, 3695, 0)),
PORT_PHASMATYS_TO_DRAGONTOOTH("Ship to Dragontooth Island", new WorldPoint(3703, 3487, 0), new WorldPoint(3791, 3561, 0)),
PORT_PHASMATYS_TO_HARMLESS("Ship to Mos Le'Harmless", new WorldPoint(3709, 3497, 0), new WorldPoint(3682, 2951, 0)),
PORT_PISCARILIUS_TO_PORTSARIM_LANDSEND("Ship to Port Sarim/Land's End", new WorldPoint(1823, 3692, 0)),
PORTSARIM_TO_GREAT_KOUREND("Ship to Great Kourend", new WorldPoint(3054, 3244, 0), new WorldPoint(1823, 3692, 0)),
PORTSARIM_TO_ENTRANA("Ship to Entrana", new WorldPoint(3046, 3233, 0), new WorldPoint(2833, 3334, 0)),
PORTSARIM_TO_KARAMJA("Ship to Karamja", new WorldPoint(3029, 3218, 0), new WorldPoint(2955, 3144, 0)),
PORTSARIM_TO_CRANDOR("Ship to Crandor", new WorldPoint(3045, 3205, 0), new WorldPoint(2839, 3261, 0)),
PORTSARIM_TO_PEST_CONTROL("Ship to Pest Control", new WorldPoint(3039, 3201, 0), new WorldPoint(2659, 2675, 0)),
RELLEKKA_TO_JATIZSO_NEITIZNOT("Ship to Jatizso/Neitiznot", new WorldPoint(2639, 3710, 0)),
RELLEKKA_TO_MISCELLANIA("Ship to Miscellania", new WorldPoint(2627, 3692, 0), new WorldPoint(2579, 3846, 0)),
RELLEKKA_TO_PIRATES_COVE("Ship to Pirates' Cove", new WorldPoint(2620, 3695, 0), new WorldPoint(2212, 3794, 0)),
RELLEKKA_TO_WATERBIRTH("Ship to Waterbirth", new WorldPoint(2618, 3685, 0), new WorldPoint(2549, 3758, 0)),
RELLEKKA_TO_WEISS_ICEBERG("Ship to Weiss/Iceberg", new WorldPoint(2707, 3735, 0)),
RELLEKKA_TO_UNGAEL("Ship to Ungael", new WorldPoint(2638, 3698, 0), new WorldPoint(2276, 4034, 0)),
RIMMINGTON_TO_CORSAIR_COVE("Ship to Corsair Cove", new WorldPoint(2909, 3227, 0 ), new WorldPoint(2577, 2839, 0)),
WATERBIRTH_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2549, 3758, 0), new WorldPoint(2618, 3685, 0)),
WEISS_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2847, 3967, 0), new WorldPoint(2707, 3735, 0)),
UNGAEL_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2276, 4034, 0), new WorldPoint(2638, 3698, 0)),
//Row Boats
ROW_BOAT_BATTLEFRONT("Rowboat to Molch/Molch Island/Shayzien", new WorldPoint(1383, 3663, 0)),
ROW_BOAT_BRAIN_DEATH("Rowboat to Port Phasmatys", new WorldPoint(2161, 5117, 0), new WorldPoint(3680, 3538, 0)),
ROW_BOAT_BURGH_DE_ROTT("Rowboat to Meiyerditch", new WorldPoint(3522, 3168, 0), new WorldPoint(3589, 3172, 0)),
ROW_BOAT_CRABCLAW("Rowboat to Hosidius", new WorldPoint(1780, 3417, 0), new WorldPoint(1779, 3457, 0)),
ROW_BOAT_DIVING_ISLAND("Rowboat to Barge/Camp/North of Island", new WorldPoint(3764, 3901, 0)),
ROW_BOAT_FISHING_GUILD("Rowboat to Hemenster", new WorldPoint(2598, 3426, 0), new WorldPoint(2613, 3439, 0)),
ROW_BOAT_GNOME_STRONGHOLD("Rowboat to Fishing Colony", new WorldPoint(2368, 3487, 0), new WorldPoint(2356, 3641, 0)),
ROW_BOAT_FISHING_COLONY("Rowboat to Gnome Stronghold", new WorldPoint(2356, 3641, 0), new WorldPoint(2368, 3487, 0)),
ROW_BOAT_HEMENSTER("Rowboat to Fishing Guild", new WorldPoint(2613, 3439, 0), new WorldPoint(2598, 3426, 0)),
ROW_BOAT_HOSIDIUS("Rowboat to Crabclaw Isle", new WorldPoint(1779, 3457, 0), new WorldPoint(1780, 3417, 0)),
ROW_BOAT_LITHKREN("Rowboat to Mushroom Forest", new WorldPoint(3582, 3973, 0), new WorldPoint(3659, 3849, 0)),
ROW_BOAT_LUMBRIDGE("Rowboat to Misthalin Mystery", new WorldPoint(3238, 3141, 0)),
ROW_BOAT_MOLCH("Rowboat to Molch Island/Shayzien/Battlefront", new WorldPoint(1343, 3646, 0)),
ROW_BOAT_MOLCH_ISLAND("Rowboat to Molch/Shayzien/Battlefront", new WorldPoint(1368, 3641, 0)),
ROW_BOAT_MORT("Rowboat to Mort Myre", new WorldPoint(3518, 3284, 0), new WorldPoint(3498, 3380, 0)),
ROW_BOAT_MORT_SWAMP("Rowboat to Mort'ton", new WorldPoint(3498, 3380, 0), new WorldPoint(3518, 3284, 0)),
ROW_BOAT_MUSEUM_CAMP("Rowboat to Barge/Digsite/North of Island", new WorldPoint(3723, 3807, 0)),
ROW_BOAT_MUSHROOM_FOREST_WEST("Rowboat to Lithkren", new WorldPoint(3659, 3849, 0), new WorldPoint(3582, 3973, 0)),
ROW_BOAT_MUSHROOM_FOREST_NE("Rowboat to Barge/Camp/Sea", new WorldPoint(3733, 3894, 0)),
ROW_BOAT_PORT_PHASMATYS_NORTH("Rowboat to Slepe", new WorldPoint(3670, 3545, 0), new WorldPoint(3661, 3279, 0)),
ROW_BOAT_PORT_PHASMATYS_EAST("Rowboat to Braindeath Island", new WorldPoint(3680, 3538, 0), new WorldPoint(2161, 5117, 0)),
ROW_BOAT_SHAYZIEN("Rowboat to Molch/Molch Island/Battlefront", new WorldPoint(1405, 3612, 0)),
ROW_BOAT_SLEPE("Rowboat to Port Phasmatys", new WorldPoint(3661, 3279, 0), new WorldPoint(3670, 3545, 0)),
OGRE_BOAT_FELDIP("Ogre Boat to Karamja", new WorldPoint(2653, 2964, 0), new WorldPoint(2757, 3085, 0)),
OGRE_BOAT_KARAMJA("Ogre Boat to Feldip", new WorldPoint(2757, 3085, 0), new WorldPoint(2653, 2964, 0)),
//Charter ships
CHARTER_BRIMHAVEN("Charter Ship", new WorldPoint(2760, 3238, 0)),
CHARTER_CATHERBY("Charter Ship", new WorldPoint(2791, 3415, 0)),
CHARTER_CORSAIR_("Charter Ship", new WorldPoint(2589, 2851, 0)),
CHARTER_KARAMJA_NORTH("Charter Ship", new WorldPoint(2954, 3158, 0)),
CHARTER_KARAMJA_EAST("Charter Ship", new WorldPoint(2999, 3032, 0)),
CHARTER_KHAZARD("Charter Ship", new WorldPoint(2673, 3143, 0)),
CHARTER_MOSLE_HARMLESS("Charter Ship", new WorldPoint(3669, 2931, 0)),
CHARTER_PORT_PHASMATYS("Charter Ship", new WorldPoint(3702, 3503, 0)),
CHARTER_PORTSARIM("Charter Ship", new WorldPoint(3037, 3191, 0)),
CHARTER_TYRAS("Charter Ship", new WorldPoint(2141, 3123, 0)),
CHARTER_PRIFDDINAS("Charter Ship", new WorldPoint(2156, 3331, 0)),
CHARTER_PRIFDDINAS_INSTANCE("Charter Ship", new WorldPoint(3180, 6083, 0)),
//Ferries
FERRY_AL_KHARID("Ferry to Ruins of Unkah", new WorldPoint(3269, 3142, 0), new WorldPoint(3145, 2843, 0)),
FERRY_RUINS_OF_UNKAH("Ferry to Al Kharid", new WorldPoint(3145, 2843, 0), new WorldPoint(3269, 3142, 0)),
//Minecarts/Carts
MINE_CART_ARCEUUS("Lovakengj Minecart Network", new WorldPoint(1673, 3832, 0)),
MINE_CART_GRANDEXCHANGE("Minecart to Keldagrim", new WorldPoint(3139, 3504, 0)),
MINE_CART_HOSIDIUS("Lovakengj Minecart Network", new WorldPoint(1656, 3542, 0)),
MINE_CART_ICE_MOUNTAIN("Minecart to Keldagrim", new WorldPoint(2995, 9836, 0)),
MINE_CART_KELDAGRIM("Keldagrim Minecart System", new WorldPoint(2908, 10170, 0)),
MINE_CART_LOVAKENGJ("Lovakengj Minecart Network", new WorldPoint(1524, 3721, 0)),
MINE_CART_PORT_PISCARILIUS("Lovakengj Minecart Network", new WorldPoint(1760, 3708, 0)),
MINE_CART_QUIDAMORTEM("Lovakengj Minecart Network", new WorldPoint(1253, 3550, 0)),
MINE_CART_SHAYZIEN("Lovakengj Minecart Network", new WorldPoint(1586, 3622, 0)),
MINE_CART_WHITE_WOLF_MOUNTAIN("Minecart to Keldagrim", new WorldPoint(2874, 9870, 0)),
CART_TO_BRIMHAVEN("Cart to Brimhaven", new WorldPoint(2833, 2958, 0), new WorldPoint(2780, 3214, 0)),
CART_TO_SHILO("Cart to Shilo Village", new WorldPoint(2780, 3214, 0), new WorldPoint(2833, 2958, 0)),
//Canoes
CANOE_BARBVILLAGE("Canoe", new WorldPoint(3111, 3409, 0)),
CANOE_CHAMPIONSGUILD("Canoe", new WorldPoint(3202, 3344, 0)),
CANOE_EDGEVILLE("Canoe", new WorldPoint(3130, 3509, 0)),
CANOE_LUMBRIDGE("Canoe", new WorldPoint(3241, 3238, 0)),
CANOE_FEROXENCLAVE("Canoe", new WorldPoint(3155, 3630, 0)),
//Gnome Gliders
GNOME_GLIDER_KHARID("Gnome Glider", new WorldPoint(3278, 3213, 0)),
GNOME_GLIDER_APE_ATOLL("Gnome Glider", new WorldPoint(2712, 2804, 0)),
GNOME_GLIDER_KARAMJA("Gnome Glider", new WorldPoint(2971, 2974, 0)),
GNOME_GLIDER_FELDIP("Gnome Glider", new WorldPoint(2540, 2969, 0)),
GNOME_GLIDER_GNOMESTRONGHOLD("Gnome Glider", new WorldPoint(2460, 3502, 0)),
GNOME_GLIDER_WHITEWOLF("Gnome Glider", new WorldPoint(2845, 3501, 0)),
//Balloons
BALLOON_VARROCK("Hot Air Balloon", new WorldPoint(3298, 3480, 0)),
BALLOON_YANILLE("Hot Air Balloon", new WorldPoint(2458, 3108, 0)),
BALLOON_GNOMESTRONGHOLD("Hot Air Balloon", new WorldPoint(2478, 3459, 0)),
BALLOON_TAVERLEY("Hot Air Balloon", new WorldPoint(2936, 3422, 0)),
BALLOON_FALADOR("Hot Air Balloon", new WorldPoint(2921, 3301, 0)),
//Spirit Tree
SPIRITTREE_ARDOUGNE("Spirit Tree", new WorldPoint(2554, 3259, 0)),
SPIRITTREE_CORSAIR("Spirit Tree", new WorldPoint(2485, 2850, 0)),
SPIRITTREE_GNOMESTRONGHOLD("Spirit Tree", new WorldPoint(2459, 3446, 0)),
SPIRITTREE_GNOMEVILLAGE("Spirit Tree", new WorldPoint(2538, 3166, 0)),
SPIRITTREE_GRANDEXCHANGE("Spirit Tree", new WorldPoint(3184, 3510, 0)),
SPIRITTREE_PRIFDDINAS("Spirit Tree", new WorldPoint(3274, 6124, 0)),
//Carpets
CARPET_KHARID("Carpet to Bedabin/Pollnivneach/Uzer", new WorldPoint(3311, 3107, 0)),
CARPET_BEDABIN("Carpet to Shantay Pass", new WorldPoint(3183, 3042, 0), new WorldPoint(3311, 3107, 0)),
CARPET_POLLNIVNEACH_NORTH("Carpet to Shantay Pass", new WorldPoint(3351, 3001, 0), new WorldPoint(3311, 3107, 0)),
CARPET_POLLNIVNEACH_SOUTH("Carpet to Nardah/Sophanem/Menaphos", new WorldPoint(3345, 2943, 0)),
CARPET_NARDAH("Carpet to Pollnivneach", new WorldPoint(3399, 2916, 0), new WorldPoint(3345, 2943, 0)),
CARPET_SOPHANEM("Carpet to Pollnivneach", new WorldPoint(3288, 2814, 0), new WorldPoint(3345, 2943, 0)),
CARPET_MENAPHOS("Carpet to Pollnivneach", new WorldPoint(3244, 2812, 0), new WorldPoint(3345, 2943, 0)),
CARPET_UZER("Carpet to Shantay Pass", new WorldPoint(3468, 3111, 0), new WorldPoint(3311, 3107, 0)),
//Teleports
TELEPORT_ARCHIVE_FROM_ARCEUUS("Teleport to Library Archive", new WorldPoint(1623, 3808, 0)),
TELEPORT_HARMLESS_FROM_HARMONY("Teleport to Mos Le'Harmless", new WorldPoint(3784, 2828, 0)),
TELEPORT_RUNE_ARDOUGNE("Teleport to Rune Essence", new WorldPoint(2681, 3325, 0)),
TELEPORT_RUNE_YANILLE("Teleport to Rune Essence", new WorldPoint(2592, 3089, 0)),
TELEPORT_SORCERESS_GARDEN("Teleport to Sorceress's Garden", new WorldPoint(3320, 3141, 0)),
TELEPORT_PRIFDDINAS_LIBRARY("Teleport to Prifddinas Library", new WorldPoint(3254, 6082, 2)),
//Other
ALTER_KOUREND_UNDERGROUND("Altar to Skotizo", new WorldPoint(1662, 10047, 0)),
FAIRY_RING_ZANARIS_TO_KHARID("Fairy Ring to Al Kharid", new WorldPoint(2483, 4471, 0)),
FAIRY_RING_ZANARIS_TO_SHACK("Fairy Ring to Shack", new WorldPoint(2451, 4471, 0)),
MOUNTAIN_GUIDE_QUIDAMORTEM("Mountain Guide", new WorldPoint(1275, 3559, 0)),
MOUNTAIN_GUIDE_WALL("Mountain Guide", new WorldPoint(1400, 3538, 0)),
MUSHTREE_MUSHROOM_FOREST("Mushtree", new WorldPoint(3674, 3871, 0)),
MUSHTREE_TAR_SWAMP("Mushtree", new WorldPoint(3676, 3755, 0)),
MUSHTREE_VERDANT_VALLEY("Mushtree", new WorldPoint(3757, 3756, 0)),
MYTHS_GUILD_PORTAL("Portal to Guilds", new WorldPoint(2456, 2856, 0)),
SOUL_WARS_PORTAL("Portal to Edgeville/Ferox Enclave", new WorldPoint(2204, 2858, 0)),
TRAIN_KELDAGRIM("Railway Station", new WorldPoint(2941, 10179, 0)),
WILDERNESS_LEVER_ARDOUGNE("Wilderness Lever to Deserted Keep", new WorldPoint(2559, 3309, 0), new WorldPoint(3154, 3924, 0)),
WILDERNESS_LEVER_EDGEVILLE("Wilderness Lever to Deserted Keep", new WorldPoint(3088, 3474, 0), new WorldPoint(3154, 3924, 0)),
WILDERNESS_LEVER_WILDERNESS("Wilderness Lever to Ardougne/Edgeville", new WorldPoint(3154, 3924, 0));
private final String tooltip;
private final WorldPoint location;
@Nullable
private final WorldPoint target;
TransportationPointLocation(String tooltip, WorldPoint worldPoint)
{
this(tooltip, worldPoint, null);
}
}
| bsd-2-clause |
edwardcrichton/BToolkit | MOTIF/CFG_DEP_BASE/CDE/C/MRIState_ffnc_ctx.h | 1456 | /* Copyright (c) 1985-2012, B-Core (UK) Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
extern char * _MRIState_ffnc_ctx_MRIState_FNCOBJ [];
#define MRIState_FNCOBJ _MRIState_ffnc_ctx_MRIState_FNCOBJ
void INI_MRIState_ffnc_ctx();
| bsd-2-clause |
kbarnes3/BaseDjangoSite | web/users/views.py | 696 | from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect, render
from users.forms import UserCreationForm
def create_user_account(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
primary_email = form.cleaned_data['primary_email']
password = form.cleaned_data['password1']
user = authenticate(username=primary_email, password=password)
login(request, user)
return redirect('/')
else:
form = UserCreationForm()
return render(request, 'users/create_user_account.html', {'form': form})
| bsd-2-clause |
wjbeksi/rgbd-covariance-descriptors | spams/dictLearn/mex/mexTrainDL.cpp | 7630 |
/* Software SPAMS v2.1 - Copyright 2009-2011 Julien Mairal
*
* This file is part of SPAMS.
*
* SPAMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SPAMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SPAMS. If not, see <http://www.gnu.org/licenses/>.
*/
/*!
* \file
* toolbox dictLearn
*
* by Julien Mairal
* [email protected]
*
* File mexTrainDL.h
* \brief mex-file, function mexTrainDL
* Usage: [D model] = mexTrainDL(X,param);
* Usage: [D model] = mexTrainDL(X,param,model);
* output model is optional
* */
#include <mexutils.h>
#include <dicts.h>
template <typename T>
inline void callFunction(mxArray* plhs[], const mxArray*prhs[],
const int nlhs,const int nrhs) {
if (!mexCheckType<T>(prhs[0]))
mexErrMsgTxt("type of argument 1 is not consistent");
if (!mxIsStruct(prhs[1]))
mexErrMsgTxt("argument 2 should be struct");
if (nrhs == 3)
if (!mxIsStruct(prhs[2]))
mexErrMsgTxt("argument 3 should be struct");
Data<T> *X;
const mwSize* dimsX=mxGetDimensions(prhs[0]);
int n=static_cast<int>(dimsX[0]);
int M=static_cast<int>(dimsX[1]);
if (mxIsSparse(prhs[0])) {
double * X_v=static_cast<double*>(mxGetPr(prhs[0]));
mwSize* X_r=mxGetIr(prhs[0]);
mwSize* X_pB=mxGetJc(prhs[0]);
mwSize* X_pE=X_pB+1;
int* X_r2, *X_pB2, *X_pE2;
T* X_v2;
createCopySparse<T>(X_v2,X_r2,X_pB2,X_pE2,
X_v,X_r,X_pB,X_pE,M);
X = new SpMatrix<T>(X_v2,X_r2,X_pB2,X_pE2,n,M,X_pB2[M]);
} else {
T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0]));
X= new Matrix<T>(prX,n,M);
}
int NUM_THREADS = getScalarStructDef<int>(prhs[1],"numThreads",-1);
#ifdef _OPENMP
NUM_THREADS = NUM_THREADS == -1 ? omp_get_num_procs() : NUM_THREADS;
#else
NUM_THREADS=1;
#endif
int batch_size = getScalarStructDef<int>(prhs[1],"batchsize",
256*(NUM_THREADS+1));
mxArray* pr_D = mxGetField(prhs[1],0,"D");
Trainer<T>* trainer;
if (!pr_D) {
int K = getScalarStruct<int>(prhs[1],"K");
trainer = new Trainer<T>(K,batch_size,NUM_THREADS);
} else {
T* prD = reinterpret_cast<T*>(mxGetPr(pr_D));
const mwSize* dimsD=mxGetDimensions(pr_D);
int nD=static_cast<int>(dimsD[0]);
int K=static_cast<int>(dimsD[1]);
if (n != nD) mexErrMsgTxt("sizes of D are not consistent");
Matrix<T> D1(prD,n,K);
if (nrhs == 3) {
mxArray* pr_A = mxGetField(prhs[2],0,"A");
if (!pr_A) mexErrMsgTxt("field A is not provided");
T* prA = reinterpret_cast<T*>(mxGetPr(pr_A));
const mwSize* dimsA=mxGetDimensions(pr_A);
int xA=static_cast<int>(dimsA[0]);
int yA=static_cast<int>(dimsA[1]);
if (xA != K || yA != K) mexErrMsgTxt("Size of A is not consistent");
Matrix<T> A(prA,K,K);
mxArray* pr_B = mxGetField(prhs[2],0,"B");
if (!pr_B) mexErrMsgTxt("field B is not provided");
T* prB = reinterpret_cast<T*>(mxGetPr(pr_B));
const mwSize* dimsB=mxGetDimensions(pr_B);
int xB=static_cast<int>(dimsB[0]);
int yB=static_cast<int>(dimsB[1]);
if (xB != n || yB != K) mexErrMsgTxt("Size of B is not consistent");
Matrix<T> B(prB,n,K);
int iter = getScalarStruct<int>(prhs[2],"iter");
trainer = new Trainer<T>(A,B,D1,iter,batch_size,NUM_THREADS);
} else {
trainer = new Trainer<T>(D1,batch_size,NUM_THREADS);
}
}
ParamDictLearn<T> param;
param.lambda = getScalarStruct<T>(prhs[1],"lambda");
param.lambda2 = getScalarStructDef<T>(prhs[1],"lambda2",10e-10);
param.iter=getScalarStruct<int>(prhs[1],"iter");
param.t0 = getScalarStructDef<T>(prhs[1],"t0",1e-5);
param.mode =(constraint_type)getScalarStructDef<int>(prhs[1],"mode",PENALTY);
param.posAlpha = getScalarStructDef<bool>(prhs[1],"posAlpha",false);
param.posD = getScalarStructDef<bool>(prhs[1],"posD",false);
param.expand= getScalarStructDef<bool>(prhs[1],"expand",false);
param.modeD=(constraint_type_D)getScalarStructDef<int>(prhs[1],"modeD",L2);
param.whiten = getScalarStructDef<bool>(prhs[1],"whiten",false);
param.clean = getScalarStructDef<bool>(prhs[1],"clean",true);
param.verbose = getScalarStructDef<bool>(prhs[1],"verbose",true);
param.gamma1 = getScalarStructDef<T>(prhs[1],"gamma1",0);
param.gamma2 = getScalarStructDef<T>(prhs[1],"gamma2",0);
param.rho = getScalarStructDef<T>(prhs[1],"rho",T(1.0));
param.stochastic =
getScalarStructDef<bool>(prhs[1],"stochastic_deprecated",
false);
param.modeParam = static_cast<mode_compute>(getScalarStructDef<int>(prhs[1],"modeParam",0));
param.batch = getScalarStructDef<bool>(prhs[1],"batch",false);
param.iter_updateD = getScalarStructDef<T>(prhs[1],"iter_updateD",param.batch ? 5 : 1);
param.log = getScalarStructDef<bool>(prhs[1],"log_deprecated",
false);
if (param.log) {
mxArray *stringData = mxGetField(prhs[1],0,
"logName_deprecated");
if (!stringData)
mexErrMsgTxt("Missing field logName_deprecated");
int stringLength = mxGetN(stringData)+1;
param.logName= new char[stringLength];
mxGetString(stringData,param.logName,stringLength);
}
trainer->train(*X,param);
if (param.log)
mxFree(param.logName);
Matrix<T> D;
trainer->getD(D);
int K = D.n();
plhs[0] = createMatrix<T>(n,K);
T* prD2 = reinterpret_cast<T*>(mxGetPr(plhs[0]));
Matrix<T> D2(prD2,n,K);
D2.copy(D);
if (nlhs == 2) {
mwSize dims[1] = {1};
int nfields=3;
const char *names[] = {"A", "B", "iter"};
plhs[1]=mxCreateStructArray(1, dims,nfields, names);
mxArray* prA = createMatrix<T>(K,K);
T* pr_A= reinterpret_cast<T*>(mxGetPr(prA));
Matrix<T> A(pr_A,K,K);
trainer->getA(A);
mxSetField(plhs[1],0,"A",prA);
mxArray* prB = createMatrix<T>(n,K);
T* pr_B= reinterpret_cast<T*>(mxGetPr(prB));
Matrix<T> B(pr_B,n,K);
trainer->getB(B);
mxSetField(plhs[1],0,"B",prB);
mxArray* priter = createScalar<T>();
*mxGetPr(priter) = static_cast<T>(trainer->getIter());
mxSetField(plhs[1],0,"iter",priter);
}
delete(trainer);
delete(X);
}
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) {
if (nrhs < 2 || nrhs > 3)
mexErrMsgTxt("Bad number of inputs arguments");
if ((nlhs < 1) || (nlhs > 2))
mexErrMsgTxt("Bad number of output arguments");
if (mxGetClassID(prhs[0]) == mxDOUBLE_CLASS) {
callFunction<double>(plhs,prhs,nlhs,nrhs);
} else {
callFunction<float>(plhs,prhs,nlhs,nrhs);
}
}
| bsd-2-clause |
TheArchives/Nexus | core/entities/confetti_create.py | 291 | # The Nexus software is licensed under the BSD 2-Clause license.
#
# You should have recieved a copy of this license with the software.
# If you did not, you can find one at the following link.
#
# http://opensource.org/licenses/bsd-license.php
entitylist.append(["confetti",(x,y,z),6,6])
| bsd-2-clause |
codeape/eye-engine | engine/PseudoRNG.hpp | 637 | /* A Pseudo Random Number Generator - Mersenne twister
* http://en.wikipedia.org/wiki/Mersenne_twister
* http://my.opera.com/metrallik/blog/2013/04/19/c-class-for-random-generation-with-mersenne-twister-method
*/
#ifndef PSEUDORNG_HPP
#define PSEUDORNG_HPP
class PseudoRNG {
private:
static const unsigned int length=624;
static const unsigned int bitMask_32=0xffffffff;
static const unsigned int bitPow_31=1<<31;
unsigned int mt[length];
unsigned int idx;
public:
PseudoRNG(unsigned int seed);
unsigned int get();
void gen();
~PseudoRNG();
};
#endif
| bsd-2-clause |
arielm/Unicode | Projects/Rendering/src/Sketch.h | 6460 | /*
* THE UNICODE TEST SUITE FOR CINDER: https://github.com/arielm/Unicode
* COPYRIGHT (C) 2013, ARIEL MALKA ALL RIGHTS RESERVED.
*
* THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:
* https://github.com/arielm/Unicode/blob/master/LICENSE.md
*/
/*
* DONE:
*
* 1) MOVING LangHelper TO FontManager AND PROVIDING PROXY TO LayoutCache IN VirtualFont
*
* 2) VirtualFont: ADDING MEANS OF OBTAINING ActualFont::Metrics (E.G. FROM A GIVEN Cluster)
*
* 3) TextItemizer::processLine():
* - DIRECTION IS NOW UNDEFINED BY DEFAULT:
* - IN THIS CASE, THE "PARAGRAPH-LEVEL" WILL BE DETERMINED FROM THE TEXT (VIA BIDI)
* AND THE RESULTING LineLayout WILL RECEIVE AN overallDirection VALUE
* - LIKEWISE, IF LANGUAGE IS UNDEFINED:
* - THE RESULTING LineLayout WILL RECEIVE A langHint VALUE BASED
* ON THE LANGUAGE DETECTED FOR THE FIRST RUN
*
* 4) FIXING REGRESSION (INTRODUCED IN COMMIT 604c7ab) AFFECTING (AT LEAST) HEBREW AND THAI
*
* 5) "COMPOSITE METRICS" FOR VirtualFont GIVEN A LineLayout:
* - getHeight() WILL RETURN THE MAXIMUM HEIGHT
* - getAscent() WILL RETURN THE MAXIMUM ASCENT
* - getDescent() WILL RETURN THE MAXIMUM DESCENT
* - getMiddleLine() WILL RETURN HALF OF getAscent() - getDescent():
* THIS IS LESS IDEAL THAN USING THE STRIKETHROUGH-OFFSET,
* BUT WE HAVE NO CHOICE IN THE CASE OF A "COMPOSITE" LineLayout
*
* 6) API ADDITIONS / IMPROVEMENTS:
* - ActualFont::getFullName()
* - VirtualFont::getCachedLineLayout()
*
* 7) SETTING DEFAULT COLOR FOR VirtualFont
*
* 8) FontManager::getFont()
* - FASTER LOOKUPS VIA THE shortcuts MAP
* - BASIC SYSTEM FOR HANDLING UNDEFINED FONT NAMES AND STYLES:
* - getFont() IS NOW SUPPOSED TO THROW ONLY UPON MALFORMED XML
* OR WHEN A FONT NAME/STYLE COMBINATION DOES NOT EXIST
* AND NO "DEFAULT FONT" HAS BEEN DEFINED
*
* 9) PREPARING THE TERRAIN FOR OPTIMIZED DRAWING:
* - DRAWING THE HORIZONTAL-LINES AND THE TEXT SEPARATELY
* - ONE SINGLE VirtualFont::begin() AND VirtualFont::end() PAIRS ARE USED
* - THE NEXT STEP WILL BE TO USE A SYSTEM FOR GROUPING SIMILAR GLYPH TEXTURES...
* - USING glDrawArrays WITH INTERLEAVED "POSITIONS + TEXTURE-COORDS"
*
* 10) FontManager: POSSIBILITY TO QUERY "TEXTURE MEMORY USAGE"
*
* 11) LayoutCache: POSSIBILITY TO QUERY MEMORY USAGE AND TO CHANGE CAPACITY
*
* 12) FINE-TUNING:
* - FontManager::getCachedFont() METHODS ARE NOW RETURNING A shared_ptr<VirtualFont>:
* - AVOID RISK OF UN-NECESSARY COPY
* - NECESSARY IN ORDER TO PROPERLY REMOVE VirtualFont INSTANCES (TBD)
* - FontManager::getCachedLineLayout() AND LayoutCache::getLineLayout() ARE NOW RETURNING A shared_ptr<LineLayout>:
* - AVOID RISK OF UN-NECESSARY COPY
* - THE CACHE WAS ALREADY USING A shared_ptr INTERNALLY
* - MORE ADAPTED TO THE NOTION OF CACHE, AND NOW CONSISTENT WITH FontManager::getCachedFont()
* - FINALLY FOUND A WAY TO USE PROTECTED CONSTRUCTORS FOR
* VirtualFont AND ActualFont (WHICH SHOULD BE CREATED ONLY VIA FontManager)
* - FontManager::loadGlobalMap() CAN ONLY BE CALLED ONCE (FURTHER ATTEMPTS WILL THROW...)
*
* 13) REDESIGN OF THE ActualFont ECO-SYSTEM:
* - FontManager::reload() HAS BEEN CANCELLED, SINCE FONT RESOURCES (HARFBUZZ AND FREETYPE RELATED)
* ARE NOW RELOADED ONLY WHEN NECESSARY (EITHER UPON LineLayout RENDERING OR CREATION)
* - PREVIOUSLY: AFTER CALLING FontManager::unload(), LineLayout RENDERING OR CREATION
* WAS SIMPLY NOT TAKING PLACE (I.E. UNTIL reload() IS CALLED),
* BUT THE SYSTEM CAN'T BE ADAPTED TO LAZY RELOADING
* - POSSIBILITY TO CALL FontManager::unload(...) PER VirtualFont:
* IT WILL CLEAR THE FONT RESOURCES (HARFBUZZ AND FREETYPE RELATED) AND DISCARD THE GLYPH TEXTURES
* ASSOCIATED SOLELY WITH THE VirtualFont
* - WHY IS IT NECESSARY TO ACTUALLY LOAD (HARFBUZZ AND FREETYPE WISE) ALL
* THE ASSOCIATED ActualFont INSTANCES WHEN A NEW VirtualFont IS CREATED?
* A) FREETYPE IS ABLE TO DETERMINE IF A FONT IS OKAY ONLY AFTER LOADING IT
* B) THE VirtualFont XML-FONT DEFINITION IS DESIGNED IN A WAY WHICH REQUIRES
* TO KNOW IF A FONT IS OKAY (SEE THE Group CONSTRUCT)
* C) WE ARE CURRENTLY PRODUCING A PROPER FontSet FOR EACH LANGUAGE UPON VirtualFont
* CREATION, WHICH IS GREATLY SIMPLIFYING THE OPERATIONS
* - IF MEMORY REALLY MATTERS: IT'S ALWAYS POSSIBLE TO CALL FontManager::unload()
* RIGHT AFTER CREATING ALL YOUR VirtualFont INSTANCES
*
* 14) XML FORMAT REDESIGN:
* - REFACTORING TO Font::loadConfig()
* - "DEFAULT FONT" DEFINED IN FontConfig/DefaultFont:
* - CALLING FontManager::getFont() WITH SOME UNDEFINED
* NAME WILL RETURN THE "DEFAULT FONT"
* - ALIASES DEFINED IN FontConfig/Aliases, E.G.
* - "Arial" FOR "sans-serif"
* - "Times" FOR "serif"
*
* 15) DEVELOPMENT HAS MOVED TO THE new-chronotext-toolkit REPOSITORY (CURRENTLY IN SYNC WITH THE develop BRANCH):
* - NUMEROUS TWEAKS, BUT IN ESSENCE:
* - API UNIFICATION WITH THE XFont SYSTEM
* - POSSIBILITY TO DO BATCH-RENDERING
*/
/*
* ON THE DESKTOP:
* - PRESS ENTER TO SHUFFLE THE LINES
* - PRESS SPACE TO TOGGLE SIZE OSCILLATION
* - PRESS T, M OR P TO SWITCH BETWEEN TOP, MIDDLE OR BOTTOM ALIGNMENTS
* - PRESS U TO CALL FontManager::unload()
* - PRESS X TO PRINT TEXTURE MEMORY USAGE
*/
/*
* ON iOS, WE'RE USING FONTS FROM THE "CACHE":
* - IT'S NOT WORKING IN THE SIMULATOR
* - IT PROBABLY WON'T PASS APP-STORE VALIDATION
*/
#pragma once
#include "chronotext/cinder/CinderSketch.h"
#include "chronotext/font/zf/FontManager.h"
#include "cinder/Rand.h"
class Sketch : public chr::CinderSketch
{
public:
chr::zf::FontManager fontManager;
std::vector<std::string> sentences;
ci::Rand rnd;
std::vector<std::string> lines;
float fontSize;
chr::ZFont::Alignment align;
bool oscillate;
Sketch(void *context, void *delegate = NULL);
void setup(bool renewContext);
void event(int id);
void update();
void draw();
void drawTextLine(chr::ZFont &font, const std::string &text, float y, float left, float right);
static void drawHLines(int count, float top, float spacing);
static void drawHLine(float y);
void shuffleLines();
static std::string trimText(const std::string &text);
};
| bsd-2-clause |
nyaki-HUN/DESIRE | DESIRE-Modules/UI-HorusUI/Externals/horus_ui/libs/freetype/include/freetype/freetype.h | 165532 | /****************************************************************************
*
* freetype.h
*
* FreeType high-level API and common types (specification only).
*
* Copyright (C) 1996-2019 by
* David Turner, Robert Wilhelm, and Werner Lemberg.
*
* This file is part of the FreeType project, and may only be used,
* modified, and distributed under the terms of the FreeType project
* license, LICENSE.TXT. By continuing to use, modify, or distribute
* this file you indicate that you have read the license and
* understand and accept it fully.
*
*/
#ifndef FREETYPE_H_
#define FREETYPE_H_
#ifndef FT_FREETYPE_H
#error "`ft2build.h' hasn't been included yet!"
#error "Please always use macros to include FreeType header files."
#error "Example:"
#error " #include <ft2build.h>"
#error " #include FT_FREETYPE_H"
#endif
#include <ft2build.h>
#include FT_CONFIG_CONFIG_H
#include FT_TYPES_H
#include FT_ERRORS_H
FT_BEGIN_HEADER
/**************************************************************************
*
* @section:
* header_inclusion
*
* @title:
* FreeType's header inclusion scheme
*
* @abstract:
* How client applications should include FreeType header files.
*
* @description:
* To be as flexible as possible (and for historical reasons), FreeType
* uses a very special inclusion scheme to load header files, for example
*
* ```
* #include <ft2build.h>
*
* #include FT_FREETYPE_H
* #include FT_OUTLINE_H
* ```
*
* A compiler and its preprocessor only needs an include path to find the
* file `ft2build.h`; the exact locations and names of the other FreeType
* header files are hidden by @header_file_macros, loaded by
* `ft2build.h`. The API documentation always gives the header macro
* name needed for a particular function.
*
*/
/**************************************************************************
*
* @section:
* user_allocation
*
* @title:
* User allocation
*
* @abstract:
* How client applications should allocate FreeType data structures.
*
* @description:
* FreeType assumes that structures allocated by the user and passed as
* arguments are zeroed out except for the actual data. In other words,
* it is recommended to use `calloc` (or variants of it) instead of
* `malloc` for allocation.
*
*/
/*************************************************************************/
/*************************************************************************/
/* */
/* B A S I C T Y P E S */
/* */
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* @section:
* base_interface
*
* @title:
* Base Interface
*
* @abstract:
* The FreeType~2 base font interface.
*
* @description:
* This section describes the most important public high-level API
* functions of FreeType~2.
*
* @order:
* FT_Library
* FT_Face
* FT_Size
* FT_GlyphSlot
* FT_CharMap
* FT_Encoding
* FT_ENC_TAG
*
* FT_FaceRec
*
* FT_FACE_FLAG_SCALABLE
* FT_FACE_FLAG_FIXED_SIZES
* FT_FACE_FLAG_FIXED_WIDTH
* FT_FACE_FLAG_HORIZONTAL
* FT_FACE_FLAG_VERTICAL
* FT_FACE_FLAG_COLOR
* FT_FACE_FLAG_SFNT
* FT_FACE_FLAG_CID_KEYED
* FT_FACE_FLAG_TRICKY
* FT_FACE_FLAG_KERNING
* FT_FACE_FLAG_MULTIPLE_MASTERS
* FT_FACE_FLAG_VARIATION
* FT_FACE_FLAG_GLYPH_NAMES
* FT_FACE_FLAG_EXTERNAL_STREAM
* FT_FACE_FLAG_HINTER
*
* FT_HAS_HORIZONTAL
* FT_HAS_VERTICAL
* FT_HAS_KERNING
* FT_HAS_FIXED_SIZES
* FT_HAS_GLYPH_NAMES
* FT_HAS_COLOR
* FT_HAS_MULTIPLE_MASTERS
*
* FT_IS_SFNT
* FT_IS_SCALABLE
* FT_IS_FIXED_WIDTH
* FT_IS_CID_KEYED
* FT_IS_TRICKY
* FT_IS_NAMED_INSTANCE
* FT_IS_VARIATION
*
* FT_STYLE_FLAG_BOLD
* FT_STYLE_FLAG_ITALIC
*
* FT_SizeRec
* FT_Size_Metrics
*
* FT_GlyphSlotRec
* FT_Glyph_Metrics
* FT_SubGlyph
*
* FT_Bitmap_Size
*
* FT_Init_FreeType
* FT_Done_FreeType
*
* FT_New_Face
* FT_Done_Face
* FT_Reference_Face
* FT_New_Memory_Face
* FT_Face_Properties
* FT_Open_Face
* FT_Open_Args
* FT_Parameter
* FT_Attach_File
* FT_Attach_Stream
*
* FT_Set_Char_Size
* FT_Set_Pixel_Sizes
* FT_Request_Size
* FT_Select_Size
* FT_Size_Request_Type
* FT_Size_RequestRec
* FT_Size_Request
* FT_Set_Transform
* FT_Load_Glyph
* FT_Get_Char_Index
* FT_Get_First_Char
* FT_Get_Next_Char
* FT_Get_Name_Index
* FT_Load_Char
*
* FT_OPEN_MEMORY
* FT_OPEN_STREAM
* FT_OPEN_PATHNAME
* FT_OPEN_DRIVER
* FT_OPEN_PARAMS
*
* FT_LOAD_DEFAULT
* FT_LOAD_RENDER
* FT_LOAD_MONOCHROME
* FT_LOAD_LINEAR_DESIGN
* FT_LOAD_NO_SCALE
* FT_LOAD_NO_HINTING
* FT_LOAD_NO_BITMAP
* FT_LOAD_NO_AUTOHINT
* FT_LOAD_COLOR
*
* FT_LOAD_VERTICAL_LAYOUT
* FT_LOAD_IGNORE_TRANSFORM
* FT_LOAD_FORCE_AUTOHINT
* FT_LOAD_NO_RECURSE
* FT_LOAD_PEDANTIC
*
* FT_LOAD_TARGET_NORMAL
* FT_LOAD_TARGET_LIGHT
* FT_LOAD_TARGET_MONO
* FT_LOAD_TARGET_LCD
* FT_LOAD_TARGET_LCD_V
*
* FT_LOAD_TARGET_MODE
*
* FT_Render_Glyph
* FT_Render_Mode
* FT_Get_Kerning
* FT_Kerning_Mode
* FT_Get_Track_Kerning
* FT_Get_Glyph_Name
* FT_Get_Postscript_Name
*
* FT_CharMapRec
* FT_Select_Charmap
* FT_Set_Charmap
* FT_Get_Charmap_Index
*
* FT_Get_FSType_Flags
* FT_Get_SubGlyph_Info
*
* FT_Face_Internal
* FT_Size_Internal
* FT_Slot_Internal
*
* FT_FACE_FLAG_XXX
* FT_STYLE_FLAG_XXX
* FT_OPEN_XXX
* FT_LOAD_XXX
* FT_LOAD_TARGET_XXX
* FT_SUBGLYPH_FLAG_XXX
* FT_FSTYPE_XXX
*
* FT_HAS_FAST_GLYPHS
*
*/
/**************************************************************************
*
* @struct:
* FT_Glyph_Metrics
*
* @description:
* A structure to model the metrics of a single glyph. The values are
* expressed in 26.6 fractional pixel format; if the flag
* @FT_LOAD_NO_SCALE has been used while loading the glyph, values are
* expressed in font units instead.
*
* @fields:
* width ::
* The glyph's width.
*
* height ::
* The glyph's height.
*
* horiBearingX ::
* Left side bearing for horizontal layout.
*
* horiBearingY ::
* Top side bearing for horizontal layout.
*
* horiAdvance ::
* Advance width for horizontal layout.
*
* vertBearingX ::
* Left side bearing for vertical layout.
*
* vertBearingY ::
* Top side bearing for vertical layout. Larger positive values mean
* further below the vertical glyph origin.
*
* vertAdvance ::
* Advance height for vertical layout. Positive values mean the glyph
* has a positive advance downward.
*
* @note:
* If not disabled with @FT_LOAD_NO_HINTING, the values represent
* dimensions of the hinted glyph (in case hinting is applicable).
*
* Stroking a glyph with an outside border does not increase
* `horiAdvance` or `vertAdvance`; you have to manually adjust these
* values to account for the added width and height.
*
* FreeType doesn't use the 'VORG' table data for CFF fonts because it
* doesn't have an interface to quickly retrieve the glyph height. The
* y~coordinate of the vertical origin can be simply computed as
* `vertBearingY + height` after loading a glyph.
*/
typedef struct FT_Glyph_Metrics_
{
FT_Pos width;
FT_Pos height;
FT_Pos horiBearingX;
FT_Pos horiBearingY;
FT_Pos horiAdvance;
FT_Pos vertBearingX;
FT_Pos vertBearingY;
FT_Pos vertAdvance;
} FT_Glyph_Metrics;
/**************************************************************************
*
* @struct:
* FT_Bitmap_Size
*
* @description:
* This structure models the metrics of a bitmap strike (i.e., a set of
* glyphs for a given point size and resolution) in a bitmap font. It is
* used for the `available_sizes` field of @FT_Face.
*
* @fields:
* height ::
* The vertical distance, in pixels, between two consecutive baselines.
* It is always positive.
*
* width ::
* The average width, in pixels, of all glyphs in the strike.
*
* size ::
* The nominal size of the strike in 26.6 fractional points. This
* field is not very useful.
*
* x_ppem ::
* The horizontal ppem (nominal width) in 26.6 fractional pixels.
*
* y_ppem ::
* The vertical ppem (nominal height) in 26.6 fractional pixels.
*
* @note:
* Windows FNT:
* The nominal size given in a FNT font is not reliable. If the driver
* finds it incorrect, it sets `size` to some calculated values, and
* `x_ppem` and `y_ppem` to the pixel width and height given in the
* font, respectively.
*
* TrueType embedded bitmaps:
* `size`, `width`, and `height` values are not contained in the bitmap
* strike itself. They are computed from the global font parameters.
*/
typedef struct FT_Bitmap_Size_
{
FT_Short height;
FT_Short width;
FT_Pos size;
FT_Pos x_ppem;
FT_Pos y_ppem;
} FT_Bitmap_Size;
/*************************************************************************/
/*************************************************************************/
/* */
/* O B J E C T C L A S S E S */
/* */
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* @type:
* FT_Library
*
* @description:
* A handle to a FreeType library instance. Each 'library' is completely
* independent from the others; it is the 'root' of a set of objects like
* fonts, faces, sizes, etc.
*
* It also embeds a memory manager (see @FT_Memory), as well as a
* scan-line converter object (see @FT_Raster).
*
* [Since 2.5.6] In multi-threaded applications it is easiest to use one
* `FT_Library` object per thread. In case this is too cumbersome, a
* single `FT_Library` object across threads is possible also, as long as
* a mutex lock is used around @FT_New_Face and @FT_Done_Face.
*
* @note:
* Library objects are normally created by @FT_Init_FreeType, and
* destroyed with @FT_Done_FreeType. If you need reference-counting
* (cf. @FT_Reference_Library), use @FT_New_Library and @FT_Done_Library.
*/
typedef struct FT_LibraryRec_ *FT_Library;
/**************************************************************************
*
* @section:
* module_management
*
*/
/**************************************************************************
*
* @type:
* FT_Module
*
* @description:
* A handle to a given FreeType module object. A module can be a font
* driver, a renderer, or anything else that provides services to the
* former.
*/
typedef struct FT_ModuleRec_* FT_Module;
/**************************************************************************
*
* @type:
* FT_Driver
*
* @description:
* A handle to a given FreeType font driver object. A font driver is a
* module capable of creating faces from font files.
*/
typedef struct FT_DriverRec_* FT_Driver;
/**************************************************************************
*
* @type:
* FT_Renderer
*
* @description:
* A handle to a given FreeType renderer. A renderer is a module in
* charge of converting a glyph's outline image to a bitmap. It supports
* a single glyph image format, and one or more target surface depths.
*/
typedef struct FT_RendererRec_* FT_Renderer;
/**************************************************************************
*
* @section:
* base_interface
*
*/
/**************************************************************************
*
* @type:
* FT_Face
*
* @description:
* A handle to a typographic face object. A face object models a given
* typeface, in a given style.
*
* @note:
* A face object also owns a single @FT_GlyphSlot object, as well as one
* or more @FT_Size objects.
*
* Use @FT_New_Face or @FT_Open_Face to create a new face object from a
* given filepath or a custom input stream.
*
* Use @FT_Done_Face to destroy it (along with its slot and sizes).
*
* An `FT_Face` object can only be safely used from one thread at a time.
* Similarly, creation and destruction of `FT_Face` with the same
* @FT_Library object can only be done from one thread at a time. On the
* other hand, functions like @FT_Load_Glyph and its siblings are
* thread-safe and do not need the lock to be held as long as the same
* `FT_Face` object is not used from multiple threads at the same time.
*
* @also:
* See @FT_FaceRec for the publicly accessible fields of a given face
* object.
*/
typedef struct FT_FaceRec_* FT_Face;
/**************************************************************************
*
* @type:
* FT_Size
*
* @description:
* A handle to an object that models a face scaled to a given character
* size.
*
* @note:
* An @FT_Face has one _active_ @FT_Size object that is used by functions
* like @FT_Load_Glyph to determine the scaling transformation that in
* turn is used to load and hint glyphs and metrics.
*
* You can use @FT_Set_Char_Size, @FT_Set_Pixel_Sizes, @FT_Request_Size
* or even @FT_Select_Size to change the content (i.e., the scaling
* values) of the active @FT_Size.
*
* You can use @FT_New_Size to create additional size objects for a given
* @FT_Face, but they won't be used by other functions until you activate
* it through @FT_Activate_Size. Only one size can be activated at any
* given time per face.
*
* @also:
* See @FT_SizeRec for the publicly accessible fields of a given size
* object.
*/
typedef struct FT_SizeRec_* FT_Size;
/**************************************************************************
*
* @type:
* FT_GlyphSlot
*
* @description:
* A handle to a given 'glyph slot'. A slot is a container that can hold
* any of the glyphs contained in its parent face.
*
* In other words, each time you call @FT_Load_Glyph or @FT_Load_Char,
* the slot's content is erased by the new glyph data, i.e., the glyph's
* metrics, its image (bitmap or outline), and other control information.
*
* @also:
* See @FT_GlyphSlotRec for the publicly accessible glyph fields.
*/
typedef struct FT_GlyphSlotRec_* FT_GlyphSlot;
/**************************************************************************
*
* @type:
* FT_CharMap
*
* @description:
* A handle to a character map (usually abbreviated to 'charmap'). A
* charmap is used to translate character codes in a given encoding into
* glyph indexes for its parent's face. Some font formats may provide
* several charmaps per font.
*
* Each face object owns zero or more charmaps, but only one of them can
* be 'active', providing the data used by @FT_Get_Char_Index or
* @FT_Load_Char.
*
* The list of available charmaps in a face is available through the
* `face->num_charmaps` and `face->charmaps` fields of @FT_FaceRec.
*
* The currently active charmap is available as `face->charmap`. You
* should call @FT_Set_Charmap to change it.
*
* @note:
* When a new face is created (either through @FT_New_Face or
* @FT_Open_Face), the library looks for a Unicode charmap within the
* list and automatically activates it. If there is no Unicode charmap,
* FreeType doesn't set an 'active' charmap.
*
* @also:
* See @FT_CharMapRec for the publicly accessible fields of a given
* character map.
*/
typedef struct FT_CharMapRec_* FT_CharMap;
/**************************************************************************
*
* @macro:
* FT_ENC_TAG
*
* @description:
* This macro converts four-letter tags into an unsigned long. It is
* used to define 'encoding' identifiers (see @FT_Encoding).
*
* @note:
* Since many 16-bit compilers don't like 32-bit enumerations, you should
* redefine this macro in case of problems to something like this:
*
* ```
* #define FT_ENC_TAG( value, a, b, c, d ) value
* ```
*
* to get a simple enumeration without assigning special numbers.
*/
#ifndef FT_ENC_TAG
#define FT_ENC_TAG( value, a, b, c, d ) \
value = ( ( (FT_UInt32)(a) << 24 ) | \
( (FT_UInt32)(b) << 16 ) | \
( (FT_UInt32)(c) << 8 ) | \
(FT_UInt32)(d) )
#endif /* FT_ENC_TAG */
/**************************************************************************
*
* @enum:
* FT_Encoding
*
* @description:
* An enumeration to specify character sets supported by charmaps. Used
* in the @FT_Select_Charmap API function.
*
* @note:
* Despite the name, this enumeration lists specific character
* repertories (i.e., charsets), and not text encoding methods (e.g.,
* UTF-8, UTF-16, etc.).
*
* Other encodings might be defined in the future.
*
* @values:
* FT_ENCODING_NONE ::
* The encoding value~0 is reserved for all formats except BDF, PCF,
* and Windows FNT; see below for more information.
*
* FT_ENCODING_UNICODE ::
* The Unicode character set. This value covers all versions of the
* Unicode repertoire, including ASCII and Latin-1. Most fonts include
* a Unicode charmap, but not all of them.
*
* For example, if you want to access Unicode value U+1F028 (and the
* font contains it), use value 0x1F028 as the input value for
* @FT_Get_Char_Index.
*
* FT_ENCODING_MS_SYMBOL ::
* Microsoft Symbol encoding, used to encode mathematical symbols and
* wingdings. For more information, see
* 'https://www.microsoft.com/typography/otspec/recom.htm#non-standard-symbol-fonts',
* 'http://www.kostis.net/charsets/symbol.htm', and
* 'http://www.kostis.net/charsets/wingding.htm'.
*
* This encoding uses character codes from the PUA (Private Unicode
* Area) in the range U+F020-U+F0FF.
*
* FT_ENCODING_SJIS ::
* Shift JIS encoding for Japanese. More info at
* 'https://en.wikipedia.org/wiki/Shift_JIS'. See note on multi-byte
* encodings below.
*
* FT_ENCODING_PRC ::
* Corresponds to encoding systems mainly for Simplified Chinese as
* used in People's Republic of China (PRC). The encoding layout is
* based on GB~2312 and its supersets GBK and GB~18030.
*
* FT_ENCODING_BIG5 ::
* Corresponds to an encoding system for Traditional Chinese as used in
* Taiwan and Hong Kong.
*
* FT_ENCODING_WANSUNG ::
* Corresponds to the Korean encoding system known as Extended Wansung
* (MS Windows code page 949). For more information see
* 'https://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WindowsBestFit/bestfit949.txt'.
*
* FT_ENCODING_JOHAB ::
* The Korean standard character set (KS~C 5601-1992), which
* corresponds to MS Windows code page 1361. This character set
* includes all possible Hangul character combinations.
*
* FT_ENCODING_ADOBE_LATIN_1 ::
* Corresponds to a Latin-1 encoding as defined in a Type~1 PostScript
* font. It is limited to 256 character codes.
*
* FT_ENCODING_ADOBE_STANDARD ::
* Adobe Standard encoding, as found in Type~1, CFF, and OpenType/CFF
* fonts. It is limited to 256 character codes.
*
* FT_ENCODING_ADOBE_EXPERT ::
* Adobe Expert encoding, as found in Type~1, CFF, and OpenType/CFF
* fonts. It is limited to 256 character codes.
*
* FT_ENCODING_ADOBE_CUSTOM ::
* Corresponds to a custom encoding, as found in Type~1, CFF, and
* OpenType/CFF fonts. It is limited to 256 character codes.
*
* FT_ENCODING_APPLE_ROMAN ::
* Apple roman encoding. Many TrueType and OpenType fonts contain a
* charmap for this 8-bit encoding, since older versions of Mac OS are
* able to use it.
*
* FT_ENCODING_OLD_LATIN_2 ::
* This value is deprecated and was neither used nor reported by
* FreeType. Don't use or test for it.
*
* FT_ENCODING_MS_SJIS ::
* Same as FT_ENCODING_SJIS. Deprecated.
*
* FT_ENCODING_MS_GB2312 ::
* Same as FT_ENCODING_PRC. Deprecated.
*
* FT_ENCODING_MS_BIG5 ::
* Same as FT_ENCODING_BIG5. Deprecated.
*
* FT_ENCODING_MS_WANSUNG ::
* Same as FT_ENCODING_WANSUNG. Deprecated.
*
* FT_ENCODING_MS_JOHAB ::
* Same as FT_ENCODING_JOHAB. Deprecated.
*
* @note:
* By default, FreeType enables a Unicode charmap and tags it with
* `FT_ENCODING_UNICODE` when it is either provided or can be generated
* from PostScript glyph name dictionaries in the font file. All other
* encodings are considered legacy and tagged only if explicitly defined
* in the font file. Otherwise, `FT_ENCODING_NONE` is used.
*
* `FT_ENCODING_NONE` is set by the BDF and PCF drivers if the charmap is
* neither Unicode nor ISO-8859-1 (otherwise it is set to
* `FT_ENCODING_UNICODE`). Use @FT_Get_BDF_Charset_ID to find out which
* encoding is really present. If, for example, the `cs_registry` field
* is 'KOI8' and the `cs_encoding` field is 'R', the font is encoded in
* KOI8-R.
*
* `FT_ENCODING_NONE` is always set (with a single exception) by the
* winfonts driver. Use @FT_Get_WinFNT_Header and examine the `charset`
* field of the @FT_WinFNT_HeaderRec structure to find out which encoding
* is really present. For example, @FT_WinFNT_ID_CP1251 (204) means
* Windows code page 1251 (for Russian).
*
* `FT_ENCODING_NONE` is set if `platform_id` is @TT_PLATFORM_MACINTOSH
* and `encoding_id` is not `TT_MAC_ID_ROMAN` (otherwise it is set to
* `FT_ENCODING_APPLE_ROMAN`).
*
* If `platform_id` is @TT_PLATFORM_MACINTOSH, use the function
* @FT_Get_CMap_Language_ID to query the Mac language ID that may be
* needed to be able to distinguish Apple encoding variants. See
*
* https://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
*
* to get an idea how to do that. Basically, if the language ID is~0,
* don't use it, otherwise subtract 1 from the language ID. Then examine
* `encoding_id`. If, for example, `encoding_id` is `TT_MAC_ID_ROMAN`
* and the language ID (minus~1) is `TT_MAC_LANGID_GREEK`, it is the
* Greek encoding, not Roman. `TT_MAC_ID_ARABIC` with
* `TT_MAC_LANGID_FARSI` means the Farsi variant the Arabic encoding.
*/
typedef enum FT_Encoding_
{
FT_ENC_TAG( FT_ENCODING_NONE, 0, 0, 0, 0 ),
FT_ENC_TAG( FT_ENCODING_MS_SYMBOL, 's', 'y', 'm', 'b' ),
FT_ENC_TAG( FT_ENCODING_UNICODE, 'u', 'n', 'i', 'c' ),
FT_ENC_TAG( FT_ENCODING_SJIS, 's', 'j', 'i', 's' ),
FT_ENC_TAG( FT_ENCODING_PRC, 'g', 'b', ' ', ' ' ),
FT_ENC_TAG( FT_ENCODING_BIG5, 'b', 'i', 'g', '5' ),
FT_ENC_TAG( FT_ENCODING_WANSUNG, 'w', 'a', 'n', 's' ),
FT_ENC_TAG( FT_ENCODING_JOHAB, 'j', 'o', 'h', 'a' ),
/* for backward compatibility */
FT_ENCODING_GB2312 = FT_ENCODING_PRC,
FT_ENCODING_MS_SJIS = FT_ENCODING_SJIS,
FT_ENCODING_MS_GB2312 = FT_ENCODING_PRC,
FT_ENCODING_MS_BIG5 = FT_ENCODING_BIG5,
FT_ENCODING_MS_WANSUNG = FT_ENCODING_WANSUNG,
FT_ENCODING_MS_JOHAB = FT_ENCODING_JOHAB,
FT_ENC_TAG( FT_ENCODING_ADOBE_STANDARD, 'A', 'D', 'O', 'B' ),
FT_ENC_TAG( FT_ENCODING_ADOBE_EXPERT, 'A', 'D', 'B', 'E' ),
FT_ENC_TAG( FT_ENCODING_ADOBE_CUSTOM, 'A', 'D', 'B', 'C' ),
FT_ENC_TAG( FT_ENCODING_ADOBE_LATIN_1, 'l', 'a', 't', '1' ),
FT_ENC_TAG( FT_ENCODING_OLD_LATIN_2, 'l', 'a', 't', '2' ),
FT_ENC_TAG( FT_ENCODING_APPLE_ROMAN, 'a', 'r', 'm', 'n' )
} FT_Encoding;
/* these constants are deprecated; use the corresponding `FT_Encoding` */
/* values instead */
#define ft_encoding_none FT_ENCODING_NONE
#define ft_encoding_unicode FT_ENCODING_UNICODE
#define ft_encoding_symbol FT_ENCODING_MS_SYMBOL
#define ft_encoding_latin_1 FT_ENCODING_ADOBE_LATIN_1
#define ft_encoding_latin_2 FT_ENCODING_OLD_LATIN_2
#define ft_encoding_sjis FT_ENCODING_SJIS
#define ft_encoding_gb2312 FT_ENCODING_PRC
#define ft_encoding_big5 FT_ENCODING_BIG5
#define ft_encoding_wansung FT_ENCODING_WANSUNG
#define ft_encoding_johab FT_ENCODING_JOHAB
#define ft_encoding_adobe_standard FT_ENCODING_ADOBE_STANDARD
#define ft_encoding_adobe_expert FT_ENCODING_ADOBE_EXPERT
#define ft_encoding_adobe_custom FT_ENCODING_ADOBE_CUSTOM
#define ft_encoding_apple_roman FT_ENCODING_APPLE_ROMAN
/**************************************************************************
*
* @struct:
* FT_CharMapRec
*
* @description:
* The base charmap structure.
*
* @fields:
* face ::
* A handle to the parent face object.
*
* encoding ::
* An @FT_Encoding tag identifying the charmap. Use this with
* @FT_Select_Charmap.
*
* platform_id ::
* An ID number describing the platform for the following encoding ID.
* This comes directly from the TrueType specification and gets
* emulated for other formats.
*
* encoding_id ::
* A platform-specific encoding number. This also comes from the
* TrueType specification and gets emulated similarly.
*/
typedef struct FT_CharMapRec_
{
FT_Face face;
FT_Encoding encoding;
FT_UShort platform_id;
FT_UShort encoding_id;
} FT_CharMapRec;
/*************************************************************************/
/*************************************************************************/
/* */
/* B A S E O B J E C T C L A S S E S */
/* */
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* @type:
* FT_Face_Internal
*
* @description:
* An opaque handle to an `FT_Face_InternalRec` structure that models the
* private data of a given @FT_Face object.
*
* This structure might change between releases of FreeType~2 and is not
* generally available to client applications.
*/
typedef struct FT_Face_InternalRec_* FT_Face_Internal;
/**************************************************************************
*
* @struct:
* FT_FaceRec
*
* @description:
* FreeType root face class structure. A face object models a typeface
* in a font file.
*
* @fields:
* num_faces ::
* The number of faces in the font file. Some font formats can have
* multiple faces in a single font file.
*
* face_index ::
* This field holds two different values. Bits 0-15 are the index of
* the face in the font file (starting with value~0). They are set
* to~0 if there is only one face in the font file.
*
* [Since 2.6.1] Bits 16-30 are relevant to GX and OpenType variation
* fonts only, holding the named instance index for the current face
* index (starting with value~1; value~0 indicates font access without
* a named instance). For non-variation fonts, bits 16-30 are ignored.
* If we have the third named instance of face~4, say, `face_index` is
* set to 0x00030004.
*
* Bit 31 is always zero (this is, `face_index` is always a positive
* value).
*
* [Since 2.9] Changing the design coordinates with
* @FT_Set_Var_Design_Coordinates or @FT_Set_Var_Blend_Coordinates does
* not influence the named instance index value (only
* @FT_Set_Named_Instance does that).
*
* face_flags ::
* A set of bit flags that give important information about the face;
* see @FT_FACE_FLAG_XXX for the details.
*
* style_flags ::
* The lower 16~bits contain a set of bit flags indicating the style of
* the face; see @FT_STYLE_FLAG_XXX for the details.
*
* [Since 2.6.1] Bits 16-30 hold the number of named instances
* available for the current face if we have a GX or OpenType variation
* (sub)font. Bit 31 is always zero (this is, `style_flags` is always
* a positive value). Note that a variation font has always at least
* one named instance, namely the default instance.
*
* num_glyphs ::
* The number of glyphs in the face. If the face is scalable and has
* sbits (see `num_fixed_sizes`), it is set to the number of outline
* glyphs.
*
* For CID-keyed fonts (not in an SFNT wrapper) this value gives the
* highest CID used in the font.
*
* family_name ::
* The face's family name. This is an ASCII string, usually in
* English, that describes the typeface's family (like 'Times New
* Roman', 'Bodoni', 'Garamond', etc). This is a least common
* denominator used to list fonts. Some formats (TrueType & OpenType)
* provide localized and Unicode versions of this string. Applications
* should use the format-specific interface to access them. Can be
* `NULL` (e.g., in fonts embedded in a PDF file).
*
* In case the font doesn't provide a specific family name entry,
* FreeType tries to synthesize one, deriving it from other name
* entries.
*
* style_name ::
* The face's style name. This is an ASCII string, usually in English,
* that describes the typeface's style (like 'Italic', 'Bold',
* 'Condensed', etc). Not all font formats provide a style name, so
* this field is optional, and can be set to `NULL`. As for
* `family_name`, some formats provide localized and Unicode versions
* of this string. Applications should use the format-specific
* interface to access them.
*
* num_fixed_sizes ::
* The number of bitmap strikes in the face. Even if the face is
* scalable, there might still be bitmap strikes, which are called
* 'sbits' in that case.
*
* available_sizes ::
* An array of @FT_Bitmap_Size for all bitmap strikes in the face. It
* is set to `NULL` if there is no bitmap strike.
*
* Note that FreeType tries to sanitize the strike data since they are
* sometimes sloppy or incorrect, but this can easily fail.
*
* num_charmaps ::
* The number of charmaps in the face.
*
* charmaps ::
* An array of the charmaps of the face.
*
* generic ::
* A field reserved for client uses. See the @FT_Generic type
* description.
*
* bbox ::
* The font bounding box. Coordinates are expressed in font units (see
* `units_per_EM`). The box is large enough to contain any glyph from
* the font. Thus, `bbox.yMax` can be seen as the 'maximum ascender',
* and `bbox.yMin` as the 'minimum descender'. Only relevant for
* scalable formats.
*
* Note that the bounding box might be off by (at least) one pixel for
* hinted fonts. See @FT_Size_Metrics for further discussion.
*
* units_per_EM ::
* The number of font units per EM square for this face. This is
* typically 2048 for TrueType fonts, and 1000 for Type~1 fonts. Only
* relevant for scalable formats.
*
* ascender ::
* The typographic ascender of the face, expressed in font units. For
* font formats not having this information, it is set to `bbox.yMax`.
* Only relevant for scalable formats.
*
* descender ::
* The typographic descender of the face, expressed in font units. For
* font formats not having this information, it is set to `bbox.yMin`.
* Note that this field is negative for values below the baseline.
* Only relevant for scalable formats.
*
* height ::
* This value is the vertical distance between two consecutive
* baselines, expressed in font units. It is always positive. Only
* relevant for scalable formats.
*
* If you want the global glyph height, use `ascender - descender`.
*
* max_advance_width ::
* The maximum advance width, in font units, for all glyphs in this
* face. This can be used to make word wrapping computations faster.
* Only relevant for scalable formats.
*
* max_advance_height ::
* The maximum advance height, in font units, for all glyphs in this
* face. This is only relevant for vertical layouts, and is set to
* `height` for fonts that do not provide vertical metrics. Only
* relevant for scalable formats.
*
* underline_position ::
* The position, in font units, of the underline line for this face.
* It is the center of the underlining stem. Only relevant for
* scalable formats.
*
* underline_thickness ::
* The thickness, in font units, of the underline for this face. Only
* relevant for scalable formats.
*
* glyph ::
* The face's associated glyph slot(s).
*
* size ::
* The current active size for this face.
*
* charmap ::
* The current active charmap for this face.
*
* @note:
* Fields may be changed after a call to @FT_Attach_File or
* @FT_Attach_Stream.
*
* For an OpenType variation font, the values of the following fields can
* change after a call to @FT_Set_Var_Design_Coordinates (and friends) if
* the font contains an 'MVAR' table: `ascender`, `descender`, `height`,
* `underline_position`, and `underline_thickness`.
*
* Especially for TrueType fonts see also the documentation for
* @FT_Size_Metrics.
*/
typedef struct FT_FaceRec_
{
FT_Long num_faces;
FT_Long face_index;
FT_Long face_flags;
FT_Long style_flags;
FT_Long num_glyphs;
FT_String* family_name;
FT_String* style_name;
FT_Int num_fixed_sizes;
FT_Bitmap_Size* available_sizes;
FT_Int num_charmaps;
FT_CharMap* charmaps;
FT_Generic generic;
/*# The following member variables (down to `underline_thickness`) */
/*# are only relevant to scalable outlines; cf. @FT_Bitmap_Size */
/*# for bitmap fonts. */
FT_BBox bbox;
FT_UShort units_per_EM;
FT_Short ascender;
FT_Short descender;
FT_Short height;
FT_Short max_advance_width;
FT_Short max_advance_height;
FT_Short underline_position;
FT_Short underline_thickness;
FT_GlyphSlot glyph;
FT_Size size;
FT_CharMap charmap;
/*@private begin */
FT_Driver driver;
FT_Memory memory;
FT_Stream stream;
FT_ListRec sizes_list;
FT_Generic autohint; /* face-specific auto-hinter data */
void* extensions; /* unused */
FT_Face_Internal internal;
/*@private end */
} FT_FaceRec;
/**************************************************************************
*
* @enum:
* FT_FACE_FLAG_XXX
*
* @description:
* A list of bit flags used in the `face_flags` field of the @FT_FaceRec
* structure. They inform client applications of properties of the
* corresponding face.
*
* @values:
* FT_FACE_FLAG_SCALABLE ::
* The face contains outline glyphs. Note that a face can contain
* bitmap strikes also, i.e., a face can have both this flag and
* @FT_FACE_FLAG_FIXED_SIZES set.
*
* FT_FACE_FLAG_FIXED_SIZES ::
* The face contains bitmap strikes. See also the `num_fixed_sizes`
* and `available_sizes` fields of @FT_FaceRec.
*
* FT_FACE_FLAG_FIXED_WIDTH ::
* The face contains fixed-width characters (like Courier, Lucida,
* MonoType, etc.).
*
* FT_FACE_FLAG_SFNT ::
* The face uses the SFNT storage scheme. For now, this means TrueType
* and OpenType.
*
* FT_FACE_FLAG_HORIZONTAL ::
* The face contains horizontal glyph metrics. This should be set for
* all common formats.
*
* FT_FACE_FLAG_VERTICAL ::
* The face contains vertical glyph metrics. This is only available in
* some formats, not all of them.
*
* FT_FACE_FLAG_KERNING ::
* The face contains kerning information. If set, the kerning distance
* can be retrieved using the function @FT_Get_Kerning. Otherwise the
* function always return the vector (0,0). Note that FreeType doesn't
* handle kerning data from the SFNT 'GPOS' table (as present in many
* OpenType fonts).
*
* FT_FACE_FLAG_FAST_GLYPHS ::
* THIS FLAG IS DEPRECATED. DO NOT USE OR TEST IT.
*
* FT_FACE_FLAG_MULTIPLE_MASTERS ::
* The face contains multiple masters and is capable of interpolating
* between them. Supported formats are Adobe MM, TrueType GX, and
* OpenType variation fonts.
*
* See section @multiple_masters for API details.
*
* FT_FACE_FLAG_GLYPH_NAMES ::
* The face contains glyph names, which can be retrieved using
* @FT_Get_Glyph_Name. Note that some TrueType fonts contain broken
* glyph name tables. Use the function @FT_Has_PS_Glyph_Names when
* needed.
*
* FT_FACE_FLAG_EXTERNAL_STREAM ::
* Used internally by FreeType to indicate that a face's stream was
* provided by the client application and should not be destroyed when
* @FT_Done_Face is called. Don't read or test this flag.
*
* FT_FACE_FLAG_HINTER ::
* The font driver has a hinting machine of its own. For example, with
* TrueType fonts, it makes sense to use data from the SFNT 'gasp'
* table only if the native TrueType hinting engine (with the bytecode
* interpreter) is available and active.
*
* FT_FACE_FLAG_CID_KEYED ::
* The face is CID-keyed. In that case, the face is not accessed by
* glyph indices but by CID values. For subsetted CID-keyed fonts this
* has the consequence that not all index values are a valid argument
* to @FT_Load_Glyph. Only the CID values for which corresponding
* glyphs in the subsetted font exist make `FT_Load_Glyph` return
* successfully; in all other cases you get an
* `FT_Err_Invalid_Argument` error.
*
* Note that CID-keyed fonts that are in an SFNT wrapper (this is, all
* OpenType/CFF fonts) don't have this flag set since the glyphs are
* accessed in the normal way (using contiguous indices); the
* 'CID-ness' isn't visible to the application.
*
* FT_FACE_FLAG_TRICKY ::
* The face is 'tricky', this is, it always needs the font format's
* native hinting engine to get a reasonable result. A typical example
* is the old Chinese font `mingli.ttf` (but not `mingliu.ttc`) that
* uses TrueType bytecode instructions to move and scale all of its
* subglyphs.
*
* It is not possible to auto-hint such fonts using
* @FT_LOAD_FORCE_AUTOHINT; it will also ignore @FT_LOAD_NO_HINTING.
* You have to set both @FT_LOAD_NO_HINTING and @FT_LOAD_NO_AUTOHINT to
* really disable hinting; however, you probably never want this except
* for demonstration purposes.
*
* Currently, there are about a dozen TrueType fonts in the list of
* tricky fonts; they are hard-coded in file `ttobjs.c`.
*
* FT_FACE_FLAG_COLOR ::
* [Since 2.5.1] The face has color glyph tables. See @FT_LOAD_COLOR
* for more information.
*
* FT_FACE_FLAG_VARIATION ::
* [Since 2.9] Set if the current face (or named instance) has been
* altered with @FT_Set_MM_Design_Coordinates,
* @FT_Set_Var_Design_Coordinates, or @FT_Set_Var_Blend_Coordinates.
* This flag is unset by a call to @FT_Set_Named_Instance.
*/
#define FT_FACE_FLAG_SCALABLE ( 1L << 0 )
#define FT_FACE_FLAG_FIXED_SIZES ( 1L << 1 )
#define FT_FACE_FLAG_FIXED_WIDTH ( 1L << 2 )
#define FT_FACE_FLAG_SFNT ( 1L << 3 )
#define FT_FACE_FLAG_HORIZONTAL ( 1L << 4 )
#define FT_FACE_FLAG_VERTICAL ( 1L << 5 )
#define FT_FACE_FLAG_KERNING ( 1L << 6 )
#define FT_FACE_FLAG_FAST_GLYPHS ( 1L << 7 )
#define FT_FACE_FLAG_MULTIPLE_MASTERS ( 1L << 8 )
#define FT_FACE_FLAG_GLYPH_NAMES ( 1L << 9 )
#define FT_FACE_FLAG_EXTERNAL_STREAM ( 1L << 10 )
#define FT_FACE_FLAG_HINTER ( 1L << 11 )
#define FT_FACE_FLAG_CID_KEYED ( 1L << 12 )
#define FT_FACE_FLAG_TRICKY ( 1L << 13 )
#define FT_FACE_FLAG_COLOR ( 1L << 14 )
#define FT_FACE_FLAG_VARIATION ( 1L << 15 )
/**************************************************************************
*
* @macro:
* FT_HAS_HORIZONTAL
*
* @description:
* A macro that returns true whenever a face object contains horizontal
* metrics (this is true for all font formats though).
*
* @also:
* @FT_HAS_VERTICAL can be used to check for vertical metrics.
*
*/
#define FT_HAS_HORIZONTAL( face ) \
( (face)->face_flags & FT_FACE_FLAG_HORIZONTAL )
/**************************************************************************
*
* @macro:
* FT_HAS_VERTICAL
*
* @description:
* A macro that returns true whenever a face object contains real
* vertical metrics (and not only synthesized ones).
*
*/
#define FT_HAS_VERTICAL( face ) \
( (face)->face_flags & FT_FACE_FLAG_VERTICAL )
/**************************************************************************
*
* @macro:
* FT_HAS_KERNING
*
* @description:
* A macro that returns true whenever a face object contains kerning data
* that can be accessed with @FT_Get_Kerning.
*
*/
#define FT_HAS_KERNING( face ) \
( (face)->face_flags & FT_FACE_FLAG_KERNING )
/**************************************************************************
*
* @macro:
* FT_IS_SCALABLE
*
* @description:
* A macro that returns true whenever a face object contains a scalable
* font face (true for TrueType, Type~1, Type~42, CID, OpenType/CFF, and
* PFR font formats).
*
*/
#define FT_IS_SCALABLE( face ) \
( (face)->face_flags & FT_FACE_FLAG_SCALABLE )
/**************************************************************************
*
* @macro:
* FT_IS_SFNT
*
* @description:
* A macro that returns true whenever a face object contains a font whose
* format is based on the SFNT storage scheme. This usually means:
* TrueType fonts, OpenType fonts, as well as SFNT-based embedded bitmap
* fonts.
*
* If this macro is true, all functions defined in @FT_SFNT_NAMES_H and
* @FT_TRUETYPE_TABLES_H are available.
*
*/
#define FT_IS_SFNT( face ) \
( (face)->face_flags & FT_FACE_FLAG_SFNT )
/**************************************************************************
*
* @macro:
* FT_IS_FIXED_WIDTH
*
* @description:
* A macro that returns true whenever a face object contains a font face
* that contains fixed-width (or 'monospace', 'fixed-pitch', etc.)
* glyphs.
*
*/
#define FT_IS_FIXED_WIDTH( face ) \
( (face)->face_flags & FT_FACE_FLAG_FIXED_WIDTH )
/**************************************************************************
*
* @macro:
* FT_HAS_FIXED_SIZES
*
* @description:
* A macro that returns true whenever a face object contains some
* embedded bitmaps. See the `available_sizes` field of the @FT_FaceRec
* structure.
*
*/
#define FT_HAS_FIXED_SIZES( face ) \
( (face)->face_flags & FT_FACE_FLAG_FIXED_SIZES )
/**************************************************************************
*
* @macro:
* FT_HAS_FAST_GLYPHS
*
* @description:
* Deprecated.
*
*/
#define FT_HAS_FAST_GLYPHS( face ) 0
/**************************************************************************
*
* @macro:
* FT_HAS_GLYPH_NAMES
*
* @description:
* A macro that returns true whenever a face object contains some glyph
* names that can be accessed through @FT_Get_Glyph_Name.
*
*/
#define FT_HAS_GLYPH_NAMES( face ) \
( (face)->face_flags & FT_FACE_FLAG_GLYPH_NAMES )
/**************************************************************************
*
* @macro:
* FT_HAS_MULTIPLE_MASTERS
*
* @description:
* A macro that returns true whenever a face object contains some
* multiple masters. The functions provided by @FT_MULTIPLE_MASTERS_H
* are then available to choose the exact design you want.
*
*/
#define FT_HAS_MULTIPLE_MASTERS( face ) \
( (face)->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS )
/**************************************************************************
*
* @macro:
* FT_IS_NAMED_INSTANCE
*
* @description:
* A macro that returns true whenever a face object is a named instance
* of a GX or OpenType variation font.
*
* [Since 2.9] Changing the design coordinates with
* @FT_Set_Var_Design_Coordinates or @FT_Set_Var_Blend_Coordinates does
* not influence the return value of this macro (only
* @FT_Set_Named_Instance does that).
*
* @since:
* 2.7
*
*/
#define FT_IS_NAMED_INSTANCE( face ) \
( (face)->face_index & 0x7FFF0000L )
/**************************************************************************
*
* @macro:
* FT_IS_VARIATION
*
* @description:
* A macro that returns true whenever a face object has been altered by
* @FT_Set_MM_Design_Coordinates, @FT_Set_Var_Design_Coordinates, or
* @FT_Set_Var_Blend_Coordinates.
*
* @since:
* 2.9
*
*/
#define FT_IS_VARIATION( face ) \
( (face)->face_flags & FT_FACE_FLAG_VARIATION )
/**************************************************************************
*
* @macro:
* FT_IS_CID_KEYED
*
* @description:
* A macro that returns true whenever a face object contains a CID-keyed
* font. See the discussion of @FT_FACE_FLAG_CID_KEYED for more details.
*
* If this macro is true, all functions defined in @FT_CID_H are
* available.
*
*/
#define FT_IS_CID_KEYED( face ) \
( (face)->face_flags & FT_FACE_FLAG_CID_KEYED )
/**************************************************************************
*
* @macro:
* FT_IS_TRICKY
*
* @description:
* A macro that returns true whenever a face represents a 'tricky' font.
* See the discussion of @FT_FACE_FLAG_TRICKY for more details.
*
*/
#define FT_IS_TRICKY( face ) \
( (face)->face_flags & FT_FACE_FLAG_TRICKY )
/**************************************************************************
*
* @macro:
* FT_HAS_COLOR
*
* @description:
* A macro that returns true whenever a face object contains tables for
* color glyphs.
*
* @since:
* 2.5.1
*
*/
#define FT_HAS_COLOR( face ) \
( (face)->face_flags & FT_FACE_FLAG_COLOR )
/**************************************************************************
*
* @enum:
* FT_STYLE_FLAG_XXX
*
* @description:
* A list of bit flags to indicate the style of a given face. These are
* used in the `style_flags` field of @FT_FaceRec.
*
* @values:
* FT_STYLE_FLAG_ITALIC ::
* The face style is italic or oblique.
*
* FT_STYLE_FLAG_BOLD ::
* The face is bold.
*
* @note:
* The style information as provided by FreeType is very basic. More
* details are beyond the scope and should be done on a higher level (for
* example, by analyzing various fields of the 'OS/2' table in SFNT based
* fonts).
*/
#define FT_STYLE_FLAG_ITALIC ( 1 << 0 )
#define FT_STYLE_FLAG_BOLD ( 1 << 1 )
/**************************************************************************
*
* @type:
* FT_Size_Internal
*
* @description:
* An opaque handle to an `FT_Size_InternalRec` structure, used to model
* private data of a given @FT_Size object.
*/
typedef struct FT_Size_InternalRec_* FT_Size_Internal;
/**************************************************************************
*
* @struct:
* FT_Size_Metrics
*
* @description:
* The size metrics structure gives the metrics of a size object.
*
* @fields:
* x_ppem ::
* The width of the scaled EM square in pixels, hence the term 'ppem'
* (pixels per EM). It is also referred to as 'nominal width'.
*
* y_ppem ::
* The height of the scaled EM square in pixels, hence the term 'ppem'
* (pixels per EM). It is also referred to as 'nominal height'.
*
* x_scale ::
* A 16.16 fractional scaling value to convert horizontal metrics from
* font units to 26.6 fractional pixels. Only relevant for scalable
* font formats.
*
* y_scale ::
* A 16.16 fractional scaling value to convert vertical metrics from
* font units to 26.6 fractional pixels. Only relevant for scalable
* font formats.
*
* ascender ::
* The ascender in 26.6 fractional pixels, rounded up to an integer
* value. See @FT_FaceRec for the details.
*
* descender ::
* The descender in 26.6 fractional pixels, rounded down to an integer
* value. See @FT_FaceRec for the details.
*
* height ::
* The height in 26.6 fractional pixels, rounded to an integer value.
* See @FT_FaceRec for the details.
*
* max_advance ::
* The maximum advance width in 26.6 fractional pixels, rounded to an
* integer value. See @FT_FaceRec for the details.
*
* @note:
* The scaling values, if relevant, are determined first during a size
* changing operation. The remaining fields are then set by the driver.
* For scalable formats, they are usually set to scaled values of the
* corresponding fields in @FT_FaceRec. Some values like ascender or
* descender are rounded for historical reasons; more precise values (for
* outline fonts) can be derived by scaling the corresponding @FT_FaceRec
* values manually, with code similar to the following.
*
* ```
* scaled_ascender = FT_MulFix( face->ascender,
* size_metrics->y_scale );
* ```
*
* Note that due to glyph hinting and the selected rendering mode these
* values are usually not exact; consequently, they must be treated as
* unreliable with an error margin of at least one pixel!
*
* Indeed, the only way to get the exact metrics is to render _all_
* glyphs. As this would be a definite performance hit, it is up to
* client applications to perform such computations.
*
* The `FT_Size_Metrics` structure is valid for bitmap fonts also.
*
*
* **TrueType fonts with native bytecode hinting**
*
* All applications that handle TrueType fonts with native hinting must
* be aware that TTFs expect different rounding of vertical font
* dimensions. The application has to cater for this, especially if it
* wants to rely on a TTF's vertical data (for example, to properly align
* box characters vertically).
*
* Only the application knows _in advance_ that it is going to use native
* hinting for TTFs! FreeType, on the other hand, selects the hinting
* mode not at the time of creating an @FT_Size object but much later,
* namely while calling @FT_Load_Glyph.
*
* Here is some pseudo code that illustrates a possible solution.
*
* ```
* font_format = FT_Get_Font_Format( face );
*
* if ( !strcmp( font_format, "TrueType" ) &&
* do_native_bytecode_hinting )
* {
* ascender = ROUND( FT_MulFix( face->ascender,
* size_metrics->y_scale ) );
* descender = ROUND( FT_MulFix( face->descender,
* size_metrics->y_scale ) );
* }
* else
* {
* ascender = size_metrics->ascender;
* descender = size_metrics->descender;
* }
*
* height = size_metrics->height;
* max_advance = size_metrics->max_advance;
* ```
*/
typedef struct FT_Size_Metrics_
{
FT_UShort x_ppem; /* horizontal pixels per EM */
FT_UShort y_ppem; /* vertical pixels per EM */
FT_Fixed x_scale; /* scaling values used to convert font */
FT_Fixed y_scale; /* units to 26.6 fractional pixels */
FT_Pos ascender; /* ascender in 26.6 frac. pixels */
FT_Pos descender; /* descender in 26.6 frac. pixels */
FT_Pos height; /* text height in 26.6 frac. pixels */
FT_Pos max_advance; /* max horizontal advance, in 26.6 pixels */
} FT_Size_Metrics;
/**************************************************************************
*
* @struct:
* FT_SizeRec
*
* @description:
* FreeType root size class structure. A size object models a face
* object at a given size.
*
* @fields:
* face ::
* Handle to the parent face object.
*
* generic ::
* A typeless pointer, unused by the FreeType library or any of its
* drivers. It can be used by client applications to link their own
* data to each size object.
*
* metrics ::
* Metrics for this size object. This field is read-only.
*/
typedef struct FT_SizeRec_
{
FT_Face face; /* parent face object */
FT_Generic generic; /* generic pointer for client uses */
FT_Size_Metrics metrics; /* size metrics */
FT_Size_Internal internal;
} FT_SizeRec;
/**************************************************************************
*
* @struct:
* FT_SubGlyph
*
* @description:
* The subglyph structure is an internal object used to describe
* subglyphs (for example, in the case of composites).
*
* @note:
* The subglyph implementation is not part of the high-level API, hence
* the forward structure declaration.
*
* You can however retrieve subglyph information with
* @FT_Get_SubGlyph_Info.
*/
typedef struct FT_SubGlyphRec_* FT_SubGlyph;
/**************************************************************************
*
* @type:
* FT_Slot_Internal
*
* @description:
* An opaque handle to an `FT_Slot_InternalRec` structure, used to model
* private data of a given @FT_GlyphSlot object.
*/
typedef struct FT_Slot_InternalRec_* FT_Slot_Internal;
/**************************************************************************
*
* @struct:
* FT_GlyphSlotRec
*
* @description:
* FreeType root glyph slot class structure. A glyph slot is a container
* where individual glyphs can be loaded, be they in outline or bitmap
* format.
*
* @fields:
* library ::
* A handle to the FreeType library instance this slot belongs to.
*
* face ::
* A handle to the parent face object.
*
* next ::
* In some cases (like some font tools), several glyph slots per face
* object can be a good thing. As this is rare, the glyph slots are
* listed through a direct, single-linked list using its `next` field.
*
* glyph_index ::
* [Since 2.10] The glyph index passed as an argument to @FT_Load_Glyph
* while initializing the glyph slot.
*
* generic ::
* A typeless pointer unused by the FreeType library or any of its
* drivers. It can be used by client applications to link their own
* data to each glyph slot object.
*
* metrics ::
* The metrics of the last loaded glyph in the slot. The returned
* values depend on the last load flags (see the @FT_Load_Glyph API
* function) and can be expressed either in 26.6 fractional pixels or
* font units.
*
* Note that even when the glyph image is transformed, the metrics are
* not.
*
* linearHoriAdvance ::
* The advance width of the unhinted glyph. Its value is expressed in
* 16.16 fractional pixels, unless @FT_LOAD_LINEAR_DESIGN is set when
* loading the glyph. This field can be important to perform correct
* WYSIWYG layout. Only relevant for outline glyphs.
*
* linearVertAdvance ::
* The advance height of the unhinted glyph. Its value is expressed in
* 16.16 fractional pixels, unless @FT_LOAD_LINEAR_DESIGN is set when
* loading the glyph. This field can be important to perform correct
* WYSIWYG layout. Only relevant for outline glyphs.
*
* advance ::
* This shorthand is, depending on @FT_LOAD_IGNORE_TRANSFORM, the
* transformed (hinted) advance width for the glyph, in 26.6 fractional
* pixel format. As specified with @FT_LOAD_VERTICAL_LAYOUT, it uses
* either the `horiAdvance` or the `vertAdvance` value of `metrics`
* field.
*
* format ::
* This field indicates the format of the image contained in the glyph
* slot. Typically @FT_GLYPH_FORMAT_BITMAP, @FT_GLYPH_FORMAT_OUTLINE,
* or @FT_GLYPH_FORMAT_COMPOSITE, but other values are possible.
*
* bitmap ::
* This field is used as a bitmap descriptor. Note that the address
* and content of the bitmap buffer can change between calls of
* @FT_Load_Glyph and a few other functions.
*
* bitmap_left ::
* The bitmap's left bearing expressed in integer pixels.
*
* bitmap_top ::
* The bitmap's top bearing expressed in integer pixels. This is the
* distance from the baseline to the top-most glyph scanline, upwards
* y~coordinates being **positive**.
*
* outline ::
* The outline descriptor for the current glyph image if its format is
* @FT_GLYPH_FORMAT_OUTLINE. Once a glyph is loaded, `outline` can be
* transformed, distorted, emboldened, etc. However, it must not be
* freed.
*
* [Since 2.10.1] If @FT_LOAD_NO_SCALE is set, outline coordinates of
* OpenType variation fonts for a selected instance are internally
* handled as 26.6 fractional font units but returned as (rounded)
* integers, as expected. To get unrounded font units, don't use
* @FT_LOAD_NO_SCALE but load the glyph with @FT_LOAD_NO_HINTING and
* scale it, using the font's `units_per_EM` value as the ppem.
*
* num_subglyphs ::
* The number of subglyphs in a composite glyph. This field is only
* valid for the composite glyph format that should normally only be
* loaded with the @FT_LOAD_NO_RECURSE flag.
*
* subglyphs ::
* An array of subglyph descriptors for composite glyphs. There are
* `num_subglyphs` elements in there. Currently internal to FreeType.
*
* control_data ::
* Certain font drivers can also return the control data for a given
* glyph image (e.g. TrueType bytecode, Type~1 charstrings, etc.).
* This field is a pointer to such data; it is currently internal to
* FreeType.
*
* control_len ::
* This is the length in bytes of the control data. Currently internal
* to FreeType.
*
* other ::
* Reserved.
*
* lsb_delta ::
* The difference between hinted and unhinted left side bearing while
* auto-hinting is active. Zero otherwise.
*
* rsb_delta ::
* The difference between hinted and unhinted right side bearing while
* auto-hinting is active. Zero otherwise.
*
* @note:
* If @FT_Load_Glyph is called with default flags (see @FT_LOAD_DEFAULT)
* the glyph image is loaded in the glyph slot in its native format
* (e.g., an outline glyph for TrueType and Type~1 formats). [Since 2.9]
* The prospective bitmap metrics are calculated according to
* @FT_LOAD_TARGET_XXX and other flags even for the outline glyph, even
* if @FT_LOAD_RENDER is not set.
*
* This image can later be converted into a bitmap by calling
* @FT_Render_Glyph. This function searches the current renderer for the
* native image's format, then invokes it.
*
* The renderer is in charge of transforming the native image through the
* slot's face transformation fields, then converting it into a bitmap
* that is returned in `slot->bitmap`.
*
* Note that `slot->bitmap_left` and `slot->bitmap_top` are also used to
* specify the position of the bitmap relative to the current pen
* position (e.g., coordinates (0,0) on the baseline). Of course,
* `slot->format` is also changed to @FT_GLYPH_FORMAT_BITMAP.
*
* Here is a small pseudo code fragment that shows how to use `lsb_delta`
* and `rsb_delta` to do fractional positioning of glyphs:
*
* ```
* FT_GlyphSlot slot = face->glyph;
* FT_Pos origin_x = 0;
*
*
* for all glyphs do
* <load glyph with `FT_Load_Glyph'>
*
* FT_Outline_Translate( slot->outline, origin_x & 63, 0 );
*
* <save glyph image, or render glyph, or ...>
*
* <compute kern between current and next glyph
* and add it to `origin_x'>
*
* origin_x += slot->advance.x;
* origin_x += slot->lsb_delta - slot->rsb_delta;
* endfor
* ```
*
* Here is another small pseudo code fragment that shows how to use
* `lsb_delta` and `rsb_delta` to improve integer positioning of glyphs:
*
* ```
* FT_GlyphSlot slot = face->glyph;
* FT_Pos origin_x = 0;
* FT_Pos prev_rsb_delta = 0;
*
*
* for all glyphs do
* <compute kern between current and previous glyph
* and add it to `origin_x'>
*
* <load glyph with `FT_Load_Glyph'>
*
* if ( prev_rsb_delta - slot->lsb_delta > 32 )
* origin_x -= 64;
* else if ( prev_rsb_delta - slot->lsb_delta < -31 )
* origin_x += 64;
*
* prev_rsb_delta = slot->rsb_delta;
*
* <save glyph image, or render glyph, or ...>
*
* origin_x += slot->advance.x;
* endfor
* ```
*
* If you use strong auto-hinting, you **must** apply these delta values!
* Otherwise you will experience far too large inter-glyph spacing at
* small rendering sizes in most cases. Note that it doesn't harm to use
* the above code for other hinting modes also, since the delta values
* are zero then.
*/
typedef struct FT_GlyphSlotRec_
{
FT_Library library;
FT_Face face;
FT_GlyphSlot next;
FT_UInt glyph_index; /* new in 2.10; was reserved previously */
FT_Generic generic;
FT_Glyph_Metrics metrics;
FT_Fixed linearHoriAdvance;
FT_Fixed linearVertAdvance;
FT_Vector advance;
FT_Glyph_Format format;
FT_Bitmap bitmap;
FT_Int bitmap_left;
FT_Int bitmap_top;
FT_Outline outline;
FT_UInt num_subglyphs;
FT_SubGlyph subglyphs;
void* control_data;
long control_len;
FT_Pos lsb_delta;
FT_Pos rsb_delta;
void* other;
FT_Slot_Internal internal;
} FT_GlyphSlotRec;
/*************************************************************************/
/*************************************************************************/
/* */
/* F U N C T I O N S */
/* */
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* @function:
* FT_Init_FreeType
*
* @description:
* Initialize a new FreeType library object. The set of modules that are
* registered by this function is determined at build time.
*
* @output:
* alibrary ::
* A handle to a new library object.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* In case you want to provide your own memory allocating routines, use
* @FT_New_Library instead, followed by a call to @FT_Add_Default_Modules
* (or a series of calls to @FT_Add_Module) and
* @FT_Set_Default_Properties.
*
* See the documentation of @FT_Library and @FT_Face for multi-threading
* issues.
*
* If you need reference-counting (cf. @FT_Reference_Library), use
* @FT_New_Library and @FT_Done_Library.
*
* If compilation option `FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES` is
* set, this function reads the `FREETYPE_PROPERTIES` environment
* variable to control driver properties. See section @properties for
* more.
*/
FT_EXPORT( FT_Error )
FT_Init_FreeType( FT_Library *alibrary );
/**************************************************************************
*
* @function:
* FT_Done_FreeType
*
* @description:
* Destroy a given FreeType library object and all of its children,
* including resources, drivers, faces, sizes, etc.
*
* @input:
* library ::
* A handle to the target library object.
*
* @return:
* FreeType error code. 0~means success.
*/
FT_EXPORT( FT_Error )
FT_Done_FreeType( FT_Library library );
/**************************************************************************
*
* @enum:
* FT_OPEN_XXX
*
* @description:
* A list of bit field constants used within the `flags` field of the
* @FT_Open_Args structure.
*
* @values:
* FT_OPEN_MEMORY ::
* This is a memory-based stream.
*
* FT_OPEN_STREAM ::
* Copy the stream from the `stream` field.
*
* FT_OPEN_PATHNAME ::
* Create a new input stream from a C~path name.
*
* FT_OPEN_DRIVER ::
* Use the `driver` field.
*
* FT_OPEN_PARAMS ::
* Use the `num_params` and `params` fields.
*
* @note:
* The `FT_OPEN_MEMORY`, `FT_OPEN_STREAM`, and `FT_OPEN_PATHNAME` flags
* are mutually exclusive.
*/
#define FT_OPEN_MEMORY 0x1
#define FT_OPEN_STREAM 0x2
#define FT_OPEN_PATHNAME 0x4
#define FT_OPEN_DRIVER 0x8
#define FT_OPEN_PARAMS 0x10
/* these constants are deprecated; use the corresponding `FT_OPEN_XXX` */
/* values instead */
#define ft_open_memory FT_OPEN_MEMORY
#define ft_open_stream FT_OPEN_STREAM
#define ft_open_pathname FT_OPEN_PATHNAME
#define ft_open_driver FT_OPEN_DRIVER
#define ft_open_params FT_OPEN_PARAMS
/**************************************************************************
*
* @struct:
* FT_Parameter
*
* @description:
* A simple structure to pass more or less generic parameters to
* @FT_Open_Face and @FT_Face_Properties.
*
* @fields:
* tag ::
* A four-byte identification tag.
*
* data ::
* A pointer to the parameter data.
*
* @note:
* The ID and function of parameters are driver-specific. See section
* @parameter_tags for more information.
*/
typedef struct FT_Parameter_
{
FT_ULong tag;
FT_Pointer data;
} FT_Parameter;
/**************************************************************************
*
* @struct:
* FT_Open_Args
*
* @description:
* A structure to indicate how to open a new font file or stream. A
* pointer to such a structure can be used as a parameter for the
* functions @FT_Open_Face and @FT_Attach_Stream.
*
* @fields:
* flags ::
* A set of bit flags indicating how to use the structure.
*
* memory_base ::
* The first byte of the file in memory.
*
* memory_size ::
* The size in bytes of the file in memory.
*
* pathname ::
* A pointer to an 8-bit file pathname.
*
* stream ::
* A handle to a source stream object.
*
* driver ::
* This field is exclusively used by @FT_Open_Face; it simply specifies
* the font driver to use for opening the face. If set to `NULL`,
* FreeType tries to load the face with each one of the drivers in its
* list.
*
* num_params ::
* The number of extra parameters.
*
* params ::
* Extra parameters passed to the font driver when opening a new face.
*
* @note:
* The stream type is determined by the contents of `flags` that are
* tested in the following order by @FT_Open_Face:
*
* If the @FT_OPEN_MEMORY bit is set, assume that this is a memory file
* of `memory_size` bytes, located at `memory_address`. The data are not
* copied, and the client is responsible for releasing and destroying
* them _after_ the corresponding call to @FT_Done_Face.
*
* Otherwise, if the @FT_OPEN_STREAM bit is set, assume that a custom
* input stream `stream` is used.
*
* Otherwise, if the @FT_OPEN_PATHNAME bit is set, assume that this is a
* normal file and use `pathname` to open it.
*
* If the @FT_OPEN_DRIVER bit is set, @FT_Open_Face only tries to open
* the file with the driver whose handler is in `driver`.
*
* If the @FT_OPEN_PARAMS bit is set, the parameters given by
* `num_params` and `params` is used. They are ignored otherwise.
*
* Ideally, both the `pathname` and `params` fields should be tagged as
* 'const'; this is missing for API backward compatibility. In other
* words, applications should treat them as read-only.
*/
typedef struct FT_Open_Args_
{
FT_UInt flags;
const FT_Byte* memory_base;
FT_Long memory_size;
FT_String* pathname;
FT_Stream stream;
FT_Module driver;
FT_Int num_params;
FT_Parameter* params;
} FT_Open_Args;
/**************************************************************************
*
* @function:
* FT_New_Face
*
* @description:
* Call @FT_Open_Face to open a font by its pathname.
*
* @inout:
* library ::
* A handle to the library resource.
*
* @input:
* pathname ::
* A path to the font file.
*
* face_index ::
* See @FT_Open_Face for a detailed description of this parameter.
*
* @output:
* aface ::
* A handle to a new face object. If `face_index` is greater than or
* equal to zero, it must be non-`NULL`.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* Use @FT_Done_Face to destroy the created @FT_Face object (along with
* its slot and sizes).
*/
FT_EXPORT( FT_Error )
FT_New_Face( FT_Library library,
const char* filepathname,
FT_Long face_index,
FT_Face *aface );
/**************************************************************************
*
* @function:
* FT_New_Memory_Face
*
* @description:
* Call @FT_Open_Face to open a font that has been loaded into memory.
*
* @inout:
* library ::
* A handle to the library resource.
*
* @input:
* file_base ::
* A pointer to the beginning of the font data.
*
* file_size ::
* The size of the memory chunk used by the font data.
*
* face_index ::
* See @FT_Open_Face for a detailed description of this parameter.
*
* @output:
* aface ::
* A handle to a new face object. If `face_index` is greater than or
* equal to zero, it must be non-`NULL`.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* You must not deallocate the memory before calling @FT_Done_Face.
*/
FT_EXPORT( FT_Error )
FT_New_Memory_Face( FT_Library library,
const FT_Byte* file_base,
FT_Long file_size,
FT_Long face_index,
FT_Face *aface );
/**************************************************************************
*
* @function:
* FT_Open_Face
*
* @description:
* Create a face object from a given resource described by @FT_Open_Args.
*
* @inout:
* library ::
* A handle to the library resource.
*
* @input:
* args ::
* A pointer to an `FT_Open_Args` structure that must be filled by the
* caller.
*
* face_index ::
* This field holds two different values. Bits 0-15 are the index of
* the face in the font file (starting with value~0). Set it to~0 if
* there is only one face in the font file.
*
* [Since 2.6.1] Bits 16-30 are relevant to GX and OpenType variation
* fonts only, specifying the named instance index for the current face
* index (starting with value~1; value~0 makes FreeType ignore named
* instances). For non-variation fonts, bits 16-30 are ignored.
* Assuming that you want to access the third named instance in face~4,
* `face_index` should be set to 0x00030004. If you want to access
* face~4 without variation handling, simply set `face_index` to
* value~4.
*
* `FT_Open_Face` and its siblings can be used to quickly check whether
* the font format of a given font resource is supported by FreeType.
* In general, if the `face_index` argument is negative, the function's
* return value is~0 if the font format is recognized, or non-zero
* otherwise. The function allocates a more or less empty face handle
* in `*aface` (if `aface` isn't `NULL`); the only two useful fields in
* this special case are `face->num_faces` and `face->style_flags`.
* For any negative value of `face_index`, `face->num_faces` gives the
* number of faces within the font file. For the negative value
* '-(N+1)' (with 'N' a non-negative 16-bit value), bits 16-30 in
* `face->style_flags` give the number of named instances in face 'N'
* if we have a variation font (or zero otherwise). After examination,
* the returned @FT_Face structure should be deallocated with a call to
* @FT_Done_Face.
*
* @output:
* aface ::
* A handle to a new face object. If `face_index` is greater than or
* equal to zero, it must be non-`NULL`.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* Unlike FreeType 1.x, this function automatically creates a glyph slot
* for the face object that can be accessed directly through
* `face->glyph`.
*
* Each new face object created with this function also owns a default
* @FT_Size object, accessible as `face->size`.
*
* One @FT_Library instance can have multiple face objects, this is,
* @FT_Open_Face and its siblings can be called multiple times using the
* same `library` argument.
*
* See the discussion of reference counters in the description of
* @FT_Reference_Face.
*
* @example:
* To loop over all faces, use code similar to the following snippet
* (omitting the error handling).
*
* ```
* ...
* FT_Face face;
* FT_Long i, num_faces;
*
*
* error = FT_Open_Face( library, args, -1, &face );
* if ( error ) { ... }
*
* num_faces = face->num_faces;
* FT_Done_Face( face );
*
* for ( i = 0; i < num_faces; i++ )
* {
* ...
* error = FT_Open_Face( library, args, i, &face );
* ...
* FT_Done_Face( face );
* ...
* }
* ```
*
* To loop over all valid values for `face_index`, use something similar
* to the following snippet, again without error handling. The code
* accesses all faces immediately (thus only a single call of
* `FT_Open_Face` within the do-loop), with and without named instances.
*
* ```
* ...
* FT_Face face;
*
* FT_Long num_faces = 0;
* FT_Long num_instances = 0;
*
* FT_Long face_idx = 0;
* FT_Long instance_idx = 0;
*
*
* do
* {
* FT_Long id = ( instance_idx << 16 ) + face_idx;
*
*
* error = FT_Open_Face( library, args, id, &face );
* if ( error ) { ... }
*
* num_faces = face->num_faces;
* num_instances = face->style_flags >> 16;
*
* ...
*
* FT_Done_Face( face );
*
* if ( instance_idx < num_instances )
* instance_idx++;
* else
* {
* face_idx++;
* instance_idx = 0;
* }
*
* } while ( face_idx < num_faces )
* ```
*/
FT_EXPORT( FT_Error )
FT_Open_Face( FT_Library library,
const FT_Open_Args* args,
FT_Long face_index,
FT_Face *aface );
/**************************************************************************
*
* @function:
* FT_Attach_File
*
* @description:
* Call @FT_Attach_Stream to attach a file.
*
* @inout:
* face ::
* The target face object.
*
* @input:
* filepathname ::
* The pathname.
*
* @return:
* FreeType error code. 0~means success.
*/
FT_EXPORT( FT_Error )
FT_Attach_File( FT_Face face,
const char* filepathname );
/**************************************************************************
*
* @function:
* FT_Attach_Stream
*
* @description:
* 'Attach' data to a face object. Normally, this is used to read
* additional information for the face object. For example, you can
* attach an AFM file that comes with a Type~1 font to get the kerning
* values and other metrics.
*
* @inout:
* face ::
* The target face object.
*
* @input:
* parameters ::
* A pointer to @FT_Open_Args that must be filled by the caller.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* The meaning of the 'attach' (i.e., what really happens when the new
* file is read) is not fixed by FreeType itself. It really depends on
* the font format (and thus the font driver).
*
* Client applications are expected to know what they are doing when
* invoking this function. Most drivers simply do not implement file or
* stream attachments.
*/
FT_EXPORT( FT_Error )
FT_Attach_Stream( FT_Face face,
FT_Open_Args* parameters );
/**************************************************************************
*
* @function:
* FT_Reference_Face
*
* @description:
* A counter gets initialized to~1 at the time an @FT_Face structure is
* created. This function increments the counter. @FT_Done_Face then
* only destroys a face if the counter is~1, otherwise it simply
* decrements the counter.
*
* This function helps in managing life-cycles of structures that
* reference @FT_Face objects.
*
* @input:
* face ::
* A handle to a target face object.
*
* @return:
* FreeType error code. 0~means success.
*
* @since:
* 2.4.2
*/
FT_EXPORT( FT_Error )
FT_Reference_Face( FT_Face face );
/**************************************************************************
*
* @function:
* FT_Done_Face
*
* @description:
* Discard a given face object, as well as all of its child slots and
* sizes.
*
* @input:
* face ::
* A handle to a target face object.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* See the discussion of reference counters in the description of
* @FT_Reference_Face.
*/
FT_EXPORT( FT_Error )
FT_Done_Face( FT_Face face );
/**************************************************************************
*
* @function:
* FT_Select_Size
*
* @description:
* Select a bitmap strike. To be more precise, this function sets the
* scaling factors of the active @FT_Size object in a face so that
* bitmaps from this particular strike are taken by @FT_Load_Glyph and
* friends.
*
* @inout:
* face ::
* A handle to a target face object.
*
* @input:
* strike_index ::
* The index of the bitmap strike in the `available_sizes` field of
* @FT_FaceRec structure.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* For bitmaps embedded in outline fonts it is common that only a subset
* of the available glyphs at a given ppem value is available. FreeType
* silently uses outlines if there is no bitmap for a given glyph index.
*
* For GX and OpenType variation fonts, a bitmap strike makes sense only
* if the default instance is active (this is, no glyph variation takes
* place); otherwise, FreeType simply ignores bitmap strikes. The same
* is true for all named instances that are different from the default
* instance.
*
* Don't use this function if you are using the FreeType cache API.
*/
FT_EXPORT( FT_Error )
FT_Select_Size( FT_Face face,
FT_Int strike_index );
/**************************************************************************
*
* @enum:
* FT_Size_Request_Type
*
* @description:
* An enumeration type that lists the supported size request types, i.e.,
* what input size (in font units) maps to the requested output size (in
* pixels, as computed from the arguments of @FT_Size_Request).
*
* @values:
* FT_SIZE_REQUEST_TYPE_NOMINAL ::
* The nominal size. The `units_per_EM` field of @FT_FaceRec is used
* to determine both scaling values.
*
* This is the standard scaling found in most applications. In
* particular, use this size request type for TrueType fonts if they
* provide optical scaling or something similar. Note, however, that
* `units_per_EM` is a rather abstract value which bears no relation to
* the actual size of the glyphs in a font.
*
* FT_SIZE_REQUEST_TYPE_REAL_DIM ::
* The real dimension. The sum of the `ascender` and (minus of) the
* `descender` fields of @FT_FaceRec is used to determine both scaling
* values.
*
* FT_SIZE_REQUEST_TYPE_BBOX ::
* The font bounding box. The width and height of the `bbox` field of
* @FT_FaceRec are used to determine the horizontal and vertical
* scaling value, respectively.
*
* FT_SIZE_REQUEST_TYPE_CELL ::
* The `max_advance_width` field of @FT_FaceRec is used to determine
* the horizontal scaling value; the vertical scaling value is
* determined the same way as @FT_SIZE_REQUEST_TYPE_REAL_DIM does.
* Finally, both scaling values are set to the smaller one. This type
* is useful if you want to specify the font size for, say, a window of
* a given dimension and 80x24 cells.
*
* FT_SIZE_REQUEST_TYPE_SCALES ::
* Specify the scaling values directly.
*
* @note:
* The above descriptions only apply to scalable formats. For bitmap
* formats, the behaviour is up to the driver.
*
* See the note section of @FT_Size_Metrics if you wonder how size
* requesting relates to scaling values.
*/
typedef enum FT_Size_Request_Type_
{
FT_SIZE_REQUEST_TYPE_NOMINAL,
FT_SIZE_REQUEST_TYPE_REAL_DIM,
FT_SIZE_REQUEST_TYPE_BBOX,
FT_SIZE_REQUEST_TYPE_CELL,
FT_SIZE_REQUEST_TYPE_SCALES,
FT_SIZE_REQUEST_TYPE_MAX
} FT_Size_Request_Type;
/**************************************************************************
*
* @struct:
* FT_Size_RequestRec
*
* @description:
* A structure to model a size request.
*
* @fields:
* type ::
* See @FT_Size_Request_Type.
*
* width ::
* The desired width, given as a 26.6 fractional point value (with 72pt
* = 1in).
*
* height ::
* The desired height, given as a 26.6 fractional point value (with
* 72pt = 1in).
*
* horiResolution ::
* The horizontal resolution (dpi, i.e., pixels per inch). If set to
* zero, `width` is treated as a 26.6 fractional **pixel** value, which
* gets internally rounded to an integer.
*
* vertResolution ::
* The vertical resolution (dpi, i.e., pixels per inch). If set to
* zero, `height` is treated as a 26.6 fractional **pixel** value,
* which gets internally rounded to an integer.
*
* @note:
* If `width` is zero, the horizontal scaling value is set equal to the
* vertical scaling value, and vice versa.
*
* If `type` is `FT_SIZE_REQUEST_TYPE_SCALES`, `width` and `height` are
* interpreted directly as 16.16 fractional scaling values, without any
* further modification, and both `horiResolution` and `vertResolution`
* are ignored.
*/
typedef struct FT_Size_RequestRec_
{
FT_Size_Request_Type type;
FT_Long width;
FT_Long height;
FT_UInt horiResolution;
FT_UInt vertResolution;
} FT_Size_RequestRec;
/**************************************************************************
*
* @struct:
* FT_Size_Request
*
* @description:
* A handle to a size request structure.
*/
typedef struct FT_Size_RequestRec_ *FT_Size_Request;
/**************************************************************************
*
* @function:
* FT_Request_Size
*
* @description:
* Resize the scale of the active @FT_Size object in a face.
*
* @inout:
* face ::
* A handle to a target face object.
*
* @input:
* req ::
* A pointer to a @FT_Size_RequestRec.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* Although drivers may select the bitmap strike matching the request,
* you should not rely on this if you intend to select a particular
* bitmap strike. Use @FT_Select_Size instead in that case.
*
* The relation between the requested size and the resulting glyph size
* is dependent entirely on how the size is defined in the source face.
* The font designer chooses the final size of each glyph relative to
* this size. For more information refer to
* 'https://www.freetype.org/freetype2/docs/glyphs/glyphs-2.html'.
*
* Contrary to @FT_Set_Char_Size, this function doesn't have special code
* to normalize zero-valued widths, heights, or resolutions (which lead
* to errors in most cases).
*
* Don't use this function if you are using the FreeType cache API.
*/
FT_EXPORT( FT_Error )
FT_Request_Size( FT_Face face,
FT_Size_Request req );
/**************************************************************************
*
* @function:
* FT_Set_Char_Size
*
* @description:
* Call @FT_Request_Size to request the nominal size (in points).
*
* @inout:
* face ::
* A handle to a target face object.
*
* @input:
* char_width ::
* The nominal width, in 26.6 fractional points.
*
* char_height ::
* The nominal height, in 26.6 fractional points.
*
* horz_resolution ::
* The horizontal resolution in dpi.
*
* vert_resolution ::
* The vertical resolution in dpi.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* While this function allows fractional points as input values, the
* resulting ppem value for the given resolution is always rounded to the
* nearest integer.
*
* If either the character width or height is zero, it is set equal to
* the other value.
*
* If either the horizontal or vertical resolution is zero, it is set
* equal to the other value.
*
* A character width or height smaller than 1pt is set to 1pt; if both
* resolution values are zero, they are set to 72dpi.
*
* Don't use this function if you are using the FreeType cache API.
*/
FT_EXPORT( FT_Error )
FT_Set_Char_Size( FT_Face face,
FT_F26Dot6 char_width,
FT_F26Dot6 char_height,
FT_UInt horz_resolution,
FT_UInt vert_resolution );
/**************************************************************************
*
* @function:
* FT_Set_Pixel_Sizes
*
* @description:
* Call @FT_Request_Size to request the nominal size (in pixels).
*
* @inout:
* face ::
* A handle to the target face object.
*
* @input:
* pixel_width ::
* The nominal width, in pixels.
*
* pixel_height ::
* The nominal height, in pixels.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* You should not rely on the resulting glyphs matching or being
* constrained to this pixel size. Refer to @FT_Request_Size to
* understand how requested sizes relate to actual sizes.
*
* Don't use this function if you are using the FreeType cache API.
*/
FT_EXPORT( FT_Error )
FT_Set_Pixel_Sizes( FT_Face face,
FT_UInt pixel_width,
FT_UInt pixel_height );
/**************************************************************************
*
* @function:
* FT_Load_Glyph
*
* @description:
* Load a glyph into the glyph slot of a face object.
*
* @inout:
* face ::
* A handle to the target face object where the glyph is loaded.
*
* @input:
* glyph_index ::
* The index of the glyph in the font file. For CID-keyed fonts
* (either in PS or in CFF format) this argument specifies the CID
* value.
*
* load_flags ::
* A flag indicating what to load for this glyph. The @FT_LOAD_XXX
* constants can be used to control the glyph loading process (e.g.,
* whether the outline should be scaled, whether to load bitmaps or
* not, whether to hint the outline, etc).
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* The loaded glyph may be transformed. See @FT_Set_Transform for the
* details.
*
* For subsetted CID-keyed fonts, `FT_Err_Invalid_Argument` is returned
* for invalid CID values (this is, for CID values that don't have a
* corresponding glyph in the font). See the discussion of the
* @FT_FACE_FLAG_CID_KEYED flag for more details.
*
* If you receive `FT_Err_Glyph_Too_Big`, try getting the glyph outline
* at EM size, then scale it manually and fill it as a graphics
* operation.
*/
FT_EXPORT( FT_Error )
FT_Load_Glyph( FT_Face face,
FT_UInt glyph_index,
FT_Int32 load_flags );
/**************************************************************************
*
* @function:
* FT_Load_Char
*
* @description:
* Load a glyph into the glyph slot of a face object, accessed by its
* character code.
*
* @inout:
* face ::
* A handle to a target face object where the glyph is loaded.
*
* @input:
* char_code ::
* The glyph's character code, according to the current charmap used in
* the face.
*
* load_flags ::
* A flag indicating what to load for this glyph. The @FT_LOAD_XXX
* constants can be used to control the glyph loading process (e.g.,
* whether the outline should be scaled, whether to load bitmaps or
* not, whether to hint the outline, etc).
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* This function simply calls @FT_Get_Char_Index and @FT_Load_Glyph.
*
* Many fonts contain glyphs that can't be loaded by this function since
* its glyph indices are not listed in any of the font's charmaps.
*
* If no active cmap is set up (i.e., `face->charmap` is zero), the call
* to @FT_Get_Char_Index is omitted, and the function behaves identically
* to @FT_Load_Glyph.
*/
FT_EXPORT( FT_Error )
FT_Load_Char( FT_Face face,
FT_ULong char_code,
FT_Int32 load_flags );
/**************************************************************************
*
* @enum:
* FT_LOAD_XXX
*
* @description:
* A list of bit field constants for @FT_Load_Glyph to indicate what kind
* of operations to perform during glyph loading.
*
* @values:
* FT_LOAD_DEFAULT ::
* Corresponding to~0, this value is used as the default glyph load
* operation. In this case, the following happens:
*
* 1. FreeType looks for a bitmap for the glyph corresponding to the
* face's current size. If one is found, the function returns. The
* bitmap data can be accessed from the glyph slot (see note below).
*
* 2. If no embedded bitmap is searched for or found, FreeType looks
* for a scalable outline. If one is found, it is loaded from the font
* file, scaled to device pixels, then 'hinted' to the pixel grid in
* order to optimize it. The outline data can be accessed from the
* glyph slot (see note below).
*
* Note that by default the glyph loader doesn't render outlines into
* bitmaps. The following flags are used to modify this default
* behaviour to more specific and useful cases.
*
* FT_LOAD_NO_SCALE ::
* Don't scale the loaded outline glyph but keep it in font units.
*
* This flag implies @FT_LOAD_NO_HINTING and @FT_LOAD_NO_BITMAP, and
* unsets @FT_LOAD_RENDER.
*
* If the font is 'tricky' (see @FT_FACE_FLAG_TRICKY for more), using
* `FT_LOAD_NO_SCALE` usually yields meaningless outlines because the
* subglyphs must be scaled and positioned with hinting instructions.
* This can be solved by loading the font without `FT_LOAD_NO_SCALE`
* and setting the character size to `font->units_per_EM`.
*
* FT_LOAD_NO_HINTING ::
* Disable hinting. This generally generates 'blurrier' bitmap glyphs
* when the glyph are rendered in any of the anti-aliased modes. See
* also the note below.
*
* This flag is implied by @FT_LOAD_NO_SCALE.
*
* FT_LOAD_RENDER ::
* Call @FT_Render_Glyph after the glyph is loaded. By default, the
* glyph is rendered in @FT_RENDER_MODE_NORMAL mode. This can be
* overridden by @FT_LOAD_TARGET_XXX or @FT_LOAD_MONOCHROME.
*
* This flag is unset by @FT_LOAD_NO_SCALE.
*
* FT_LOAD_NO_BITMAP ::
* Ignore bitmap strikes when loading. Bitmap-only fonts ignore this
* flag.
*
* @FT_LOAD_NO_SCALE always sets this flag.
*
* FT_LOAD_VERTICAL_LAYOUT ::
* Load the glyph for vertical text layout. In particular, the
* `advance` value in the @FT_GlyphSlotRec structure is set to the
* `vertAdvance` value of the `metrics` field.
*
* In case @FT_HAS_VERTICAL doesn't return true, you shouldn't use this
* flag currently. Reason is that in this case vertical metrics get
* synthesized, and those values are not always consistent across
* various font formats.
*
* FT_LOAD_FORCE_AUTOHINT ::
* Prefer the auto-hinter over the font's native hinter. See also the
* note below.
*
* FT_LOAD_PEDANTIC ::
* Make the font driver perform pedantic verifications during glyph
* loading and hinting. This is mostly used to detect broken glyphs in
* fonts. By default, FreeType tries to handle broken fonts also.
*
* In particular, errors from the TrueType bytecode engine are not
* passed to the application if this flag is not set; this might result
* in partially hinted or distorted glyphs in case a glyph's bytecode
* is buggy.
*
* FT_LOAD_NO_RECURSE ::
* Don't load composite glyphs recursively. Instead, the font driver
* fills the `num_subglyph` and `subglyphs` values of the glyph slot;
* it also sets `glyph->format` to @FT_GLYPH_FORMAT_COMPOSITE. The
* description of subglyphs can then be accessed with
* @FT_Get_SubGlyph_Info.
*
* Don't use this flag for retrieving metrics information since some
* font drivers only return rudimentary data.
*
* This flag implies @FT_LOAD_NO_SCALE and @FT_LOAD_IGNORE_TRANSFORM.
*
* FT_LOAD_IGNORE_TRANSFORM ::
* Ignore the transform matrix set by @FT_Set_Transform.
*
* FT_LOAD_MONOCHROME ::
* This flag is used with @FT_LOAD_RENDER to indicate that you want to
* render an outline glyph to a 1-bit monochrome bitmap glyph, with
* 8~pixels packed into each byte of the bitmap data.
*
* Note that this has no effect on the hinting algorithm used. You
* should rather use @FT_LOAD_TARGET_MONO so that the
* monochrome-optimized hinting algorithm is used.
*
* FT_LOAD_LINEAR_DESIGN ::
* Keep `linearHoriAdvance` and `linearVertAdvance` fields of
* @FT_GlyphSlotRec in font units. See @FT_GlyphSlotRec for details.
*
* FT_LOAD_NO_AUTOHINT ::
* Disable the auto-hinter. See also the note below.
*
* FT_LOAD_COLOR ::
* Load colored glyphs. There are slight differences depending on the
* font format.
*
* [Since 2.5] Load embedded color bitmap images. The resulting color
* bitmaps, if available, will have the @FT_PIXEL_MODE_BGRA format,
* with pre-multiplied color channels. If the flag is not set and
* color bitmaps are found, they are converted to 256-level gray
* bitmaps, using the @FT_PIXEL_MODE_GRAY format.
*
* [Since 2.10, experimental] If the glyph index contains an entry in
* the face's 'COLR' table with a 'CPAL' palette table (as defined in
* the OpenType specification), make @FT_Render_Glyph provide a default
* blending of the color glyph layers associated with the glyph index,
* using the same bitmap format as embedded color bitmap images. This
* is mainly for convenience; for full control of color layers use
* @FT_Get_Color_Glyph_Layer and FreeType's color functions like
* @FT_Palette_Select instead of setting @FT_LOAD_COLOR for rendering
* so that the client application can handle blending by itself.
*
* FT_LOAD_COMPUTE_METRICS ::
* [Since 2.6.1] Compute glyph metrics from the glyph data, without the
* use of bundled metrics tables (for example, the 'hdmx' table in
* TrueType fonts). This flag is mainly used by font validating or
* font editing applications, which need to ignore, verify, or edit
* those tables.
*
* Currently, this flag is only implemented for TrueType fonts.
*
* FT_LOAD_BITMAP_METRICS_ONLY ::
* [Since 2.7.1] Request loading of the metrics and bitmap image
* information of a (possibly embedded) bitmap glyph without allocating
* or copying the bitmap image data itself. No effect if the target
* glyph is not a bitmap image.
*
* This flag unsets @FT_LOAD_RENDER.
*
* FT_LOAD_CROP_BITMAP ::
* Ignored. Deprecated.
*
* FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH ::
* Ignored. Deprecated.
*
* @note:
* By default, hinting is enabled and the font's native hinter (see
* @FT_FACE_FLAG_HINTER) is preferred over the auto-hinter. You can
* disable hinting by setting @FT_LOAD_NO_HINTING or change the
* precedence by setting @FT_LOAD_FORCE_AUTOHINT. You can also set
* @FT_LOAD_NO_AUTOHINT in case you don't want the auto-hinter to be used
* at all.
*
* See the description of @FT_FACE_FLAG_TRICKY for a special exception
* (affecting only a handful of Asian fonts).
*
* Besides deciding which hinter to use, you can also decide which
* hinting algorithm to use. See @FT_LOAD_TARGET_XXX for details.
*
* Note that the auto-hinter needs a valid Unicode cmap (either a native
* one or synthesized by FreeType) for producing correct results. If a
* font provides an incorrect mapping (for example, assigning the
* character code U+005A, LATIN CAPITAL LETTER~Z, to a glyph depicting a
* mathematical integral sign), the auto-hinter might produce useless
* results.
*
*/
#define FT_LOAD_DEFAULT 0x0
#define FT_LOAD_NO_SCALE ( 1L << 0 )
#define FT_LOAD_NO_HINTING ( 1L << 1 )
#define FT_LOAD_RENDER ( 1L << 2 )
#define FT_LOAD_NO_BITMAP ( 1L << 3 )
#define FT_LOAD_VERTICAL_LAYOUT ( 1L << 4 )
#define FT_LOAD_FORCE_AUTOHINT ( 1L << 5 )
#define FT_LOAD_CROP_BITMAP ( 1L << 6 )
#define FT_LOAD_PEDANTIC ( 1L << 7 )
#define FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH ( 1L << 9 )
#define FT_LOAD_NO_RECURSE ( 1L << 10 )
#define FT_LOAD_IGNORE_TRANSFORM ( 1L << 11 )
#define FT_LOAD_MONOCHROME ( 1L << 12 )
#define FT_LOAD_LINEAR_DESIGN ( 1L << 13 )
#define FT_LOAD_NO_AUTOHINT ( 1L << 15 )
/* Bits 16-19 are used by `FT_LOAD_TARGET_` */
#define FT_LOAD_COLOR ( 1L << 20 )
#define FT_LOAD_COMPUTE_METRICS ( 1L << 21 )
#define FT_LOAD_BITMAP_METRICS_ONLY ( 1L << 22 )
/* */
/* used internally only by certain font drivers */
#define FT_LOAD_ADVANCE_ONLY ( 1L << 8 )
#define FT_LOAD_SBITS_ONLY ( 1L << 14 )
/**************************************************************************
*
* @enum:
* FT_LOAD_TARGET_XXX
*
* @description:
* A list of values to select a specific hinting algorithm for the
* hinter. You should OR one of these values to your `load_flags` when
* calling @FT_Load_Glyph.
*
* Note that a font's native hinters may ignore the hinting algorithm you
* have specified (e.g., the TrueType bytecode interpreter). You can set
* @FT_LOAD_FORCE_AUTOHINT to ensure that the auto-hinter is used.
*
* @values:
* FT_LOAD_TARGET_NORMAL ::
* The default hinting algorithm, optimized for standard gray-level
* rendering. For monochrome output, use @FT_LOAD_TARGET_MONO instead.
*
* FT_LOAD_TARGET_LIGHT ::
* A lighter hinting algorithm for gray-level modes. Many generated
* glyphs are fuzzier but better resemble their original shape. This
* is achieved by snapping glyphs to the pixel grid only vertically
* (Y-axis), as is done by FreeType's new CFF engine or Microsoft's
* ClearType font renderer. This preserves inter-glyph spacing in
* horizontal text. The snapping is done either by the native font
* driver, if the driver itself and the font support it, or by the
* auto-hinter.
*
* Advance widths are rounded to integer values; however, using the
* `lsb_delta` and `rsb_delta` fields of @FT_GlyphSlotRec, it is
* possible to get fractional advance widths for subpixel positioning
* (which is recommended to use).
*
* If configuration option `AF_CONFIG_OPTION_TT_SIZE_METRICS` is
* active, TrueType-like metrics are used to make this mode behave
* similarly as in unpatched FreeType versions between 2.4.6 and 2.7.1
* (inclusive).
*
* FT_LOAD_TARGET_MONO ::
* Strong hinting algorithm that should only be used for monochrome
* output. The result is probably unpleasant if the glyph is rendered
* in non-monochrome modes.
*
* Note that for outline fonts only the TrueType font driver has proper
* monochrome hinting support, provided the TTFs contain hints for B/W
* rendering (which most fonts no longer provide). If these conditions
* are not met it is very likely that you get ugly results at smaller
* sizes.
*
* FT_LOAD_TARGET_LCD ::
* A variant of @FT_LOAD_TARGET_LIGHT optimized for horizontally
* decimated LCD displays.
*
* FT_LOAD_TARGET_LCD_V ::
* A variant of @FT_LOAD_TARGET_NORMAL optimized for vertically
* decimated LCD displays.
*
* @note:
* You should use only _one_ of the `FT_LOAD_TARGET_XXX` values in your
* `load_flags`. They can't be ORed.
*
* If @FT_LOAD_RENDER is also set, the glyph is rendered in the
* corresponding mode (i.e., the mode that matches the used algorithm
* best). An exception is `FT_LOAD_TARGET_MONO` since it implies
* @FT_LOAD_MONOCHROME.
*
* You can use a hinting algorithm that doesn't correspond to the same
* rendering mode. As an example, it is possible to use the 'light'
* hinting algorithm and have the results rendered in horizontal LCD
* pixel mode, with code like
*
* ```
* FT_Load_Glyph( face, glyph_index,
* load_flags | FT_LOAD_TARGET_LIGHT );
*
* FT_Render_Glyph( face->glyph, FT_RENDER_MODE_LCD );
* ```
*
* In general, you should stick with one rendering mode. For example,
* switching between @FT_LOAD_TARGET_NORMAL and @FT_LOAD_TARGET_MONO
* enforces a lot of recomputation for TrueType fonts, which is slow.
* Another reason is caching: Selecting a different mode usually causes
* changes in both the outlines and the rasterized bitmaps; it is thus
* necessary to empty the cache after a mode switch to avoid false hits.
*
*/
#define FT_LOAD_TARGET_( x ) ( (FT_Int32)( (x) & 15 ) << 16 )
#define FT_LOAD_TARGET_NORMAL FT_LOAD_TARGET_( FT_RENDER_MODE_NORMAL )
#define FT_LOAD_TARGET_LIGHT FT_LOAD_TARGET_( FT_RENDER_MODE_LIGHT )
#define FT_LOAD_TARGET_MONO FT_LOAD_TARGET_( FT_RENDER_MODE_MONO )
#define FT_LOAD_TARGET_LCD FT_LOAD_TARGET_( FT_RENDER_MODE_LCD )
#define FT_LOAD_TARGET_LCD_V FT_LOAD_TARGET_( FT_RENDER_MODE_LCD_V )
/**************************************************************************
*
* @macro:
* FT_LOAD_TARGET_MODE
*
* @description:
* Return the @FT_Render_Mode corresponding to a given
* @FT_LOAD_TARGET_XXX value.
*
*/
#define FT_LOAD_TARGET_MODE( x ) ( (FT_Render_Mode)( ( (x) >> 16 ) & 15 ) )
/**************************************************************************
*
* @function:
* FT_Set_Transform
*
* @description:
* Set the transformation that is applied to glyph images when they are
* loaded into a glyph slot through @FT_Load_Glyph.
*
* @inout:
* face ::
* A handle to the source face object.
*
* @input:
* matrix ::
* A pointer to the transformation's 2x2 matrix. Use `NULL` for the
* identity matrix.
* delta ::
* A pointer to the translation vector. Use `NULL` for the null vector.
*
* @note:
* The transformation is only applied to scalable image formats after the
* glyph has been loaded. It means that hinting is unaltered by the
* transformation and is performed on the character size given in the
* last call to @FT_Set_Char_Size or @FT_Set_Pixel_Sizes.
*
* Note that this also transforms the `face.glyph.advance` field, but
* **not** the values in `face.glyph.metrics`.
*/
FT_EXPORT( void )
FT_Set_Transform( FT_Face face,
FT_Matrix* matrix,
FT_Vector* delta );
/**************************************************************************
*
* @enum:
* FT_Render_Mode
*
* @description:
* Render modes supported by FreeType~2. Each mode corresponds to a
* specific type of scanline conversion performed on the outline.
*
* For bitmap fonts and embedded bitmaps the `bitmap->pixel_mode` field
* in the @FT_GlyphSlotRec structure gives the format of the returned
* bitmap.
*
* All modes except @FT_RENDER_MODE_MONO use 256 levels of opacity,
* indicating pixel coverage. Use linear alpha blending and gamma
* correction to correctly render non-monochrome glyph bitmaps onto a
* surface; see @FT_Render_Glyph.
*
* @values:
* FT_RENDER_MODE_NORMAL ::
* Default render mode; it corresponds to 8-bit anti-aliased bitmaps.
*
* FT_RENDER_MODE_LIGHT ::
* This is equivalent to @FT_RENDER_MODE_NORMAL. It is only defined as
* a separate value because render modes are also used indirectly to
* define hinting algorithm selectors. See @FT_LOAD_TARGET_XXX for
* details.
*
* FT_RENDER_MODE_MONO ::
* This mode corresponds to 1-bit bitmaps (with 2~levels of opacity).
*
* FT_RENDER_MODE_LCD ::
* This mode corresponds to horizontal RGB and BGR subpixel displays
* like LCD screens. It produces 8-bit bitmaps that are 3~times the
* width of the original glyph outline in pixels, and which use the
* @FT_PIXEL_MODE_LCD mode.
*
* FT_RENDER_MODE_LCD_V ::
* This mode corresponds to vertical RGB and BGR subpixel displays
* (like PDA screens, rotated LCD displays, etc.). It produces 8-bit
* bitmaps that are 3~times the height of the original glyph outline in
* pixels and use the @FT_PIXEL_MODE_LCD_V mode.
*
* @note:
* Should you define `FT_CONFIG_OPTION_SUBPIXEL_RENDERING` in your
* `ftoption.h`, which enables patented ClearType-style rendering, the
* LCD-optimized glyph bitmaps should be filtered to reduce color fringes
* inherent to this technology. You can either set up LCD filtering with
* @FT_Library_SetLcdFilter or @FT_Face_Properties, or do the filtering
* yourself. The default FreeType LCD rendering technology does not
* require filtering.
*
* The selected render mode only affects vector glyphs of a font.
* Embedded bitmaps often have a different pixel mode like
* @FT_PIXEL_MODE_MONO. You can use @FT_Bitmap_Convert to transform them
* into 8-bit pixmaps.
*/
typedef enum FT_Render_Mode_
{
FT_RENDER_MODE_NORMAL = 0,
FT_RENDER_MODE_LIGHT,
FT_RENDER_MODE_MONO,
FT_RENDER_MODE_LCD,
FT_RENDER_MODE_LCD_V,
FT_RENDER_MODE_MAX
} FT_Render_Mode;
/* these constants are deprecated; use the corresponding */
/* `FT_Render_Mode` values instead */
#define ft_render_mode_normal FT_RENDER_MODE_NORMAL
#define ft_render_mode_mono FT_RENDER_MODE_MONO
/**************************************************************************
*
* @function:
* FT_Render_Glyph
*
* @description:
* Convert a given glyph image to a bitmap. It does so by inspecting the
* glyph image format, finding the relevant renderer, and invoking it.
*
* @inout:
* slot ::
* A handle to the glyph slot containing the image to convert.
*
* @input:
* render_mode ::
* The render mode used to render the glyph image into a bitmap. See
* @FT_Render_Mode for a list of possible values.
*
* If @FT_RENDER_MODE_NORMAL is used, a previous call of @FT_Load_Glyph
* with flag @FT_LOAD_COLOR makes FT_Render_Glyph provide a default
* blending of colored glyph layers associated with the current glyph
* slot (provided the font contains such layers) instead of rendering
* the glyph slot's outline. This is an experimental feature; see
* @FT_LOAD_COLOR for more information.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* To get meaningful results, font scaling values must be set with
* functions like @FT_Set_Char_Size before calling `FT_Render_Glyph`.
*
* When FreeType outputs a bitmap of a glyph, it really outputs an alpha
* coverage map. If a pixel is completely covered by a filled-in
* outline, the bitmap contains 0xFF at that pixel, meaning that
* 0xFF/0xFF fraction of that pixel is covered, meaning the pixel is 100%
* black (or 0% bright). If a pixel is only 50% covered (value 0x80),
* the pixel is made 50% black (50% bright or a middle shade of grey).
* 0% covered means 0% black (100% bright or white).
*
* On high-DPI screens like on smartphones and tablets, the pixels are so
* small that their chance of being completely covered and therefore
* completely black are fairly good. On the low-DPI screens, however,
* the situation is different. The pixels are too large for most of the
* details of a glyph and shades of gray are the norm rather than the
* exception.
*
* This is relevant because all our screens have a second problem: they
* are not linear. 1~+~1 is not~2. Twice the value does not result in
* twice the brightness. When a pixel is only 50% covered, the coverage
* map says 50% black, and this translates to a pixel value of 128 when
* you use 8~bits per channel (0-255). However, this does not translate
* to 50% brightness for that pixel on our sRGB and gamma~2.2 screens.
* Due to their non-linearity, they dwell longer in the darks and only a
* pixel value of about 186 results in 50% brightness -- 128 ends up too
* dark on both bright and dark backgrounds. The net result is that dark
* text looks burnt-out, pixely and blotchy on bright background, bright
* text too frail on dark backgrounds, and colored text on colored
* background (for example, red on green) seems to have dark halos or
* 'dirt' around it. The situation is especially ugly for diagonal stems
* like in 'w' glyph shapes where the quality of FreeType's anti-aliasing
* depends on the correct display of grays. On high-DPI screens where
* smaller, fully black pixels reign supreme, this doesn't matter, but on
* our low-DPI screens with all the gray shades, it does. 0% and 100%
* brightness are the same things in linear and non-linear space, just
* all the shades in-between aren't.
*
* The blending function for placing text over a background is
*
* ```
* dst = alpha * src + (1 - alpha) * dst ,
* ```
*
* which is known as the OVER operator.
*
* To correctly composite an antialiased pixel of a glyph onto a surface,
*
* 1. take the foreground and background colors (e.g., in sRGB space)
* and apply gamma to get them in a linear space,
*
* 2. use OVER to blend the two linear colors using the glyph pixel
* as the alpha value (remember, the glyph bitmap is an alpha coverage
* bitmap), and
*
* 3. apply inverse gamma to the blended pixel and write it back to
* the image.
*
* Internal testing at Adobe found that a target inverse gamma of~1.8 for
* step~3 gives good results across a wide range of displays with an sRGB
* gamma curve or a similar one.
*
* This process can cost performance. There is an approximation that
* does not need to know about the background color; see
* https://bel.fi/alankila/lcd/ and
* https://bel.fi/alankila/lcd/alpcor.html for details.
*
* **ATTENTION**: Linear blending is even more important when dealing
* with subpixel-rendered glyphs to prevent color-fringing! A
* subpixel-rendered glyph must first be filtered with a filter that
* gives equal weight to the three color primaries and does not exceed a
* sum of 0x100, see section @lcd_rendering. Then the only difference to
* gray linear blending is that subpixel-rendered linear blending is done
* 3~times per pixel: red foreground subpixel to red background subpixel
* and so on for green and blue.
*/
FT_EXPORT( FT_Error )
FT_Render_Glyph( FT_GlyphSlot slot,
FT_Render_Mode render_mode );
/**************************************************************************
*
* @enum:
* FT_Kerning_Mode
*
* @description:
* An enumeration to specify the format of kerning values returned by
* @FT_Get_Kerning.
*
* @values:
* FT_KERNING_DEFAULT ::
* Return grid-fitted kerning distances in 26.6 fractional pixels.
*
* FT_KERNING_UNFITTED ::
* Return un-grid-fitted kerning distances in 26.6 fractional pixels.
*
* FT_KERNING_UNSCALED ::
* Return the kerning vector in original font units.
*
* @note:
* `FT_KERNING_DEFAULT` returns full pixel values; it also makes FreeType
* heuristically scale down kerning distances at small ppem values so
* that they don't become too big.
*
* Both `FT_KERNING_DEFAULT` and `FT_KERNING_UNFITTED` use the current
* horizontal scaling factor (as set e.g. with @FT_Set_Char_Size) to
* convert font units to pixels.
*/
typedef enum FT_Kerning_Mode_
{
FT_KERNING_DEFAULT = 0,
FT_KERNING_UNFITTED,
FT_KERNING_UNSCALED
} FT_Kerning_Mode;
/* these constants are deprecated; use the corresponding */
/* `FT_Kerning_Mode` values instead */
#define ft_kerning_default FT_KERNING_DEFAULT
#define ft_kerning_unfitted FT_KERNING_UNFITTED
#define ft_kerning_unscaled FT_KERNING_UNSCALED
/**************************************************************************
*
* @function:
* FT_Get_Kerning
*
* @description:
* Return the kerning vector between two glyphs of the same face.
*
* @input:
* face ::
* A handle to a source face object.
*
* left_glyph ::
* The index of the left glyph in the kern pair.
*
* right_glyph ::
* The index of the right glyph in the kern pair.
*
* kern_mode ::
* See @FT_Kerning_Mode for more information. Determines the scale and
* dimension of the returned kerning vector.
*
* @output:
* akerning ::
* The kerning vector. This is either in font units, fractional pixels
* (26.6 format), or pixels for scalable formats, and in pixels for
* fixed-sizes formats.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* Only horizontal layouts (left-to-right & right-to-left) are supported
* by this method. Other layouts, or more sophisticated kernings, are
* out of the scope of this API function -- they can be implemented
* through format-specific interfaces.
*
* Kerning for OpenType fonts implemented in a 'GPOS' table is not
* supported; use @FT_HAS_KERNING to find out whether a font has data
* that can be extracted with `FT_Get_Kerning`.
*/
FT_EXPORT( FT_Error )
FT_Get_Kerning( FT_Face face,
FT_UInt left_glyph,
FT_UInt right_glyph,
FT_UInt kern_mode,
FT_Vector *akerning );
/**************************************************************************
*
* @function:
* FT_Get_Track_Kerning
*
* @description:
* Return the track kerning for a given face object at a given size.
*
* @input:
* face ::
* A handle to a source face object.
*
* point_size ::
* The point size in 16.16 fractional points.
*
* degree ::
* The degree of tightness. Increasingly negative values represent
* tighter track kerning, while increasingly positive values represent
* looser track kerning. Value zero means no track kerning.
*
* @output:
* akerning ::
* The kerning in 16.16 fractional points, to be uniformly applied
* between all glyphs.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* Currently, only the Type~1 font driver supports track kerning, using
* data from AFM files (if attached with @FT_Attach_File or
* @FT_Attach_Stream).
*
* Only very few AFM files come with track kerning data; please refer to
* Adobe's AFM specification for more details.
*/
FT_EXPORT( FT_Error )
FT_Get_Track_Kerning( FT_Face face,
FT_Fixed point_size,
FT_Int degree,
FT_Fixed* akerning );
/**************************************************************************
*
* @function:
* FT_Get_Glyph_Name
*
* @description:
* Retrieve the ASCII name of a given glyph in a face. This only works
* for those faces where @FT_HAS_GLYPH_NAMES(face) returns~1.
*
* @input:
* face ::
* A handle to a source face object.
*
* glyph_index ::
* The glyph index.
*
* buffer_max ::
* The maximum number of bytes available in the buffer.
*
* @output:
* buffer ::
* A pointer to a target buffer where the name is copied to.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* An error is returned if the face doesn't provide glyph names or if the
* glyph index is invalid. In all cases of failure, the first byte of
* `buffer` is set to~0 to indicate an empty name.
*
* The glyph name is truncated to fit within the buffer if it is too
* long. The returned string is always zero-terminated.
*
* Be aware that FreeType reorders glyph indices internally so that glyph
* index~0 always corresponds to the 'missing glyph' (called '.notdef').
*
* This function always returns an error if the config macro
* `FT_CONFIG_OPTION_NO_GLYPH_NAMES` is not defined in `ftoption.h`.
*/
FT_EXPORT( FT_Error )
FT_Get_Glyph_Name( FT_Face face,
FT_UInt glyph_index,
FT_Pointer buffer,
FT_UInt buffer_max );
/**************************************************************************
*
* @function:
* FT_Get_Postscript_Name
*
* @description:
* Retrieve the ASCII PostScript name of a given face, if available.
* This only works with PostScript, TrueType, and OpenType fonts.
*
* @input:
* face ::
* A handle to the source face object.
*
* @return:
* A pointer to the face's PostScript name. `NULL` if unavailable.
*
* @note:
* The returned pointer is owned by the face and is destroyed with it.
*
* For variation fonts, this string changes if you select a different
* instance, and you have to call `FT_Get_PostScript_Name` again to
* retrieve it. FreeType follows Adobe TechNote #5902, 'Generating
* PostScript Names for Fonts Using OpenType Font Variations'.
*
* https://download.macromedia.com/pub/developer/opentype/tech-notes/5902.AdobePSNameGeneration.html
*
* [Since 2.9] Special PostScript names for named instances are only
* returned if the named instance is set with @FT_Set_Named_Instance (and
* the font has corresponding entries in its 'fvar' table). If
* @FT_IS_VARIATION returns true, the algorithmically derived PostScript
* name is provided, not looking up special entries for named instances.
*/
FT_EXPORT( const char* )
FT_Get_Postscript_Name( FT_Face face );
/**************************************************************************
*
* @function:
* FT_Select_Charmap
*
* @description:
* Select a given charmap by its encoding tag (as listed in
* `freetype.h`).
*
* @inout:
* face ::
* A handle to the source face object.
*
* @input:
* encoding ::
* A handle to the selected encoding.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* This function returns an error if no charmap in the face corresponds
* to the encoding queried here.
*
* Because many fonts contain more than a single cmap for Unicode
* encoding, this function has some special code to select the one that
* covers Unicode best ('best' in the sense that a UCS-4 cmap is
* preferred to a UCS-2 cmap). It is thus preferable to @FT_Set_Charmap
* in this case.
*/
FT_EXPORT( FT_Error )
FT_Select_Charmap( FT_Face face,
FT_Encoding encoding );
/**************************************************************************
*
* @function:
* FT_Set_Charmap
*
* @description:
* Select a given charmap for character code to glyph index mapping.
*
* @inout:
* face ::
* A handle to the source face object.
*
* @input:
* charmap ::
* A handle to the selected charmap.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* This function returns an error if the charmap is not part of the face
* (i.e., if it is not listed in the `face->charmaps` table).
*
* It also fails if an OpenType type~14 charmap is selected (which
* doesn't map character codes to glyph indices at all).
*/
FT_EXPORT( FT_Error )
FT_Set_Charmap( FT_Face face,
FT_CharMap charmap );
/**************************************************************************
*
* @function:
* FT_Get_Charmap_Index
*
* @description:
* Retrieve index of a given charmap.
*
* @input:
* charmap ::
* A handle to a charmap.
*
* @return:
* The index into the array of character maps within the face to which
* `charmap` belongs. If an error occurs, -1 is returned.
*
*/
FT_EXPORT( FT_Int )
FT_Get_Charmap_Index( FT_CharMap charmap );
/**************************************************************************
*
* @function:
* FT_Get_Char_Index
*
* @description:
* Return the glyph index of a given character code. This function uses
* the currently selected charmap to do the mapping.
*
* @input:
* face ::
* A handle to the source face object.
*
* charcode ::
* The character code.
*
* @return:
* The glyph index. 0~means 'undefined character code'.
*
* @note:
* If you use FreeType to manipulate the contents of font files directly,
* be aware that the glyph index returned by this function doesn't always
* correspond to the internal indices used within the file. This is done
* to ensure that value~0 always corresponds to the 'missing glyph'. If
* the first glyph is not named '.notdef', then for Type~1 and Type~42
* fonts, '.notdef' will be moved into the glyph ID~0 position, and
* whatever was there will be moved to the position '.notdef' had. For
* Type~1 fonts, if there is no '.notdef' glyph at all, then one will be
* created at index~0 and whatever was there will be moved to the last
* index -- Type~42 fonts are considered invalid under this condition.
*/
FT_EXPORT( FT_UInt )
FT_Get_Char_Index( FT_Face face,
FT_ULong charcode );
/**************************************************************************
*
* @function:
* FT_Get_First_Char
*
* @description:
* Return the first character code in the current charmap of a given
* face, together with its corresponding glyph index.
*
* @input:
* face ::
* A handle to the source face object.
*
* @output:
* agindex ::
* Glyph index of first character code. 0~if charmap is empty.
*
* @return:
* The charmap's first character code.
*
* @note:
* You should use this function together with @FT_Get_Next_Char to parse
* all character codes available in a given charmap. The code should
* look like this:
*
* ```
* FT_ULong charcode;
* FT_UInt gindex;
*
*
* charcode = FT_Get_First_Char( face, &gindex );
* while ( gindex != 0 )
* {
* ... do something with (charcode,gindex) pair ...
*
* charcode = FT_Get_Next_Char( face, charcode, &gindex );
* }
* ```
*
* Be aware that character codes can have values up to 0xFFFFFFFF; this
* might happen for non-Unicode or malformed cmaps. However, even with
* regular Unicode encoding, so-called 'last resort fonts' (using SFNT
* cmap format 13, see function @FT_Get_CMap_Format) normally have
* entries for all Unicode characters up to 0x1FFFFF, which can cause *a
* lot* of iterations.
*
* Note that `*agindex` is set to~0 if the charmap is empty. The result
* itself can be~0 in two cases: if the charmap is empty or if the
* value~0 is the first valid character code.
*/
FT_EXPORT( FT_ULong )
FT_Get_First_Char( FT_Face face,
FT_UInt *agindex );
/**************************************************************************
*
* @function:
* FT_Get_Next_Char
*
* @description:
* Return the next character code in the current charmap of a given face
* following the value `char_code`, as well as the corresponding glyph
* index.
*
* @input:
* face ::
* A handle to the source face object.
*
* char_code ::
* The starting character code.
*
* @output:
* agindex ::
* Glyph index of next character code. 0~if charmap is empty.
*
* @return:
* The charmap's next character code.
*
* @note:
* You should use this function with @FT_Get_First_Char to walk over all
* character codes available in a given charmap. See the note for that
* function for a simple code example.
*
* Note that `*agindex` is set to~0 when there are no more codes in the
* charmap.
*/
FT_EXPORT( FT_ULong )
FT_Get_Next_Char( FT_Face face,
FT_ULong char_code,
FT_UInt *agindex );
/**************************************************************************
*
* @function:
* FT_Face_Properties
*
* @description:
* Set or override certain (library or module-wide) properties on a
* face-by-face basis. Useful for finer-grained control and avoiding
* locks on shared structures (threads can modify their own faces as they
* see fit).
*
* Contrary to @FT_Property_Set, this function uses @FT_Parameter so that
* you can pass multiple properties to the target face in one call. Note
* that only a subset of the available properties can be controlled.
*
* * @FT_PARAM_TAG_STEM_DARKENING (stem darkening, corresponding to the
* property `no-stem-darkening` provided by the 'autofit', 'cff',
* 'type1', and 't1cid' modules; see @no-stem-darkening).
*
* * @FT_PARAM_TAG_LCD_FILTER_WEIGHTS (LCD filter weights, corresponding
* to function @FT_Library_SetLcdFilterWeights).
*
* * @FT_PARAM_TAG_RANDOM_SEED (seed value for the CFF, Type~1, and CID
* 'random' operator, corresponding to the `random-seed` property
* provided by the 'cff', 'type1', and 't1cid' modules; see
* @random-seed).
*
* Pass `NULL` as `data` in @FT_Parameter for a given tag to reset the
* option and use the library or module default again.
*
* @input:
* face ::
* A handle to the source face object.
*
* num_properties ::
* The number of properties that follow.
*
* properties ::
* A handle to an @FT_Parameter array with `num_properties` elements.
*
* @return:
* FreeType error code. 0~means success.
*
* @example:
* Here is an example that sets three properties. You must define
* `FT_CONFIG_OPTION_SUBPIXEL_RENDERING` to make the LCD filter examples
* work.
*
* ```
* FT_Parameter property1;
* FT_Bool darken_stems = 1;
*
* FT_Parameter property2;
* FT_LcdFiveTapFilter custom_weight =
* { 0x11, 0x44, 0x56, 0x44, 0x11 };
*
* FT_Parameter property3;
* FT_Int32 random_seed = 314159265;
*
* FT_Parameter properties[3] = { property1,
* property2,
* property3 };
*
*
* property1.tag = FT_PARAM_TAG_STEM_DARKENING;
* property1.data = &darken_stems;
*
* property2.tag = FT_PARAM_TAG_LCD_FILTER_WEIGHTS;
* property2.data = custom_weight;
*
* property3.tag = FT_PARAM_TAG_RANDOM_SEED;
* property3.data = &random_seed;
*
* FT_Face_Properties( face, 3, properties );
* ```
*
* The next example resets a single property to its default value.
*
* ```
* FT_Parameter property;
*
*
* property.tag = FT_PARAM_TAG_LCD_FILTER_WEIGHTS;
* property.data = NULL;
*
* FT_Face_Properties( face, 1, &property );
* ```
*
* @since:
* 2.8
*
*/
FT_EXPORT( FT_Error )
FT_Face_Properties( FT_Face face,
FT_UInt num_properties,
FT_Parameter* properties );
/**************************************************************************
*
* @function:
* FT_Get_Name_Index
*
* @description:
* Return the glyph index of a given glyph name.
*
* @input:
* face ::
* A handle to the source face object.
*
* glyph_name ::
* The glyph name.
*
* @return:
* The glyph index. 0~means 'undefined character code'.
*/
FT_EXPORT( FT_UInt )
FT_Get_Name_Index( FT_Face face,
const FT_String* glyph_name );
/**************************************************************************
*
* @enum:
* FT_SUBGLYPH_FLAG_XXX
*
* @description:
* A list of constants describing subglyphs. Please refer to the 'glyf'
* table description in the OpenType specification for the meaning of the
* various flags (which get synthesized for non-OpenType subglyphs).
*
* https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#composite-glyph-description
*
* @values:
* FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS ::
* FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES ::
* FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID ::
* FT_SUBGLYPH_FLAG_SCALE ::
* FT_SUBGLYPH_FLAG_XY_SCALE ::
* FT_SUBGLYPH_FLAG_2X2 ::
* FT_SUBGLYPH_FLAG_USE_MY_METRICS ::
*
*/
#define FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS 1
#define FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES 2
#define FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID 4
#define FT_SUBGLYPH_FLAG_SCALE 8
#define FT_SUBGLYPH_FLAG_XY_SCALE 0x40
#define FT_SUBGLYPH_FLAG_2X2 0x80
#define FT_SUBGLYPH_FLAG_USE_MY_METRICS 0x200
/**************************************************************************
*
* @function:
* FT_Get_SubGlyph_Info
*
* @description:
* Retrieve a description of a given subglyph. Only use it if
* `glyph->format` is @FT_GLYPH_FORMAT_COMPOSITE; an error is returned
* otherwise.
*
* @input:
* glyph ::
* The source glyph slot.
*
* sub_index ::
* The index of the subglyph. Must be less than
* `glyph->num_subglyphs`.
*
* @output:
* p_index ::
* The glyph index of the subglyph.
*
* p_flags ::
* The subglyph flags, see @FT_SUBGLYPH_FLAG_XXX.
*
* p_arg1 ::
* The subglyph's first argument (if any).
*
* p_arg2 ::
* The subglyph's second argument (if any).
*
* p_transform ::
* The subglyph transformation (if any).
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* The values of `*p_arg1`, `*p_arg2`, and `*p_transform` must be
* interpreted depending on the flags returned in `*p_flags`. See the
* OpenType specification for details.
*
* https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#composite-glyph-description
*
*/
FT_EXPORT( FT_Error )
FT_Get_SubGlyph_Info( FT_GlyphSlot glyph,
FT_UInt sub_index,
FT_Int *p_index,
FT_UInt *p_flags,
FT_Int *p_arg1,
FT_Int *p_arg2,
FT_Matrix *p_transform );
/**************************************************************************
*
* @section:
* layer_management
*
* @title:
* Glyph Layer Management
*
* @abstract:
* Retrieving and manipulating OpenType's 'COLR' table data.
*
* @description:
* The functions described here allow access of colored glyph layer data
* in OpenType's 'COLR' tables.
*/
/**************************************************************************
*
* @struct:
* FT_LayerIterator
*
* @description:
* This iterator object is needed for @FT_Get_Color_Glyph_Layer.
*
* @fields:
* num_layers ::
* The number of glyph layers for the requested glyph index. Will be
* set by @FT_Get_Color_Glyph_Layer.
*
* layer ::
* The current layer. Will be set by @FT_Get_Color_Glyph_Layer.
*
* p ::
* An opaque pointer into 'COLR' table data. The caller must set this
* to `NULL` before the first call of @FT_Get_Color_Glyph_Layer.
*/
typedef struct FT_LayerIterator_
{
FT_UInt num_layers;
FT_UInt layer;
FT_Byte* p;
} FT_LayerIterator;
/**************************************************************************
*
* @function:
* FT_Get_Color_Glyph_Layer
*
* @description:
* This is an interface to the 'COLR' table in OpenType fonts to
* iteratively retrieve the colored glyph layers associated with the
* current glyph slot.
*
* https://docs.microsoft.com/en-us/typography/opentype/spec/colr
*
* The glyph layer data for a given glyph index, if present, provides an
* alternative, multi-colour glyph representation: Instead of rendering
* the outline or bitmap with the given glyph index, glyphs with the
* indices and colors returned by this function are rendered layer by
* layer.
*
* The returned elements are ordered in the z~direction from bottom to
* top; the 'n'th element should be rendered with the associated palette
* color and blended on top of the already rendered layers (elements 0,
* 1, ..., n-1).
*
* @input:
* face ::
* A handle to the parent face object.
*
* base_glyph ::
* The glyph index the colored glyph layers are associated with.
*
* @inout:
* iterator ::
* An @FT_LayerIterator object. For the first call you should set
* `iterator->p` to `NULL`. For all following calls, simply use the
* same object again.
*
* @output:
* aglyph_index ::
* The glyph index of the current layer.
*
* acolor_index ::
* The color index into the font face's color palette of the current
* layer. The value 0xFFFF is special; it doesn't reference a palette
* entry but indicates that the text foreground color should be used
* instead (to be set up by the application outside of FreeType).
*
* The color palette can be retrieved with @FT_Palette_Select.
*
* @return:
* Value~1 if everything is OK. If there are no more layers (or if there
* are no layers at all), value~0 gets returned. In case of an error,
* value~0 is returned also.
*
* @note:
* This function is necessary if you want to handle glyph layers by
* yourself. In particular, functions that operate with @FT_GlyphRec
* objects (like @FT_Get_Glyph or @FT_Glyph_To_Bitmap) don't have access
* to this information.
*
* Note that @FT_Render_Glyph is able to handle colored glyph layers
* automatically if the @FT_LOAD_COLOR flag is passed to a previous call
* to @FT_Load_Glyph. [This is an experimental feature.]
*
* @example:
* ```
* FT_Color* palette;
* FT_LayerIterator iterator;
*
* FT_Bool have_layers;
* FT_UInt layer_glyph_index;
* FT_UInt layer_color_index;
*
*
* error = FT_Palette_Select( face, palette_index, &palette );
* if ( error )
* palette = NULL;
*
* iterator.p = NULL;
* have_layers = FT_Get_Color_Glyph_Layer( face,
* glyph_index,
* &layer_glyph_index,
* &layer_color_index,
* &iterator );
*
* if ( palette && have_layers )
* {
* do
* {
* FT_Color layer_color;
*
*
* if ( layer_color_index == 0xFFFF )
* layer_color = text_foreground_color;
* else
* layer_color = palette[layer_color_index];
*
* // Load and render glyph `layer_glyph_index', then
* // blend resulting pixmap (using color `layer_color')
* // with previously created pixmaps.
*
* } while ( FT_Get_Color_Glyph_Layer( face,
* glyph_index,
* &layer_glyph_index,
* &layer_color_index,
* &iterator ) );
* }
* ```
*/
FT_EXPORT( FT_Bool )
FT_Get_Color_Glyph_Layer( FT_Face face,
FT_UInt base_glyph,
FT_UInt *aglyph_index,
FT_UInt *acolor_index,
FT_LayerIterator* iterator );
/**************************************************************************
*
* @section:
* base_interface
*
*/
/**************************************************************************
*
* @enum:
* FT_FSTYPE_XXX
*
* @description:
* A list of bit flags used in the `fsType` field of the OS/2 table in a
* TrueType or OpenType font and the `FSType` entry in a PostScript font.
* These bit flags are returned by @FT_Get_FSType_Flags; they inform
* client applications of embedding and subsetting restrictions
* associated with a font.
*
* See
* https://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/FontPolicies.pdf
* for more details.
*
* @values:
* FT_FSTYPE_INSTALLABLE_EMBEDDING ::
* Fonts with no fsType bit set may be embedded and permanently
* installed on the remote system by an application.
*
* FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING ::
* Fonts that have only this bit set must not be modified, embedded or
* exchanged in any manner without first obtaining permission of the
* font software copyright owner.
*
* FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING ::
* The font may be embedded and temporarily loaded on the remote
* system. Documents containing Preview & Print fonts must be opened
* 'read-only'; no edits can be applied to the document.
*
* FT_FSTYPE_EDITABLE_EMBEDDING ::
* The font may be embedded but must only be installed temporarily on
* other systems. In contrast to Preview & Print fonts, documents
* containing editable fonts may be opened for reading, editing is
* permitted, and changes may be saved.
*
* FT_FSTYPE_NO_SUBSETTING ::
* The font may not be subsetted prior to embedding.
*
* FT_FSTYPE_BITMAP_EMBEDDING_ONLY ::
* Only bitmaps contained in the font may be embedded; no outline data
* may be embedded. If there are no bitmaps available in the font,
* then the font is unembeddable.
*
* @note:
* The flags are ORed together, thus more than a single value can be
* returned.
*
* While the `fsType` flags can indicate that a font may be embedded, a
* license with the font vendor may be separately required to use the
* font in this way.
*/
#define FT_FSTYPE_INSTALLABLE_EMBEDDING 0x0000
#define FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING 0x0002
#define FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING 0x0004
#define FT_FSTYPE_EDITABLE_EMBEDDING 0x0008
#define FT_FSTYPE_NO_SUBSETTING 0x0100
#define FT_FSTYPE_BITMAP_EMBEDDING_ONLY 0x0200
/**************************************************************************
*
* @function:
* FT_Get_FSType_Flags
*
* @description:
* Return the `fsType` flags for a font.
*
* @input:
* face ::
* A handle to the source face object.
*
* @return:
* The `fsType` flags, see @FT_FSTYPE_XXX.
*
* @note:
* Use this function rather than directly reading the `fs_type` field in
* the @PS_FontInfoRec structure, which is only guaranteed to return the
* correct results for Type~1 fonts.
*
* @since:
* 2.3.8
*/
FT_EXPORT( FT_UShort )
FT_Get_FSType_Flags( FT_Face face );
/**************************************************************************
*
* @section:
* glyph_variants
*
* @title:
* Unicode Variation Sequences
*
* @abstract:
* The FreeType~2 interface to Unicode Variation Sequences (UVS), using
* the SFNT cmap format~14.
*
* @description:
* Many characters, especially for CJK scripts, have variant forms. They
* are a sort of grey area somewhere between being totally irrelevant and
* semantically distinct; for this reason, the Unicode consortium decided
* to introduce Variation Sequences (VS), consisting of a Unicode base
* character and a variation selector instead of further extending the
* already huge number of characters.
*
* Unicode maintains two different sets, namely 'Standardized Variation
* Sequences' and registered 'Ideographic Variation Sequences' (IVS),
* collected in the 'Ideographic Variation Database' (IVD).
*
* https://unicode.org/Public/UCD/latest/ucd/StandardizedVariants.txt
* https://unicode.org/reports/tr37/ https://unicode.org/ivd/
*
* To date (January 2017), the character with the most ideographic
* variations is U+9089, having 32 such IVS.
*
* Three Mongolian Variation Selectors have the values U+180B-U+180D; 256
* generic Variation Selectors are encoded in the ranges U+FE00-U+FE0F
* and U+E0100-U+E01EF. IVS currently use Variation Selectors from the
* range U+E0100-U+E01EF only.
*
* A VS consists of the base character value followed by a single
* Variation Selector. For example, to get the first variation of
* U+9089, you have to write the character sequence `U+9089 U+E0100`.
*
* Adobe and MS decided to support both standardized and ideographic VS
* with a new cmap subtable (format~14). It is an odd subtable because
* it is not a mapping of input code points to glyphs, but contains lists
* of all variations supported by the font.
*
* A variation may be either 'default' or 'non-default' for a given font.
* A default variation is the one you will get for that code point if you
* look it up in the standard Unicode cmap. A non-default variation is a
* different glyph.
*
*/
/**************************************************************************
*
* @function:
* FT_Face_GetCharVariantIndex
*
* @description:
* Return the glyph index of a given character code as modified by the
* variation selector.
*
* @input:
* face ::
* A handle to the source face object.
*
* charcode ::
* The character code point in Unicode.
*
* variantSelector ::
* The Unicode code point of the variation selector.
*
* @return:
* The glyph index. 0~means either 'undefined character code', or
* 'undefined selector code', or 'no variation selector cmap subtable',
* or 'current CharMap is not Unicode'.
*
* @note:
* If you use FreeType to manipulate the contents of font files directly,
* be aware that the glyph index returned by this function doesn't always
* correspond to the internal indices used within the file. This is done
* to ensure that value~0 always corresponds to the 'missing glyph'.
*
* This function is only meaningful if
* a) the font has a variation selector cmap sub table, and
* b) the current charmap has a Unicode encoding.
*
* @since:
* 2.3.6
*/
FT_EXPORT( FT_UInt )
FT_Face_GetCharVariantIndex( FT_Face face,
FT_ULong charcode,
FT_ULong variantSelector );
/**************************************************************************
*
* @function:
* FT_Face_GetCharVariantIsDefault
*
* @description:
* Check whether this variation of this Unicode character is the one to
* be found in the charmap.
*
* @input:
* face ::
* A handle to the source face object.
*
* charcode ::
* The character codepoint in Unicode.
*
* variantSelector ::
* The Unicode codepoint of the variation selector.
*
* @return:
* 1~if found in the standard (Unicode) cmap, 0~if found in the variation
* selector cmap, or -1 if it is not a variation.
*
* @note:
* This function is only meaningful if the font has a variation selector
* cmap subtable.
*
* @since:
* 2.3.6
*/
FT_EXPORT( FT_Int )
FT_Face_GetCharVariantIsDefault( FT_Face face,
FT_ULong charcode,
FT_ULong variantSelector );
/**************************************************************************
*
* @function:
* FT_Face_GetVariantSelectors
*
* @description:
* Return a zero-terminated list of Unicode variation selectors found in
* the font.
*
* @input:
* face ::
* A handle to the source face object.
*
* @return:
* A pointer to an array of selector code points, or `NULL` if there is
* no valid variation selector cmap subtable.
*
* @note:
* The last item in the array is~0; the array is owned by the @FT_Face
* object but can be overwritten or released on the next call to a
* FreeType function.
*
* @since:
* 2.3.6
*/
FT_EXPORT( FT_UInt32* )
FT_Face_GetVariantSelectors( FT_Face face );
/**************************************************************************
*
* @function:
* FT_Face_GetVariantsOfChar
*
* @description:
* Return a zero-terminated list of Unicode variation selectors found for
* the specified character code.
*
* @input:
* face ::
* A handle to the source face object.
*
* charcode ::
* The character codepoint in Unicode.
*
* @return:
* A pointer to an array of variation selector code points that are
* active for the given character, or `NULL` if the corresponding list is
* empty.
*
* @note:
* The last item in the array is~0; the array is owned by the @FT_Face
* object but can be overwritten or released on the next call to a
* FreeType function.
*
* @since:
* 2.3.6
*/
FT_EXPORT( FT_UInt32* )
FT_Face_GetVariantsOfChar( FT_Face face,
FT_ULong charcode );
/**************************************************************************
*
* @function:
* FT_Face_GetCharsOfVariant
*
* @description:
* Return a zero-terminated list of Unicode character codes found for the
* specified variation selector.
*
* @input:
* face ::
* A handle to the source face object.
*
* variantSelector ::
* The variation selector code point in Unicode.
*
* @return:
* A list of all the code points that are specified by this selector
* (both default and non-default codes are returned) or `NULL` if there
* is no valid cmap or the variation selector is invalid.
*
* @note:
* The last item in the array is~0; the array is owned by the @FT_Face
* object but can be overwritten or released on the next call to a
* FreeType function.
*
* @since:
* 2.3.6
*/
FT_EXPORT( FT_UInt32* )
FT_Face_GetCharsOfVariant( FT_Face face,
FT_ULong variantSelector );
/**************************************************************************
*
* @section:
* computations
*
* @title:
* Computations
*
* @abstract:
* Crunching fixed numbers and vectors.
*
* @description:
* This section contains various functions used to perform computations
* on 16.16 fixed-float numbers or 2d vectors.
*
* **Attention**: Most arithmetic functions take `FT_Long` as arguments.
* For historical reasons, FreeType was designed under the assumption
* that `FT_Long` is a 32-bit integer; results can thus be undefined if
* the arguments don't fit into 32 bits.
*
* @order:
* FT_MulDiv
* FT_MulFix
* FT_DivFix
* FT_RoundFix
* FT_CeilFix
* FT_FloorFix
* FT_Vector_Transform
* FT_Matrix_Multiply
* FT_Matrix_Invert
*
*/
/**************************************************************************
*
* @function:
* FT_MulDiv
*
* @description:
* Compute `(a*b)/c` with maximum accuracy, using a 64-bit intermediate
* integer whenever necessary.
*
* This function isn't necessarily as fast as some processor-specific
* operations, but is at least completely portable.
*
* @input:
* a ::
* The first multiplier.
*
* b ::
* The second multiplier.
*
* c ::
* The divisor.
*
* @return:
* The result of `(a*b)/c`. This function never traps when trying to
* divide by zero; it simply returns 'MaxInt' or 'MinInt' depending on
* the signs of `a` and `b`.
*/
FT_EXPORT( FT_Long )
FT_MulDiv( FT_Long a,
FT_Long b,
FT_Long c );
/**************************************************************************
*
* @function:
* FT_MulFix
*
* @description:
* Compute `(a*b)/0x10000` with maximum accuracy. Its main use is to
* multiply a given value by a 16.16 fixed-point factor.
*
* @input:
* a ::
* The first multiplier.
*
* b ::
* The second multiplier. Use a 16.16 factor here whenever possible
* (see note below).
*
* @return:
* The result of `(a*b)/0x10000`.
*
* @note:
* This function has been optimized for the case where the absolute value
* of `a` is less than 2048, and `b` is a 16.16 scaling factor. As this
* happens mainly when scaling from notional units to fractional pixels
* in FreeType, it resulted in noticeable speed improvements between
* versions 2.x and 1.x.
*
* As a conclusion, always try to place a 16.16 factor as the _second_
* argument of this function; this can make a great difference.
*/
FT_EXPORT( FT_Long )
FT_MulFix( FT_Long a,
FT_Long b );
/**************************************************************************
*
* @function:
* FT_DivFix
*
* @description:
* Compute `(a*0x10000)/b` with maximum accuracy. Its main use is to
* divide a given value by a 16.16 fixed-point factor.
*
* @input:
* a ::
* The numerator.
*
* b ::
* The denominator. Use a 16.16 factor here.
*
* @return:
* The result of `(a*0x10000)/b`.
*/
FT_EXPORT( FT_Long )
FT_DivFix( FT_Long a,
FT_Long b );
/**************************************************************************
*
* @function:
* FT_RoundFix
*
* @description:
* Round a 16.16 fixed number.
*
* @input:
* a ::
* The number to be rounded.
*
* @return:
* `a` rounded to the nearest 16.16 fixed integer, halfway cases away
* from zero.
*
* @note:
* The function uses wrap-around arithmetic.
*/
FT_EXPORT( FT_Fixed )
FT_RoundFix( FT_Fixed a );
/**************************************************************************
*
* @function:
* FT_CeilFix
*
* @description:
* Compute the smallest following integer of a 16.16 fixed number.
*
* @input:
* a ::
* The number for which the ceiling function is to be computed.
*
* @return:
* `a` rounded towards plus infinity.
*
* @note:
* The function uses wrap-around arithmetic.
*/
FT_EXPORT( FT_Fixed )
FT_CeilFix( FT_Fixed a );
/**************************************************************************
*
* @function:
* FT_FloorFix
*
* @description:
* Compute the largest previous integer of a 16.16 fixed number.
*
* @input:
* a ::
* The number for which the floor function is to be computed.
*
* @return:
* `a` rounded towards minus infinity.
*/
FT_EXPORT( FT_Fixed )
FT_FloorFix( FT_Fixed a );
/**************************************************************************
*
* @function:
* FT_Vector_Transform
*
* @description:
* Transform a single vector through a 2x2 matrix.
*
* @inout:
* vector ::
* The target vector to transform.
*
* @input:
* matrix ::
* A pointer to the source 2x2 matrix.
*
* @note:
* The result is undefined if either `vector` or `matrix` is invalid.
*/
FT_EXPORT( void )
FT_Vector_Transform( FT_Vector* vector,
const FT_Matrix* matrix );
/**************************************************************************
*
* @section:
* version
*
* @title:
* FreeType Version
*
* @abstract:
* Functions and macros related to FreeType versions.
*
* @description:
* Note that those functions and macros are of limited use because even a
* new release of FreeType with only documentation changes increases the
* version number.
*
* @order:
* FT_Library_Version
*
* FREETYPE_MAJOR
* FREETYPE_MINOR
* FREETYPE_PATCH
*
* FT_Face_CheckTrueTypePatents
* FT_Face_SetUnpatentedHinting
*
*/
/**************************************************************************
*
* @enum:
* FREETYPE_XXX
*
* @description:
* These three macros identify the FreeType source code version. Use
* @FT_Library_Version to access them at runtime.
*
* @values:
* FREETYPE_MAJOR ::
* The major version number.
* FREETYPE_MINOR ::
* The minor version number.
* FREETYPE_PATCH ::
* The patch level.
*
* @note:
* The version number of FreeType if built as a dynamic link library with
* the 'libtool' package is _not_ controlled by these three macros.
*
*/
#define FREETYPE_MAJOR 2
#define FREETYPE_MINOR 10
#define FREETYPE_PATCH 0
/**************************************************************************
*
* @function:
* FT_Library_Version
*
* @description:
* Return the version of the FreeType library being used. This is useful
* when dynamically linking to the library, since one cannot use the
* macros @FREETYPE_MAJOR, @FREETYPE_MINOR, and @FREETYPE_PATCH.
*
* @input:
* library ::
* A source library handle.
*
* @output:
* amajor ::
* The major version number.
*
* aminor ::
* The minor version number.
*
* apatch ::
* The patch version number.
*
* @note:
* The reason why this function takes a `library` argument is because
* certain programs implement library initialization in a custom way that
* doesn't use @FT_Init_FreeType.
*
* In such cases, the library version might not be available before the
* library object has been created.
*/
FT_EXPORT( void )
FT_Library_Version( FT_Library library,
FT_Int *amajor,
FT_Int *aminor,
FT_Int *apatch );
/**************************************************************************
*
* @function:
* FT_Face_CheckTrueTypePatents
*
* @description:
* Deprecated, does nothing.
*
* @input:
* face ::
* A face handle.
*
* @return:
* Always returns false.
*
* @note:
* Since May 2010, TrueType hinting is no longer patented.
*
* @since:
* 2.3.5
*/
FT_EXPORT( FT_Bool )
FT_Face_CheckTrueTypePatents( FT_Face face );
/**************************************************************************
*
* @function:
* FT_Face_SetUnpatentedHinting
*
* @description:
* Deprecated, does nothing.
*
* @input:
* face ::
* A face handle.
*
* value ::
* New boolean setting.
*
* @return:
* Always returns false.
*
* @note:
* Since May 2010, TrueType hinting is no longer patented.
*
* @since:
* 2.3.5
*/
FT_EXPORT( FT_Bool )
FT_Face_SetUnpatentedHinting( FT_Face face,
FT_Bool value );
/* */
FT_END_HEADER
#endif /* FREETYPE_H_ */
/* END */
| bsd-2-clause |
tescalada/npyscreen-restructure | auto-doc/npyscreen.autocomplete.TitleFilename-class.html | 11511 | <?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>npyscreen.autocomplete.TitleFilename</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="npyscreen-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<th class="navbar" width="100%"></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="npyscreen-module.html">Package npyscreen</a> ::
<a href="npyscreen.autocomplete-module.html">Module autocomplete</a> ::
Class TitleFilename
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="npyscreen.autocomplete.TitleFilename-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class TitleFilename</h1><span class="codelink"><a href="npyscreen.autocomplete-pysrc.html#TitleFilename">source code</a></span><br /><br />
<pre class="base-tree">
object --+
|
<a href="npyscreen.widget.InputHandler-class.html">widget.InputHandler</a> --+
|
<a href="npyscreen.widget.Widget-class.html">widget.Widget</a> --+
|
<a href="npyscreen.titlefield.TitleText-class.html">titlefield.TitleText</a> --+
|
<strong class="uidshort">TitleFilename</strong>
</pre>
<hr />
<!-- ==================== NESTED CLASSES ==================== -->
<a name="section-NestedClasses"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Nested Classes</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-NestedClasses"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr class="private">
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="npyscreen.autocomplete.Filename-class.html" class="summary-name">_entry_type</a>
</td>
</tr>
</table>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="npyscreen.titlefield.TitleText-class.html">titlefield.TitleText</a></code></b>:
<code><a href="npyscreen.titlefield.TitleText-class.html#__init__">__init__</a></code>,
<code><a href="npyscreen.titlefield.TitleText-class.html#del_value">del_value</a></code>,
<code><a href="npyscreen.titlefield.TitleText-class.html#edit">edit</a></code>,
<code><a href="npyscreen.titlefield.TitleText-class.html#get_value">get_value</a></code>,
<code><a href="npyscreen.titlefield.TitleText-class.html#recalculate_size">recalculate_size</a></code>,
<code><a href="npyscreen.titlefield.TitleText-class.html#set_value">set_value</a></code>,
<code><a href="npyscreen.titlefield.TitleText-class.html#update">update</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="npyscreen.widget.Widget-class.html">widget.Widget</a></code></b>:
<code><a href="npyscreen.widget.Widget-class.html#calculate_area_needed">calculate_area_needed</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#clear">clear</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#destroy">destroy</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#display">display</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#get_and_use_key_press">get_and_use_key_press</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#get_editable">get_editable</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#safe_filter">safe_filter</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#safe_string">safe_string</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#set_editable">set_editable</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#set_size">set_size</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#space_available">space_available</a></code>,
<code><a href="npyscreen.widget.Widget-class.html#try_adjust_widgets">try_adjust_widgets</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="npyscreen.widget.InputHandler-class.html">widget.InputHandler</a></code></b>:
<code><a href="npyscreen.widget.InputHandler-class.html#add_complex_handlers">add_complex_handlers</a></code>,
<code><a href="npyscreen.widget.InputHandler-class.html#add_handlers">add_handlers</a></code>,
<code><a href="npyscreen.widget.InputHandler-class.html#h_exit_down">h_exit_down</a></code>,
<code><a href="npyscreen.widget.InputHandler-class.html#h_exit_escape">h_exit_escape</a></code>,
<code><a href="npyscreen.widget.InputHandler-class.html#h_exit_left">h_exit_left</a></code>,
<code><a href="npyscreen.widget.InputHandler-class.html#h_exit_right">h_exit_right</a></code>,
<code><a href="npyscreen.widget.InputHandler-class.html#h_exit_up">h_exit_up</a></code>,
<code><a href="npyscreen.widget.InputHandler-class.html#handle_input">handle_input</a></code>,
<code><a href="npyscreen.widget.InputHandler-class.html#set_up_handlers">set_up_handlers</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__delattr__</code>,
<code>__getattribute__</code>,
<code>__hash__</code>,
<code>__new__</code>,
<code>__reduce__</code>,
<code>__reduce_ex__</code>,
<code>__repr__</code>,
<code>__setattr__</code>,
<code>__str__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== CLASS VARIABLES ==================== -->
<a name="section-ClassVariables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Class Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-ClassVariables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="npyscreen.titlefield.TitleText-class.html">titlefield.TitleText</a></code></b>:
<code><a href="npyscreen.titlefield.TitleText-class.html#value">value</a></code>
</p>
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="npyscreen-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<th class="navbar" width="100%"></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0beta1 on Thu Mar 29 15:58:54 2007
</td>
<td align="right" class="footer">
<a href="http://epydoc.sourceforge.net">http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie()
// -->
</script>
</body>
</html>
| bsd-2-clause |
teddym6/TricSqlLoad | TricSQlLoad/TricSqlLoad/src/com/tvh/tricsql/test/load/ParameterizedMultiThreadedRunner.java | 4620 | package com.tvh.tricsql.test.load;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Suite;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerScheduler;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestClass;
import com.tvh.tricsql.test.load.util.GlobalSettings;
import com.tvh.tricsql.test.load.util.TestDataLoader;
public class ParameterizedMultiThreadedRunner extends Suite {
protected class ParametrizedRunner extends BlockJUnit4ClassRunner {
private final int fParameterSetNumber;
private final List<Object[]> fParameterList;
public ParametrizedRunner(Class<?> type,
List<Object[]> parameterList, int i) throws InitializationError {
super(type);
fParameterList= parameterList;
fParameterSetNumber= i;
}
@Override
public Object createTest() throws Exception {
return getTestClass().getOnlyConstructor().newInstance(
computeParams());
}
private Object[] computeParams() throws Exception {
try {
return fParameterList.get(fParameterSetNumber);
} catch (ClassCastException e) {
throw new Exception(String.format(
"%s.%s() must return a Collection of arrays.",
getTestClass().getName(), getParametersMethod(
getTestClass()).getName()));
}
}
@Override
protected String getName() {
return String.format("Tets number [%s] and parameters:[%s] ", fParameterSetNumber,
( !(fParameterList.get(fParameterSetNumber) == null)
&& !(fParameterList.get(fParameterSetNumber).length == 0) ) ?
fParameterList.get(fParameterSetNumber)[0].toString() : "");
}
@Override
protected String testName(final FrameworkMethod method) {
return String.format("%s[%s]", method.getName(),
fParameterSetNumber);
}
@Override
protected void validateConstructor(List<Throwable> errors) {
validateOnlyOneConstructor(errors);
}
@Override
protected Statement classBlock(RunNotifier notifier) {
return childrenInvoker(notifier);
}
}
private final ArrayList<Runner> runners= new ArrayList<Runner>();
/**
* Only called reflectively. Do not use programmatically.
*/
public ParameterizedMultiThreadedRunner(Class<?> klass) throws Throwable {
super(klass, Collections.<Runner>emptyList());
final List<Object[]> parametersList= getParametersList(getTestClass());
for (int i= 0; i < parametersList.size(); i++) {
ParametrizedRunner runner = new ParametrizedRunner(getTestClass().getJavaClass(),
parametersList, i);
runners.add(runner);
}
boolean runInParallel = Boolean.valueOf(
TestDataLoader.getInstance().getSetting(GlobalSettings.RUN_IN_PARALLEL));
if (runInParallel) {
setScheduler(new RunnerScheduler() {
private final ExecutorService fService = Executors.newFixedThreadPool(parametersList.size());
@Override
public void schedule(Runnable childStatement) {
fService.submit(childStatement);
}
@Override
public void finished() {
try {
fService.shutdown();
fService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
}
@Override
protected List<Runner> getChildren() {
return runners;
}
@SuppressWarnings("unchecked")
private List<Object[]> getParametersList(TestClass klass)
throws Throwable {
return (List<Object[]>) getParametersMethod(klass).invokeExplosively(
null);
}
private FrameworkMethod getParametersMethod(TestClass testClass)
throws Exception {
List<FrameworkMethod> methods= testClass
.getAnnotatedMethods(Parameters.class);
for (FrameworkMethod each : methods) {
int modifiers= each.getMethod().getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
return each;
}
throw new Exception("No public static parameters method on class "
+ testClass.getName());
}
}
| bsd-2-clause |
editor700/esocks | src/utils.h | 900 | /*
* Copyright (c) editor700
* (c) 2015 <[email protected]>
*/
#ifndef _utils_h_
#define _utils_h_
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#define TRUE ((uchar)'\x01')
#define FALSE ((uchar)'\x00')
#ifdef SOCKS5
char *socks5_login, *socks5_password;
#endif
int clients;
typedef unsigned char bool;
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
char *pname, *logfile;
bool output, daem;
uchar ptype;
int max_clients;
void perr(const char*, ...); // print error then exit
void msg(const char*, ...); // logging
/* standart functions */
inline uchar *strcatd(uchar*, uchar*, int, int);
inline bool in_str(uchar*, uchar, int);
#endif
| bsd-2-clause |
Devronium/ConceptApplicationServer | modules/standard.lib.cbor/src/cbor/internal/builder_callbacks.h | 1991 | /*
* Copyright (c) 2014-2017 Pavel Kalvoda <[email protected]>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_BUILDER_CALLBACKS_H
#define LIBCBOR_BUILDER_CALLBACKS_H
#include "cbor/common.h"
#include "../callbacks.h"
#include "stack.h"
#ifdef __cplusplus
extern "C" {
#endif
/** High-level decoding context */
struct _cbor_decoder_context {
/** Callback creating the last item has failed */
bool creation_failed;
/** Stack expectation mismatch */
bool syntax_error;
cbor_item_t *root;
struct _cbor_stack *stack;
};
void cbor_builder_uint8_callback(void *, uint8_t);
void cbor_builder_uint16_callback(void *, uint16_t);
void cbor_builder_uint32_callback(void *, uint32_t);
void cbor_builder_uint64_callback(void *, uint64_t);
void cbor_builder_negint8_callback(void *, uint8_t);
void cbor_builder_negint16_callback(void *, uint16_t);
void cbor_builder_negint32_callback(void *, uint32_t);
void cbor_builder_negint64_callback(void *, uint64_t);
void cbor_builder_string_callback(void *, cbor_data, size_t);
void cbor_builder_string_start_callback(void *);
void cbor_builder_byte_string_callback(void *, cbor_data, size_t);
void cbor_builder_byte_string_start_callback(void *);
void cbor_builder_array_start_callback(void *, size_t);
void cbor_builder_indef_array_start_callback(void *);
void cbor_builder_map_start_callback(void *, size_t);
void cbor_builder_indef_map_start_callback(void *);
void cbor_builder_tag_callback(void *, uint64_t);
void cbor_builder_float2_callback(void *, float);
void cbor_builder_float4_callback(void *, float);
void cbor_builder_float8_callback(void *, double);
void cbor_builder_null_callback(void *);
void cbor_builder_undefined_callback(void *);
void cbor_builder_boolean_callback(void *, bool);
void cbor_builder_indef_break_callback(void *);
#ifdef __cplusplus
}
#endif
#endif //LIBCBOR_BUILDER_CALLBACKS_H
| bsd-2-clause |
faiverson/JNP | README.md | 1051 | # JNP Plugin
## What is this for?
JNP jQuery Notification Plugin for Twitter Bootstrap is a plugin built in jQuery for use in your website if you need notifications messages. There are several configuration to make yor own notification or use a pre render.
## Quick start
Add bootstrap library (js and css) from here: http://twitter.github.com/bootstrap/ <br />
Add jQuery library from here: http://jquery.com/download/
Add the plugin jquery.notification
Initializate the plugin: <code>$('body').JNP();</code>
That is it!
## Features
* You can set a position where the plugin is showed using an element as a wrapper or a default position at the top/bottom or a lightbox effect.
* You can choose triggered using a element.
* You can choose render automatically or use a delay.
* You can choose to use your own css, the default css or the bootstrap styles.
* You can choose make it dissapear after a while.
## More Information
If you need more information, you can find the documentation and examples on the website <br />http://www.jnp-plugin.com.ar | bsd-2-clause |
vikingosegundo/EmailChecker | EmailValidation/EmailValidation/Validator.h | 450 | //
// Validator.h
// EmailValidation
//
// Created by Manuel Meyer on 16.07.14.
// Copyright (c) 2014 vs. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol Validator <NSObject>
-(BOOL)isValidAddress:(NSString *)address;
@end
@interface Validator : NSObject<Validator>
@property (nonatomic, copy) BOOL (^validatorBlock)(NSString *email);
-(instancetype)initWithValidationBlock:(BOOL(^)(NSString *email))validatorBlock;
@end | bsd-2-clause |
godspeed1989/WDUtils | tiamoPCI/source/pci.struct.h | 19627 | //********************************************************************
// created: 22:7:2008 12:04
// file: pci.struct.h
// author: tiamo
// purpose: struct
//********************************************************************
#pragma once
#include <pshpack1.h>
//
// ide controller progif
//
typedef union _PCI_NATIVE_IDE_CONTROLLER_PROGIF
{
struct
{
//
// primary state
//
UCHAR PrimaryState : 1;
//
// primary switchable
//
UCHAR PrimarySwitchable : 1;
//
// secondary state
//
UCHAR SecondaryState : 1;
//
// secondary switchable
//
UCHAR SecondarySwitchable : 1;
//
// reserved
//
UCHAR Reserved : 4;
};
//
// progif
//
UCHAR ProgIf;
}PCI_NATIVE_IDE_CONTROLLER_PROGIF,*PPCI_NATIVE_IDE_CONTROLLER_PROGIF;
//
// pci irq routing table header
//
typedef struct _PCI_IRQ_ROUTING_TABLE_HEAD
{
//
// signature = $PIR
//
ULONG Signature;
//
// version
//
USHORT Version;
//
// size
//
USHORT Size;
//
// router bus
//
UCHAR RouterBus;
//
// route dev func
//
UCHAR RouterDevFunc;
//
// exclusive irqs
//
USHORT ExclusiveIRQs;
//
// Compatible PCI Interrupt Router
//
ULONG CompatiblePCIInterruptRouter;
//
// Miniport Data
//
ULONG MiniportData;
//
// reserved
//
UCHAR Reserved[11];
//
// checksum
//
UCHAR Checksum;
}PCI_IRQ_ROUTING_TABLE_HEAD,*PPCI_IRQ_ROUTING_TABLE_HEAD;
//
// irq routine table entry
//
typedef struct _PCI_IRQ_ROUTING_TABLE_ENTRY
{
//
// bus
//
UCHAR BusNumber;
//
// reserved
//
UCHAR Reserved : 3;
//
// device
//
UCHAR DeviceNumber : 5;
//
// link and bitmap
//
struct
{
//
// link
//
UCHAR Link;
//
// bitmap
//
USHORT Bitmap;
}LinkBitmap[4];
//
// slot
//
UCHAR SlotNumber;
//
// reserved
//
UCHAR Reserved2;
}PCI_IRQ_ROUTING_TABLE_ENTRY,*PPCI_IRQ_ROUTING_TABLE_ENTRY;
//
// rom header
//
typedef struct _PCI_ROM_HEADER
{
//
// signature
//
USHORT Signature;
//
// reserved
//
UCHAR Reserved[0x16];
//
// pci date ptr
//
USHORT PciDataPtr;
}PCI_ROM_HEADER,*PPCI_ROM_HEADER;
//
// pci data structor
//
typedef struct _PCI_ROM_DATA_HEADER
{
//
// signature
//
ULONG Signature;
//
// vendor id
//
USHORT VendorId;
//
// device id
//
USHORT DeviceId;
//
// vpd
//
USHORT VpdPtr;
//
// length
//
USHORT Length;
//
// revision
//
UCHAR Revision;
//
// class code
//
UCHAR ClassCode[3];
//
// image length
//
USHORT ImageLength;
//
// data revision
//
USHORT CodeDataRevisionLevel;
//
// code type
//
UCHAR CodeType;
//
// indicator
//
UCHAR Indicator;
//
// reserved
//
USHORT Reserved;
}PCI_ROM_DATA_HEADER,*PPCI_ROM_DATA_HEADER;
#include <poppack.h>
//
// id buffer
//
typedef struct _PCI_ID_BUFFER
{
//
// count
//
ULONG Count;
//
// ansi string
//
ANSI_STRING AnsiString[8];
//
// unicode string size
//
USHORT UnicodeStringSize[8];
//
// total length
//
USHORT TotalLength;
//
// buffer
//
PCHAR CurrentBuffer;
//
// storage
//
CHAR StorageBuffer[0x100];
}PCI_ID_BUFFER,*PPCI_ID_BUFFER;
//
// pci hack table entry
//
typedef struct _PCI_HACK_TABLE_ENTRY
{
//
// vendor id
//
USHORT VendorId;
//
// device id
//
USHORT DeviceId;
//
// sub vendor id
//
USHORT SubVendorId;
//
// sub system id
//
USHORT SubSystemId;
//
// revision id
//
UCHAR RevisionId;
//
// sub system and sub vendor id is valid
//
UCHAR SubSystemVendorIdValid:1;
//
// revision is valid
//
UCHAR RevisionIdValid:1;
//
// reserved for padding
//
UCHAR Reserved0:6;
//
// hack flags
//
ULONGLONG HackFlags;
}PCI_HACK_TABLE_ENTRY,*PPCI_HACK_TABLE_ENTRY;
//
// debug port
//
typedef struct _PCI_DEBUG_PORT
{
//
// bus
//
ULONG Bus;
//
// slot number
//
PCI_SLOT_NUMBER SlotNumber;
}PCI_DEBUG_PORT,*PPCI_DEBUG_PORT;
//
// minor dispatch table
//
typedef struct _PCI_MN_DISPATCH_TABLE
{
//
// style
//
PCI_DISPATCH_STYLE DispatchStyle;
//
// dispatch routine
//
PCI_DISPATCH_ROUTINE DispatchFunction;
}PCI_MN_DISPATCH_TABLE,*PPCI_MN_DISPATCH_TABLE;
//
// major dispatch table
//
typedef struct _PCI_MJ_DISPATCH_TABLE
{
//
// pnp max function
//
ULONG PnpIrpMaximumMinorFunction;
//
// pnp dispatch table
//
PPCI_MN_DISPATCH_TABLE PnpIrpDispatchTable;
//
// power max function
//
ULONG PowerIrpMaximumMinorFunction;
//
// power dispatch table
//
PPCI_MN_DISPATCH_TABLE PowerIrpDispatchTable;
//
// system control style
//
PCI_DISPATCH_STYLE SystemControlIrpDispatchStyle;
//
// system control dispatch routine
//
PCI_DISPATCH_ROUTINE SystemControlIrpDispatchFunction;
//
// other sytle
//
PCI_DISPATCH_STYLE OtherIrpDispatchStyle;
//
// other dispatch routine
//
PCI_DISPATCH_ROUTINE OtherIrpDispatchFunction;
}PCI_MJ_DISPATCH_TABLE,*PPCI_MJ_DISPATCH_TABLE;
//
// power state
//
typedef struct _PCI_POWER_STATE
{
//
// current system state
//
SYSTEM_POWER_STATE CurrentSystemState;
//
// current device state
//
DEVICE_POWER_STATE CurrentDeviceState;
//
// system wake level
//
SYSTEM_POWER_STATE SystemWakeLevel;
//
// device wake level
//
DEVICE_POWER_STATE DeviceWakeLevel;
//
// map system state to device state
//
DEVICE_POWER_STATE SystemStateMapping[POWER_SYSTEM_MAXIMUM];
//
// wait wake irp
//
PIRP WaitWakeIrp;
//
// saved cancel routine
//
PDRIVER_CANCEL SavedCancelRoutine;
//
// paging count
//
LONG Paging;
//
// hibernate count
//
LONG Hibernate;
//
// crash dump count
//
LONG CrashDump;
}PCI_POWER_STATE,*PPCI_POWER_STATE;
//
// pci lock
//
typedef struct _PCI_LOCK
{
//
// spinlock
//
KSPIN_LOCK SpinLock;
//
// saved irql
//
KIRQL OldIrql;
//
// file
//
PCHAR File;
//
// line
//
ULONG Line;
}PCI_LOCK,*PPCI_LOCK;
//
// hotplug
//
typedef struct _PCI_HOTPLUG_PARAMETERS
{
//
// acquired
//
BOOLEAN Acquired;
//
// cache line size
//
UCHAR CacheLineSize;
//
// latency timer
//
UCHAR LatencyTimer;
//
// enable PERR
//
BOOLEAN EnablePERR;
//
// enable SERR
//
BOOLEAN EnableSERR;
}PCI_HOTPLUG_PARAMETERS,*PPCI_HOTPLUG_PARAMETERS;
//
// function resource
//
typedef struct _PCI_FUNCTION_RESOURCES
{
//
// limit
//
IO_RESOURCE_DESCRIPTOR Limit[7];
//
// current
//
CM_PARTIAL_RESOURCE_DESCRIPTOR Current[7];
}PCI_FUNCTION_RESOURCES,*PPCI_FUNCTION_RESOURCES;
//
// header
//
typedef union _PCI_HEADER_TYPE_DEPENDENT
{
//
// device type
//
struct
{
UCHAR Spare[4];
}type0;
//
// pci-to-pci bridge
//
struct
{
//
// primary bus
//
UCHAR PrimaryBus;
//
// sencodary bus
//
UCHAR SecondaryBus;
//
// subordinate bus
//
UCHAR SubordinateBus;
//
// subtractive decode
//
UCHAR SubtractiveDecode : 1;
//
// isa
//
UCHAR IsaBitSet : 1;
//
// vga
//
UCHAR VgaBitSet : 1;
//
// bus number changed
//
UCHAR WeChangedBusNumbers : 1;
//
// require isa
//
UCHAR IsaBitRequired : 1;
//
// pading
//
UCHAR Padding : 3;
}type1;
struct
{
//
// primary bus
//
UCHAR PrimaryBus;
//
// sencodary bus
//
UCHAR SecondaryBus;
//
// subordinate bus
//
UCHAR SubordinateBus;
//
// subtractive decode
//
UCHAR SubtractiveDecode : 1;
//
// isa
//
UCHAR IsaBitSet : 1;
//
// vga
//
UCHAR VgaBitSet : 1;
//
// bus number changed
//
UCHAR WeChangedBusNumbers : 1;
//
// require isa
//
UCHAR IsaBitRequired : 1;
//
// pading
//
UCHAR Padding : 3;
}type2;
}PCI_HEADER_TYPE_DEPENDENT,*PPCI_HEADER_TYPE_DEPENDENT;
//
// common extension
//
typedef struct _PCI_COMMON_EXTENSION
{
//
// next
//
SINGLE_LIST_ENTRY ListEntry;
//
// signature
//
PCI_SIGNATURE ExtensionType;
//
// irp dispatch table
//
PPCI_MJ_DISPATCH_TABLE IrpDispatchTable;
//
// device state
//
PCI_DEVICE_STATE DeviceState;
//
// next state
//
PCI_DEVICE_STATE TentativeNextState;
//
// secondary extension lock
//
KEVENT SecondaryExtLock;
}PCI_COMMON_EXTENSION,*PPCI_COMMON_EXTENSION;
//
// fdo extension
//
typedef struct _PCI_FDO_EXTENSION
{
//
// common header
//
PCI_COMMON_EXTENSION Common;
//
// physical device object
//
PDEVICE_OBJECT PhysicalDeviceObject;
//
// function device object
//
PDEVICE_OBJECT FunctionalDeviceObject;
//
// attached device object
//
PDEVICE_OBJECT AttachedDeviceObject;
//
// child list lock
//
KEVENT ChildListLock;
//
// child pdo list
//
SINGLE_LIST_ENTRY ChildPdoList;
//
// bus root fdo extension
//
struct _PCI_FDO_EXTENSION* BusRootFdoExtension;
//
// parent fdo extension
//
struct _PCI_FDO_EXTENSION* ParentFdoExtension;
//
// child bridge pdo list
//
struct _PCI_PDO_EXTENSION* ChildBridgePdoList;
//
// pci bus interface
//
PPCI_BUS_INTERFACE_STANDARD PciBusInterface;
//
// max subordinate bus
//
UCHAR MaxSubordinateBus;
//
// bus handler
//
PBUS_HANDLER BusHandler;
//
// base bus
//
UCHAR BaseBus;
//
// fake
//
BOOLEAN Fake;
//
// child delete
//
BOOLEAN ChildDelete;
//
// scaned
//
BOOLEAN Scanned;
//
// arbiter initialized
//
BOOLEAN ArbitersInitialized;
//
// broken video hack applied
//
BOOLEAN BrokenVideoHackApplied;
//
// hibernated
//
BOOLEAN Hibernated;
//
// power state
//
PCI_POWER_STATE PowerState;
//
// secondary extension
//
SINGLE_LIST_ENTRY SecondaryExtension;
//
// wait wake count
//
LONG ChildWaitWakeCount;
//
// preserved config
//
PPCI_COMMON_CONFIG PreservedConfig;
//
// pci lock
//
PCI_LOCK Lock;
//
// hotplug parameters
//
PCI_HOTPLUG_PARAMETERS HotPlugParameters;
//
// bus hack flags
//
ULONG BusHackFlags;
}PCI_FDO_EXTENSION,*PPCI_FDO_EXTENSION;
//
// pdo extension
//
typedef struct _PCI_PDO_EXTENSION
{
//
// common
//
PCI_COMMON_EXTENSION Common;
//
// slot
//
PCI_SLOT_NUMBER Slot;
//
// physical device object
//
PDEVICE_OBJECT PhysicalDeviceObject;
//
// parent fdo extension
//
PPCI_FDO_EXTENSION ParentFdoExtension;
//
// secondary extension
//
SINGLE_LIST_ENTRY SecondaryExtension;
//
// bus interface reference count
//
LONG BusInterfaceReferenceCount;
//
// agp interface reference count
//
LONG AgpInterfaceReferenceCount;
//
// vendor id
//
USHORT VendorId;
//
// device id
//
USHORT DeviceId;
//
// sub system id
//
USHORT SubSystemId;
//
// sub vendor id
//
USHORT SubVendorId;
//
// revision id
//
UCHAR RevisionId;
//
// prog if
//
UCHAR ProgIf;
//
// sub class
//
UCHAR SubClass;
//
// base class
//
UCHAR BaseClass;
//
// additional resources count
//
UCHAR AdditionalResourceCount;
//
// adjusted interrupt line
//
UCHAR AdjustedInterruptLine;
//
// interrupt pin
//
UCHAR InterruptPin;
//
// raw interrupt line
//
UCHAR RawInterruptLine;
//
// capabilities ptr
//
UCHAR CapabilitiesPtr;
//
// saved latency timer
//
UCHAR SavedLatencyTimer;
//
// saved cache line size
//
UCHAR SavedCacheLineSize;
//
// head type
//
UCHAR HeaderType;
//
// not present
//
BOOLEAN NotPresent;
//
// reported missing
//
BOOLEAN ReportedMissing;
//
// expected writeback failure
//
BOOLEAN ExpectedWritebackFailure;
//
// do not touch PME
//
BOOLEAN NoTouchPmeEnable;
//
// legacy driver
//
BOOLEAN LegacyDriver;
//
// update hardware
//
BOOLEAN UpdateHardware;
//
// moved device
//
BOOLEAN MovedDevice;
//
// disable power down
//
BOOLEAN DisablePowerDown;
//
// need hotplug
//
BOOLEAN NeedsHotPlugConfiguration;
//
// switch to native mode
//
BOOLEAN SwitchedIDEToNativeMode;
//
// BIOS allow native mode
//
BOOLEAN BIOSAllowsIDESwitchToNativeMode;
//
// io space under native ide control
//
BOOLEAN IoSpaceUnderNativeIdeControl;
//
// on debug path
//
BOOLEAN OnDebugPath;
//
// power state
//
PCI_POWER_STATE PowerState;
//
// header
//
PCI_HEADER_TYPE_DEPENDENT Dependent;
//
// hack flags
//
ULARGE_INTEGER HackFlags;
//
// resource
//
PPCI_FUNCTION_RESOURCES Resources;
//
// bridge fdo extension
//
PPCI_FDO_EXTENSION BridgeFdoExtension;
//
// next bridge
//
struct _PCI_PDO_EXTENSION* NextBridge;
//
// next hash entry
//
struct _PCI_PDO_EXTENSION* NextHashEntry;
//
// lock
//
PCI_LOCK Lock;
//
// pmc
//
PCI_PMC PowerCapabilities;
//
// target agp capabilites ptr
//
UCHAR TargetAgpCapabilityId;
//
// command enables
//
USHORT CommandEnables;
//
// initial command
//
USHORT InitialCommand;
}PCI_PDO_EXTENSION,*PPCI_PDO_EXTENSION;
//
// pci interface
//
typedef struct _PCI_INTERFACE
{
//
// interface guid
//
GUID const* Guid;
//
// min size
//
USHORT MinSize;
//
// min version
//
USHORT MinVersion;
//
// max version
//
USHORT MaxVersion;
//
// flags
//
USHORT Flags;
//
// reference count
//
ULONG ReferenceCount;
//
// signature
//
PCI_SIGNATURE Signature;
//
// constructor
//
PCI_INTERFACE_CONSTRUCTOR Constructor;
//
// initializer
//
PCI_ARBITER_INSTANCE_INITIALIZER Initializer;
}PCI_INTERFACE,*PPCI_INTERFACE;
//
// secondary extension
//
typedef struct _PCI_SECONDARY_EXTENSION
{
//
// next
//
SINGLE_LIST_ENTRY ListEntry;
//
// type
//
PCI_SIGNATURE Type;
//
// destrutor
//
PCI_ARBITER_INSTANCE_DESTRUCTOR Destructor;
}PCI_SECONDARY_EXTENSION,*PPCI_SECONDARY_EXTENSION;
//
// arbiter instance
//
typedef struct _PCI_ARBITER_INSTANCE
{
//
// secondary extension
//
PCI_SECONDARY_EXTENSION SecondaryExtension;
//
// interface
//
PPCI_INTERFACE Interface;
//
// fdo extension
//
PPCI_FDO_EXTENSION BusFdoExtension;
//
// name
//
WCHAR InstanceName[24];
//
// common instance
//
ARBITER_INSTANCE CommonInstance;
}PCI_ARBITER_INSTANCE,*PPCI_ARBITER_INSTANCE;
//
// configurator
//
typedef struct _PCI_CONFIGURATOR
{
//
// massage header for limit determination
//
PCI_MASSAGE_HEADER_FOR_LIMITS_DETERMINATION MassageHeaderForLimitsDetermination;
//
// restore current
//
PCI_RESTORE_CURRENT RestoreCurrent;
//
// save limits
//
PCI_SAVE_LIMITS SaveLimits;
//
// save current setting
//
PCI_SAVE_CURRENT_SETTINGS SaveCurrentSettings;
//
// change resource settings
//
PCI_CHANGE_RESOURCE_SETTINGS ChangeResourceSettings;
//
// get additional descriptors
//
PCI_GET_ADDITIONAL_RESOURCE_DESCRIPTORS GetAdditionalResourceDescriptors;
//
// reset device
//
PCI_RESET_DEVICE ResetDevice;
}PCI_CONFIGURATOR,*PPCI_CONFIGURATOR;
//
// configurator param
//
typedef struct _PCI_CONFIGURATOR_PARAM
{
//
// pdo ext
//
PPCI_PDO_EXTENSION PdoExt;
//
// original config
//
PPCI_COMMON_HEADER OriginalConfig;
//
// config workspace
//
PPCI_COMMON_HEADER Working;
//
// configurator
//
PPCI_CONFIGURATOR Configurator;
//
// saved secondary status
//
USHORT SavedSecondaryStatus;
//
// saved status
//
USHORT SavedStatus;
//
// saved command
//
USHORT SavedCommand;
}PCI_CONFIGURATOR_PARAM,*PPCI_CONFIGURATOR_PARAM;
//
// legacy device info
//
typedef struct _PCI_LEGACY_DEVICE_INFO
{
//
// list entry
//
SINGLE_LIST_ENTRY ListEntry;
//
// owner device
//
PDEVICE_OBJECT OwnerDevice;
//
// bus
//
ULONG BusNumber;
//
// slot
//
ULONG SlotNumber;
//
// base class
//
UCHAR BaseClass;
//
// sub class
//
UCHAR SubClass;
//
// interrupt line
//
UCHAR InterruptLine;
//
// interrupt pin
//
UCHAR InterruptPin;
//
// parent pdo
//
PDEVICE_OBJECT ParentPdo;
//
// routing token
//
ROUTING_TOKEN RoutingToken;
//
// pdo ext
//
PPCI_PDO_EXTENSION PdoExt;
}PCI_LEGACY_DEVICE_INFO,*PPCI_LEGACY_DEVICE_INFO;
//
// int routing extension
//
typedef struct _PCI_INTTERUPT_ROUTING_SECONDARY_EXTENSION
{
//
// common
//
PCI_SECONDARY_EXTENSION SecondaryExtension;
//
// token
//
ROUTING_TOKEN RoutingToken;
}PCI_INTTERUPT_ROUTING_SECONDARY_EXTENSION,*PPCI_INTTERUPT_ROUTING_SECONDARY_EXTENSION;
//
// memory arbiter extension
//
typedef struct _PCI_MEMORY_ARBITER_EXTENSION
{
//
// have prefetchable resource
//
BOOLEAN HasPrefetchableResource;
//
// memory extension initialized
//
BOOLEAN Initialized;
//
// prefetchable resource count
//
USHORT PrefetchableResourceCount;
//
// prefetchable ordering list
//
ARBITER_ORDERING_LIST PrefetchableOrderingList;
//
// normal ordering list
//
ARBITER_ORDERING_LIST NormalOrderingList;
//
// default ordering list
//
ARBITER_ORDERING_LIST DefaultOrderingList;
}PCI_MEMORY_ARBITER_EXTENSION,*PPCI_MEMORY_ARBITER_EXTENSION;
//
// partial list context
//
typedef struct _PCI_PARTIAL_LIST_CONTEXT
{
//
// partial list
//
PCM_PARTIAL_RESOURCE_LIST PartialList;
//
// resourc type
//
UCHAR ResourceType;
//
// count
//
ULONG DescriptorCount;
//
// current descriptor
//
PCM_PARTIAL_RESOURCE_DESCRIPTOR CurrentDescriptor;
//
// alias io descriptor
//
CM_PARTIAL_RESOURCE_DESCRIPTOR AliasPortDescriptor;
}PCI_PARTIAL_LIST_CONTEXT,*PPCI_PARTIAL_LIST_CONTEXT;
//
// range list entry
//
typedef struct _PCI_RANGE_LIST_ENTRY
{
//
// list entry
//
LIST_ENTRY ListEntry;
//
// start
//
ULONGLONG Start;
//
// end
//
ULONGLONG End;
//
// valid
//
BOOLEAN Valid;
}PCI_RANGE_LIST_ENTRY,*PPCI_RANGE_LIST_ENTRY; | bsd-2-clause |
sukinull/libxenserver | src/xen_vif.c | 29109 | /*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stddef.h>
#include <stdlib.h>
#include "xen_internal.h"
#include "xen_string_vif_operations_map_internal.h"
#include "xen_vif_locking_mode_internal.h"
#include "xen_vif_operations_internal.h"
#include <xen/api/xen_common.h>
#include <xen/api/xen_network.h>
#include <xen/api/xen_string_string_map.h>
#include <xen/api/xen_string_vif_operations_map.h>
#include <xen/api/xen_vif.h>
#include <xen/api/xen_vif_metrics.h>
#include <xen/api/xen_vif_operations.h>
#include <xen/api/xen_vif_xen_vif_record_map.h>
#include <xen/api/xen_vm.h>
XEN_FREE(xen_vif)
XEN_SET_ALLOC_FREE(xen_vif)
XEN_ALLOC(xen_vif_record)
XEN_SET_ALLOC_FREE(xen_vif_record)
XEN_ALLOC(xen_vif_record_opt)
XEN_RECORD_OPT_FREE(xen_vif)
XEN_SET_ALLOC_FREE(xen_vif_record_opt)
static const struct_member xen_vif_record_struct_members[] =
{
{ .key = "uuid",
.type = &abstract_type_string,
.offset = offsetof(xen_vif_record, uuid) },
{ .key = "allowed_operations",
.type = &xen_vif_operations_set_abstract_type_,
.offset = offsetof(xen_vif_record, allowed_operations) },
{ .key = "current_operations",
.type = &string_vif_operations_map_abstract_type_,
.offset = offsetof(xen_vif_record, current_operations) },
{ .key = "device",
.type = &abstract_type_string,
.offset = offsetof(xen_vif_record, device) },
{ .key = "network",
.type = &abstract_type_ref,
.offset = offsetof(xen_vif_record, network) },
{ .key = "VM",
.type = &abstract_type_ref,
.offset = offsetof(xen_vif_record, vm) },
{ .key = "MAC",
.type = &abstract_type_string,
.offset = offsetof(xen_vif_record, mac) },
{ .key = "MTU",
.type = &abstract_type_int,
.offset = offsetof(xen_vif_record, mtu) },
{ .key = "other_config",
.type = &abstract_type_string_string_map,
.offset = offsetof(xen_vif_record, other_config) },
{ .key = "currently_attached",
.type = &abstract_type_bool,
.offset = offsetof(xen_vif_record, currently_attached) },
{ .key = "status_code",
.type = &abstract_type_int,
.offset = offsetof(xen_vif_record, status_code) },
{ .key = "status_detail",
.type = &abstract_type_string,
.offset = offsetof(xen_vif_record, status_detail) },
{ .key = "runtime_properties",
.type = &abstract_type_string_string_map,
.offset = offsetof(xen_vif_record, runtime_properties) },
{ .key = "qos_algorithm_type",
.type = &abstract_type_string,
.offset = offsetof(xen_vif_record, qos_algorithm_type) },
{ .key = "qos_algorithm_params",
.type = &abstract_type_string_string_map,
.offset = offsetof(xen_vif_record, qos_algorithm_params) },
{ .key = "qos_supported_algorithms",
.type = &abstract_type_string_set,
.offset = offsetof(xen_vif_record, qos_supported_algorithms) },
{ .key = "metrics",
.type = &abstract_type_ref,
.offset = offsetof(xen_vif_record, metrics) },
{ .key = "MAC_autogenerated",
.type = &abstract_type_bool,
.offset = offsetof(xen_vif_record, mac_autogenerated) },
{ .key = "locking_mode",
.type = &xen_vif_locking_mode_abstract_type_,
.offset = offsetof(xen_vif_record, locking_mode) },
{ .key = "ipv4_allowed",
.type = &abstract_type_string_set,
.offset = offsetof(xen_vif_record, ipv4_allowed) },
{ .key = "ipv6_allowed",
.type = &abstract_type_string_set,
.offset = offsetof(xen_vif_record, ipv6_allowed) }
};
const abstract_type xen_vif_record_abstract_type_ =
{
.typename = STRUCT,
.struct_size = sizeof(xen_vif_record),
.member_count =
sizeof(xen_vif_record_struct_members) / sizeof(struct_member),
.members = xen_vif_record_struct_members
};
static const struct struct_member xen_vif_xen_vif_record_members[] =
{
{
.type = &abstract_type_string,
.offset = offsetof(xen_vif_xen_vif_record_map_contents, key)
},
{
.type = &xen_vif_record_abstract_type_,
.offset = offsetof(xen_vif_xen_vif_record_map_contents, val)
}
};
const abstract_type abstract_type_string_xen_vif_record_map =
{
.typename = MAP,
.struct_size = sizeof(xen_vif_xen_vif_record_map_contents),
.members = xen_vif_xen_vif_record_members
};
void
xen_vif_record_free(xen_vif_record *record)
{
if (record == NULL)
{
return;
}
free(record->handle);
free(record->uuid);
xen_vif_operations_set_free(record->allowed_operations);
xen_string_vif_operations_map_free(record->current_operations);
free(record->device);
xen_network_record_opt_free(record->network);
xen_vm_record_opt_free(record->vm);
free(record->mac);
xen_string_string_map_free(record->other_config);
free(record->status_detail);
xen_string_string_map_free(record->runtime_properties);
free(record->qos_algorithm_type);
xen_string_string_map_free(record->qos_algorithm_params);
xen_string_set_free(record->qos_supported_algorithms);
xen_vif_metrics_record_opt_free(record->metrics);
xen_string_set_free(record->ipv4_allowed);
xen_string_set_free(record->ipv6_allowed);
free(record);
}
bool
xen_vif_get_record(xen_session *session, xen_vif_record **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = xen_vif_record_abstract_type_;
*result = NULL;
XEN_CALL_("VIF.get_record");
if (session->ok)
{
(*result)->handle = xen_opaque_strdup_(vif);
}
return session->ok;
}
bool
xen_vif_get_by_uuid(xen_session *session, xen_vif *result, char *uuid)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = uuid }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.get_by_uuid");
return session->ok;
}
bool
xen_vif_create(xen_session *session, xen_vif *result, xen_vif_record *record)
{
abstract_value param_values[] =
{
{ .type = &xen_vif_record_abstract_type_,
.u.struct_val = record }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.create");
return session->ok;
}
bool
xen_vif_create_async(xen_session *session, xen_task *result, xen_vif_record *record)
{
abstract_value param_values[] =
{
{ .type = &xen_vif_record_abstract_type_,
.u.struct_val = record }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.create");
return session->ok;
}
bool
xen_vif_destroy(xen_session *session, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
xen_call_(session, "VIF.destroy", param_values, 1, NULL, NULL);
return session->ok;
}
bool
xen_vif_destroy_async(xen_session *session, xen_task *result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.destroy");
return session->ok;
}
bool
xen_vif_get_allowed_operations(xen_session *session, struct xen_vif_operations_set **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = xen_vif_operations_set_abstract_type_;
*result = NULL;
XEN_CALL_("VIF.get_allowed_operations");
return session->ok;
}
bool
xen_vif_get_current_operations(xen_session *session, xen_string_vif_operations_map **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = string_vif_operations_map_abstract_type_;
*result = NULL;
XEN_CALL_("VIF.get_current_operations");
return session->ok;
}
bool
xen_vif_get_device(xen_session *session, char **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.get_device");
return session->ok;
}
bool
xen_vif_get_network(xen_session *session, xen_network *result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.get_network");
return session->ok;
}
bool
xen_vif_get_vm(xen_session *session, xen_vm *result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.get_VM");
return session->ok;
}
bool
xen_vif_get_mac(xen_session *session, char **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.get_MAC");
return session->ok;
}
bool
xen_vif_get_mtu(xen_session *session, int64_t *result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_int;
XEN_CALL_("VIF.get_MTU");
return session->ok;
}
bool
xen_vif_get_other_config(xen_session *session, xen_string_string_map **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string_string_map;
*result = NULL;
XEN_CALL_("VIF.get_other_config");
return session->ok;
}
bool
xen_vif_get_currently_attached(xen_session *session, bool *result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_bool;
XEN_CALL_("VIF.get_currently_attached");
return session->ok;
}
bool
xen_vif_get_status_code(xen_session *session, int64_t *result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_int;
XEN_CALL_("VIF.get_status_code");
return session->ok;
}
bool
xen_vif_get_status_detail(xen_session *session, char **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.get_status_detail");
return session->ok;
}
bool
xen_vif_get_runtime_properties(xen_session *session, xen_string_string_map **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string_string_map;
*result = NULL;
XEN_CALL_("VIF.get_runtime_properties");
return session->ok;
}
bool
xen_vif_get_qos_algorithm_type(xen_session *session, char **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.get_qos_algorithm_type");
return session->ok;
}
bool
xen_vif_get_qos_algorithm_params(xen_session *session, xen_string_string_map **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string_string_map;
*result = NULL;
XEN_CALL_("VIF.get_qos_algorithm_params");
return session->ok;
}
bool
xen_vif_get_qos_supported_algorithms(xen_session *session, struct xen_string_set **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string_set;
*result = NULL;
XEN_CALL_("VIF.get_qos_supported_algorithms");
return session->ok;
}
bool
xen_vif_get_metrics(xen_session *session, xen_vif_metrics *result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.get_metrics");
return session->ok;
}
bool
xen_vif_get_mac_autogenerated(xen_session *session, bool *result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_bool;
XEN_CALL_("VIF.get_MAC_autogenerated");
return session->ok;
}
bool
xen_vif_get_locking_mode(xen_session *session, enum xen_vif_locking_mode *result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = xen_vif_locking_mode_abstract_type_;
XEN_CALL_("VIF.get_locking_mode");
return session->ok;
}
bool
xen_vif_get_ipv4_allowed(xen_session *session, struct xen_string_set **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string_set;
*result = NULL;
XEN_CALL_("VIF.get_ipv4_allowed");
return session->ok;
}
bool
xen_vif_get_ipv6_allowed(xen_session *session, struct xen_string_set **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string_set;
*result = NULL;
XEN_CALL_("VIF.get_ipv6_allowed");
return session->ok;
}
bool
xen_vif_set_other_config(xen_session *session, xen_vif vif, xen_string_string_map *other_config)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif },
{ .type = &abstract_type_string_string_map,
.u.set_val = (arbitrary_set *)other_config }
};
xen_call_(session, "VIF.set_other_config", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_add_to_other_config(xen_session *session, xen_vif vif, char *key, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif },
{ .type = &abstract_type_string,
.u.string_val = key },
{ .type = &abstract_type_string,
.u.string_val = value }
};
xen_call_(session, "VIF.add_to_other_config", param_values, 3, NULL, NULL);
return session->ok;
}
bool
xen_vif_remove_from_other_config(xen_session *session, xen_vif vif, char *key)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif },
{ .type = &abstract_type_string,
.u.string_val = key }
};
xen_call_(session, "VIF.remove_from_other_config", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_set_qos_algorithm_type(xen_session *session, xen_vif vif, char *algorithm_type)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif },
{ .type = &abstract_type_string,
.u.string_val = algorithm_type }
};
xen_call_(session, "VIF.set_qos_algorithm_type", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_set_qos_algorithm_params(xen_session *session, xen_vif vif, xen_string_string_map *algorithm_params)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif },
{ .type = &abstract_type_string_string_map,
.u.set_val = (arbitrary_set *)algorithm_params }
};
xen_call_(session, "VIF.set_qos_algorithm_params", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_add_to_qos_algorithm_params(xen_session *session, xen_vif vif, char *key, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif },
{ .type = &abstract_type_string,
.u.string_val = key },
{ .type = &abstract_type_string,
.u.string_val = value }
};
xen_call_(session, "VIF.add_to_qos_algorithm_params", param_values, 3, NULL, NULL);
return session->ok;
}
bool
xen_vif_remove_from_qos_algorithm_params(xen_session *session, xen_vif vif, char *key)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif },
{ .type = &abstract_type_string,
.u.string_val = key }
};
xen_call_(session, "VIF.remove_from_qos_algorithm_params", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_plug(xen_session *session, xen_vif self)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self }
};
xen_call_(session, "VIF.plug", param_values, 1, NULL, NULL);
return session->ok;
}
bool
xen_vif_plug_async(xen_session *session, xen_task *result, xen_vif self)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.plug");
return session->ok;
}
bool
xen_vif_unplug(xen_session *session, xen_vif self)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self }
};
xen_call_(session, "VIF.unplug", param_values, 1, NULL, NULL);
return session->ok;
}
bool
xen_vif_unplug_async(xen_session *session, xen_task *result, xen_vif self)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.unplug");
return session->ok;
}
bool
xen_vif_unplug_force(xen_session *session, xen_vif self)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self }
};
xen_call_(session, "VIF.unplug_force", param_values, 1, NULL, NULL);
return session->ok;
}
bool
xen_vif_unplug_force_async(xen_session *session, xen_task *result, xen_vif self)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.unplug_force");
return session->ok;
}
bool
xen_vif_set_locking_mode(xen_session *session, xen_vif self, enum xen_vif_locking_mode value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &xen_vif_locking_mode_abstract_type_,
.u.enum_val = value }
};
xen_call_(session, "VIF.set_locking_mode", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_set_locking_mode_async(xen_session *session, xen_task *result, xen_vif self, enum xen_vif_locking_mode value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &xen_vif_locking_mode_abstract_type_,
.u.enum_val = value }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.set_locking_mode");
return session->ok;
}
bool
xen_vif_set_ipv4_allowed(xen_session *session, xen_vif self, struct xen_string_set *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string_set,
.u.set_val = (arbitrary_set *)value }
};
xen_call_(session, "VIF.set_ipv4_allowed", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_set_ipv4_allowed_async(xen_session *session, xen_task *result, xen_vif self, struct xen_string_set *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string_set,
.u.set_val = (arbitrary_set *)value }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.set_ipv4_allowed");
return session->ok;
}
bool
xen_vif_add_ipv4_allowed(xen_session *session, xen_vif self, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string,
.u.string_val = value }
};
xen_call_(session, "VIF.add_ipv4_allowed", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_add_ipv4_allowed_async(xen_session *session, xen_task *result, xen_vif self, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string,
.u.string_val = value }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.add_ipv4_allowed");
return session->ok;
}
bool
xen_vif_remove_ipv4_allowed(xen_session *session, xen_vif self, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string,
.u.string_val = value }
};
xen_call_(session, "VIF.remove_ipv4_allowed", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_remove_ipv4_allowed_async(xen_session *session, xen_task *result, xen_vif self, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string,
.u.string_val = value }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.remove_ipv4_allowed");
return session->ok;
}
bool
xen_vif_set_ipv6_allowed(xen_session *session, xen_vif self, struct xen_string_set *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string_set,
.u.set_val = (arbitrary_set *)value }
};
xen_call_(session, "VIF.set_ipv6_allowed", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_set_ipv6_allowed_async(xen_session *session, xen_task *result, xen_vif self, struct xen_string_set *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string_set,
.u.set_val = (arbitrary_set *)value }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.set_ipv6_allowed");
return session->ok;
}
bool
xen_vif_add_ipv6_allowed(xen_session *session, xen_vif self, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string,
.u.string_val = value }
};
xen_call_(session, "VIF.add_ipv6_allowed", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_add_ipv6_allowed_async(xen_session *session, xen_task *result, xen_vif self, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string,
.u.string_val = value }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.add_ipv6_allowed");
return session->ok;
}
bool
xen_vif_remove_ipv6_allowed(xen_session *session, xen_vif self, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string,
.u.string_val = value }
};
xen_call_(session, "VIF.remove_ipv6_allowed", param_values, 2, NULL, NULL);
return session->ok;
}
bool
xen_vif_remove_ipv6_allowed_async(xen_session *session, xen_task *result, xen_vif self, char *value)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = self },
{ .type = &abstract_type_string,
.u.string_val = value }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("Async.VIF.remove_ipv6_allowed");
return session->ok;
}
bool
xen_vif_get_all(xen_session *session, struct xen_vif_set **result)
{
abstract_type result_type = abstract_type_string_set;
*result = NULL;
xen_call_(session, "VIF.get_all", NULL, 0, &result_type, result);
return session->ok;
}
bool
xen_vif_get_all_records(xen_session *session, xen_vif_xen_vif_record_map **result)
{
abstract_type result_type = abstract_type_string_xen_vif_record_map;
*result = NULL;
xen_call_(session, "VIF.get_all_records", NULL, 0, &result_type, result);
return session->ok;
}
bool
xen_vif_get_uuid(xen_session *session, char **result, xen_vif vif)
{
abstract_value param_values[] =
{
{ .type = &abstract_type_string,
.u.string_val = vif }
};
abstract_type result_type = abstract_type_string;
*result = NULL;
XEN_CALL_("VIF.get_uuid");
return session->ok;
}
| bsd-2-clause |
sklam/numba | numba/cuda/simulator/__init__.py | 1170 | from .api import *
from .reduction import Reduce
from .cudadrv.devicearray import (device_array, device_array_like, pinned,
pinned_array, pinned_array_like, to_device, auto_device)
from .cudadrv import devicearray
from .cudadrv.devices import require_context, gpus
from .cudadrv.devices import get_context as current_context
from .cudadrv.runtime import runtime
from numba.core import config
reduce = Reduce
# Ensure that any user code attempting to import cudadrv etc. gets the
# simulator's version and not the real version if the simulator is enabled.
if config.ENABLE_CUDASIM:
import sys
from numba.cuda.simulator import cudadrv
sys.modules['numba.cuda.cudadrv'] = cudadrv
sys.modules['numba.cuda.cudadrv.devicearray'] = cudadrv.devicearray
sys.modules['numba.cuda.cudadrv.devices'] = cudadrv.devices
sys.modules['numba.cuda.cudadrv.driver'] = cudadrv.driver
sys.modules['numba.cuda.cudadrv.runtime'] = cudadrv.runtime
sys.modules['numba.cuda.cudadrv.drvapi'] = cudadrv.drvapi
sys.modules['numba.cuda.cudadrv.nvvm'] = cudadrv.nvvm
from . import compiler
sys.modules['numba.cuda.compiler'] = compiler
| bsd-2-clause |
dartsim/dart | dart/dynamics/WeldJoint.hpp | 3722 | /*
* Copyright (c) 2011-2022, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DART_DYNAMICS_WELDJOINT_HPP_
#define DART_DYNAMICS_WELDJOINT_HPP_
#include <string>
#include <Eigen/Dense>
#include "dart/dynamics/ZeroDofJoint.hpp"
namespace dart {
namespace dynamics {
/// class WeldJoint
class WeldJoint : public ZeroDofJoint
{
public:
friend class Skeleton;
struct Properties : ZeroDofJoint::Properties
{
DART_DEFINE_ALIGNED_SHARED_OBJECT_CREATOR(Properties)
Properties(const Joint::Properties& _properties = Joint::Properties());
virtual ~Properties() = default;
};
WeldJoint(const WeldJoint&) = delete;
/// Destructor
virtual ~WeldJoint();
/// Get the Properties of this WeldJoint
Properties getWeldJointProperties() const;
// Documentation inherited
const std::string& getType() const override;
/// Get joint type for this class
static const std::string& getStaticType();
// Documentation inherited
bool isCyclic(std::size_t _index) const override;
// Documentation inherited
void setTransformFromParentBodyNode(const Eigen::Isometry3d& _T) override;
// Documentation inherited
void setTransformFromChildBodyNode(const Eigen::Isometry3d& _T) override;
protected:
/// Constructor called by Skeleton class
WeldJoint(const Properties& properties);
// Documentation inherited
Joint* clone() const override;
//----------------------------------------------------------------------------
// Recursive algorithms
//----------------------------------------------------------------------------
// Documentation inherited
void updateRelativeTransform() const override;
// Documentation inherited
void updateRelativeSpatialVelocity() const override;
// Documentation inherited
void updateRelativeSpatialAcceleration() const override;
// Documentation inherited
void updateRelativePrimaryAcceleration() const override;
// Documentation inherited
void updateRelativeJacobian(bool = true) const override;
// Documentation inherited
void updateRelativeJacobianTimeDeriv() const override;
};
} // namespace dynamics
} // namespace dart
#endif // DART_DYNAMICS_WELDJOINT_HPP_
| bsd-2-clause |
epiqc/ScaffCC | clang/include/clang/Serialization/ModuleFile.h | 16020 | //===- ModuleFile.h - Module file description -------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the Module class, which describes a module that has
// been loaded from an AST file.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SERIALIZATION_MODULEFILE_H
#define LLVM_CLANG_SERIALIZATION_MODULEFILE_H
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Serialization/ASTBitCodes.h"
#include "clang/Serialization/ContinuousRangeMap.h"
#include "clang/Serialization/ModuleFileExtension.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitstream/BitstreamReader.h"
#include "llvm/Support/Endian.h"
#include <cassert>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace clang {
class FileEntry;
namespace serialization {
/// Specifies the kind of module that has been loaded.
enum ModuleKind {
/// File is an implicitly-loaded module.
MK_ImplicitModule,
/// File is an explicitly-loaded module.
MK_ExplicitModule,
/// File is a PCH file treated as such.
MK_PCH,
/// File is a PCH file treated as the preamble.
MK_Preamble,
/// File is a PCH file treated as the actual main file.
MK_MainFile,
/// File is from a prebuilt module path.
MK_PrebuiltModule
};
/// The input file that has been loaded from this AST file, along with
/// bools indicating whether this was an overridden buffer or if it was
/// out-of-date or not-found.
class InputFile {
enum {
Overridden = 1,
OutOfDate = 2,
NotFound = 3
};
llvm::PointerIntPair<const FileEntry *, 2, unsigned> Val;
public:
InputFile() = default;
InputFile(const FileEntry *File,
bool isOverridden = false, bool isOutOfDate = false) {
assert(!(isOverridden && isOutOfDate) &&
"an overridden cannot be out-of-date");
unsigned intVal = 0;
if (isOverridden)
intVal = Overridden;
else if (isOutOfDate)
intVal = OutOfDate;
Val.setPointerAndInt(File, intVal);
}
static InputFile getNotFound() {
InputFile File;
File.Val.setInt(NotFound);
return File;
}
const FileEntry *getFile() const { return Val.getPointer(); }
bool isOverridden() const { return Val.getInt() == Overridden; }
bool isOutOfDate() const { return Val.getInt() == OutOfDate; }
bool isNotFound() const { return Val.getInt() == NotFound; }
};
/// Information about a module that has been loaded by the ASTReader.
///
/// Each instance of the Module class corresponds to a single AST file, which
/// may be a precompiled header, precompiled preamble, a module, or an AST file
/// of some sort loaded as the main file, all of which are specific formulations
/// of the general notion of a "module". A module may depend on any number of
/// other modules.
class ModuleFile {
public:
ModuleFile(ModuleKind Kind, unsigned Generation)
: Kind(Kind), Generation(Generation) {}
~ModuleFile();
// === General information ===
/// The index of this module in the list of modules.
unsigned Index = 0;
/// The type of this module.
ModuleKind Kind;
/// The file name of the module file.
std::string FileName;
/// The name of the module.
std::string ModuleName;
/// The base directory of the module.
std::string BaseDirectory;
std::string getTimestampFilename() const {
return FileName + ".timestamp";
}
/// The original source file name that was used to build the
/// primary AST file, which may have been modified for
/// relocatable-pch support.
std::string OriginalSourceFileName;
/// The actual original source file name that was used to
/// build this AST file.
std::string ActualOriginalSourceFileName;
/// The file ID for the original source file that was used to
/// build this AST file.
FileID OriginalSourceFileID;
/// The directory that the PCH was originally created in. Used to
/// allow resolving headers even after headers+PCH was moved to a new path.
std::string OriginalDir;
std::string ModuleMapPath;
/// Whether this precompiled header is a relocatable PCH file.
bool RelocatablePCH = false;
/// Whether timestamps are included in this module file.
bool HasTimestamps = false;
/// Whether the PCH has a corresponding object file.
bool PCHHasObjectFile = false;
/// Whether the top-level module has been read from the AST file.
bool DidReadTopLevelSubmodule = false;
/// The file entry for the module file.
const FileEntry *File = nullptr;
/// The signature of the module file, which may be used instead of the size
/// and modification time to identify this particular file.
ASTFileSignature Signature;
/// Whether this module has been directly imported by the
/// user.
bool DirectlyImported = false;
/// The generation of which this module file is a part.
unsigned Generation;
/// The memory buffer that stores the data associated with
/// this AST file, owned by the InMemoryModuleCache.
llvm::MemoryBuffer *Buffer;
/// The size of this file, in bits.
uint64_t SizeInBits = 0;
/// The global bit offset (or base) of this module
uint64_t GlobalBitOffset = 0;
/// The serialized bitstream data for this file.
StringRef Data;
/// The main bitstream cursor for the main block.
llvm::BitstreamCursor Stream;
/// The source location where the module was explicitly or implicitly
/// imported in the local translation unit.
///
/// If module A depends on and imports module B, both modules will have the
/// same DirectImportLoc, but different ImportLoc (B's ImportLoc will be a
/// source location inside module A).
///
/// WARNING: This is largely useless. It doesn't tell you when a module was
/// made visible, just when the first submodule of that module was imported.
SourceLocation DirectImportLoc;
/// The source location where this module was first imported.
SourceLocation ImportLoc;
/// The first source location in this module.
SourceLocation FirstLoc;
/// The list of extension readers that are attached to this module
/// file.
std::vector<std::unique_ptr<ModuleFileExtensionReader>> ExtensionReaders;
/// The module offset map data for this file. If non-empty, the various
/// ContinuousRangeMaps described below have not yet been populated.
StringRef ModuleOffsetMap;
// === Input Files ===
/// The cursor to the start of the input-files block.
llvm::BitstreamCursor InputFilesCursor;
/// Offsets for all of the input file entries in the AST file.
const llvm::support::unaligned_uint64_t *InputFileOffsets = nullptr;
/// The input files that have been loaded from this AST file.
std::vector<InputFile> InputFilesLoaded;
// All user input files reside at the index range [0, NumUserInputFiles), and
// system input files reside at [NumUserInputFiles, InputFilesLoaded.size()).
unsigned NumUserInputFiles = 0;
/// If non-zero, specifies the time when we last validated input
/// files. Zero means we never validated them.
///
/// The time is specified in seconds since the start of the Epoch.
uint64_t InputFilesValidationTimestamp = 0;
// === Source Locations ===
/// Cursor used to read source location entries.
llvm::BitstreamCursor SLocEntryCursor;
/// The number of source location entries in this AST file.
unsigned LocalNumSLocEntries = 0;
/// The base ID in the source manager's view of this module.
int SLocEntryBaseID = 0;
/// The base offset in the source manager's view of this module.
unsigned SLocEntryBaseOffset = 0;
/// Offsets for all of the source location entries in the
/// AST file.
const uint32_t *SLocEntryOffsets = nullptr;
/// SLocEntries that we're going to preload.
SmallVector<uint64_t, 4> PreloadSLocEntries;
/// Remapping table for source locations in this module.
ContinuousRangeMap<uint32_t, int, 2> SLocRemap;
// === Identifiers ===
/// The number of identifiers in this AST file.
unsigned LocalNumIdentifiers = 0;
/// Offsets into the identifier table data.
///
/// This array is indexed by the identifier ID (-1), and provides
/// the offset into IdentifierTableData where the string data is
/// stored.
const uint32_t *IdentifierOffsets = nullptr;
/// Base identifier ID for identifiers local to this module.
serialization::IdentID BaseIdentifierID = 0;
/// Remapping table for identifier IDs in this module.
ContinuousRangeMap<uint32_t, int, 2> IdentifierRemap;
/// Actual data for the on-disk hash table of identifiers.
///
/// This pointer points into a memory buffer, where the on-disk hash
/// table for identifiers actually lives.
const char *IdentifierTableData = nullptr;
/// A pointer to an on-disk hash table of opaque type
/// IdentifierHashTable.
void *IdentifierLookupTable = nullptr;
/// Offsets of identifiers that we're going to preload within
/// IdentifierTableData.
std::vector<unsigned> PreloadIdentifierOffsets;
// === Macros ===
/// The cursor to the start of the preprocessor block, which stores
/// all of the macro definitions.
llvm::BitstreamCursor MacroCursor;
/// The number of macros in this AST file.
unsigned LocalNumMacros = 0;
/// Offsets of macros in the preprocessor block.
///
/// This array is indexed by the macro ID (-1), and provides
/// the offset into the preprocessor block where macro definitions are
/// stored.
const uint32_t *MacroOffsets = nullptr;
/// Base macro ID for macros local to this module.
serialization::MacroID BaseMacroID = 0;
/// Remapping table for macro IDs in this module.
ContinuousRangeMap<uint32_t, int, 2> MacroRemap;
/// The offset of the start of the set of defined macros.
uint64_t MacroStartOffset = 0;
// === Detailed PreprocessingRecord ===
/// The cursor to the start of the (optional) detailed preprocessing
/// record block.
llvm::BitstreamCursor PreprocessorDetailCursor;
/// The offset of the start of the preprocessor detail cursor.
uint64_t PreprocessorDetailStartOffset = 0;
/// Base preprocessed entity ID for preprocessed entities local to
/// this module.
serialization::PreprocessedEntityID BasePreprocessedEntityID = 0;
/// Remapping table for preprocessed entity IDs in this module.
ContinuousRangeMap<uint32_t, int, 2> PreprocessedEntityRemap;
const PPEntityOffset *PreprocessedEntityOffsets = nullptr;
unsigned NumPreprocessedEntities = 0;
/// Base ID for preprocessed skipped ranges local to this module.
unsigned BasePreprocessedSkippedRangeID = 0;
const PPSkippedRange *PreprocessedSkippedRangeOffsets = nullptr;
unsigned NumPreprocessedSkippedRanges = 0;
// === Header search information ===
/// The number of local HeaderFileInfo structures.
unsigned LocalNumHeaderFileInfos = 0;
/// Actual data for the on-disk hash table of header file
/// information.
///
/// This pointer points into a memory buffer, where the on-disk hash
/// table for header file information actually lives.
const char *HeaderFileInfoTableData = nullptr;
/// The on-disk hash table that contains information about each of
/// the header files.
void *HeaderFileInfoTable = nullptr;
// === Submodule information ===
/// The number of submodules in this module.
unsigned LocalNumSubmodules = 0;
/// Base submodule ID for submodules local to this module.
serialization::SubmoduleID BaseSubmoduleID = 0;
/// Remapping table for submodule IDs in this module.
ContinuousRangeMap<uint32_t, int, 2> SubmoduleRemap;
// === Selectors ===
/// The number of selectors new to this file.
///
/// This is the number of entries in SelectorOffsets.
unsigned LocalNumSelectors = 0;
/// Offsets into the selector lookup table's data array
/// where each selector resides.
const uint32_t *SelectorOffsets = nullptr;
/// Base selector ID for selectors local to this module.
serialization::SelectorID BaseSelectorID = 0;
/// Remapping table for selector IDs in this module.
ContinuousRangeMap<uint32_t, int, 2> SelectorRemap;
/// A pointer to the character data that comprises the selector table
///
/// The SelectorOffsets table refers into this memory.
const unsigned char *SelectorLookupTableData = nullptr;
/// A pointer to an on-disk hash table of opaque type
/// ASTSelectorLookupTable.
///
/// This hash table provides the IDs of all selectors, and the associated
/// instance and factory methods.
void *SelectorLookupTable = nullptr;
// === Declarations ===
/// DeclsCursor - This is a cursor to the start of the DECLS_BLOCK block. It
/// has read all the abbreviations at the start of the block and is ready to
/// jump around with these in context.
llvm::BitstreamCursor DeclsCursor;
/// The number of declarations in this AST file.
unsigned LocalNumDecls = 0;
/// Offset of each declaration within the bitstream, indexed
/// by the declaration ID (-1).
const DeclOffset *DeclOffsets = nullptr;
/// Base declaration ID for declarations local to this module.
serialization::DeclID BaseDeclID = 0;
/// Remapping table for declaration IDs in this module.
ContinuousRangeMap<uint32_t, int, 2> DeclRemap;
/// Mapping from the module files that this module file depends on
/// to the base declaration ID for that module as it is understood within this
/// module.
///
/// This is effectively a reverse global-to-local mapping for declaration
/// IDs, so that we can interpret a true global ID (for this translation unit)
/// as a local ID (for this module file).
llvm::DenseMap<ModuleFile *, serialization::DeclID> GlobalToLocalDeclIDs;
/// Array of file-level DeclIDs sorted by file.
const serialization::DeclID *FileSortedDecls = nullptr;
unsigned NumFileSortedDecls = 0;
/// Array of category list location information within this
/// module file, sorted by the definition ID.
const serialization::ObjCCategoriesInfo *ObjCCategoriesMap = nullptr;
/// The number of redeclaration info entries in ObjCCategoriesMap.
unsigned LocalNumObjCCategoriesInMap = 0;
/// The Objective-C category lists for categories known to this
/// module.
SmallVector<uint64_t, 1> ObjCCategories;
// === Types ===
/// The number of types in this AST file.
unsigned LocalNumTypes = 0;
/// Offset of each type within the bitstream, indexed by the
/// type ID, or the representation of a Type*.
const uint32_t *TypeOffsets = nullptr;
/// Base type ID for types local to this module as represented in
/// the global type ID space.
serialization::TypeID BaseTypeIndex = 0;
/// Remapping table for type IDs in this module.
ContinuousRangeMap<uint32_t, int, 2> TypeRemap;
// === Miscellaneous ===
/// Diagnostic IDs and their mappings that the user changed.
SmallVector<uint64_t, 8> PragmaDiagMappings;
/// List of modules which depend on this module
llvm::SetVector<ModuleFile *> ImportedBy;
/// List of modules which this module depends on
llvm::SetVector<ModuleFile *> Imports;
/// Determine whether this module was directly imported at
/// any point during translation.
bool isDirectlyImported() const { return DirectlyImported; }
/// Is this a module file for a module (rather than a PCH or similar).
bool isModule() const {
return Kind == MK_ImplicitModule || Kind == MK_ExplicitModule ||
Kind == MK_PrebuiltModule;
}
/// Dump debugging output for this module.
void dump();
};
} // namespace serialization
} // namespace clang
#endif // LLVM_CLANG_SERIALIZATION_MODULEFILE_H
| bsd-2-clause |
hughperkins/pytorch | build.sh | 1284 | #!/bin/bash
# - must have Cython installed
# - must have already run:
# mkdir cbuild
# (cd cbuild && cmake .. && make -j 4 )
# - torch is expected to be already activated, ie run:
# source ~/torch/install/bin/torch_activate.sh
# ... or similar
# - torch is expected to be at $HOME/torch
export TORCH_INSTALL=$(dirname $(dirname $(which luajit) 2>/dev/null) 2>/dev/null)
if [[ x${INCREMENTAL} == x ]]; then {
rm -Rf build PyBuild.so dist *.egg-info cbuild ${TORCH_INSTALL}/lib/libPyTorch*
pip uninstall -y PyTorch
} fi
mkdir -p cbuild
if [[ x${TORCH_INSTALL} == x ]]; then {
echo
echo Please run:
echo
echo ' source ~/torch/install/bin/torch-activate'
echo
echo ... then try again
echo
exit 1
} fi
if [[ $(uname -s) == 'Darwin' ]]; then { USE_LUAJIT=OFF; } fi
if [[ x${USE_LUAJIT} == x ]]; then { USE_LUAJIT=ON; } fi
if [[ x${CYTHON} != x ]]; then { JINJA2_ONLY=1 python setup.py || exit 1; } fi
(cd cbuild; cmake .. -DCMAKE_BUILD_TYPE=Debug -DUSE_LUAJIT=${USE_LUAJIT} -DCMAKE_INSTALL_PREFIX=${TORCH_INSTALL} && make -j 4 install) || exit 1
if [[ x${VIRTUAL_ENV} != x ]]; then {
# we are in a virtualenv
python setup.py install || exit 1
} else {
# not virtualenv
python setup.py install --user || exit 1
} fi
| bsd-2-clause |
ponty/confduino | confduino/boardremove.py | 452 | from confduino.boardlist import boards_txt
from entrypoint2 import entrypoint
import logging
log = logging.getLogger(__name__)
@entrypoint
def remove_board(board_id):
"""remove board.
:param board_id: board id (e.g. 'diecimila')
:rtype: None
"""
log.debug('remove %s', board_id)
lines = boards_txt().lines()
lines = filter(lambda x: not x.strip().startswith(board_id + '.'), lines)
boards_txt().write_lines(lines)
| bsd-2-clause |
SupremeBeing/Silver-Hammer | silver-hammer-core/src/main/java/ru/silverhammer/processor/ControlProcessor.java | 5459 | /*
* Copyright (c) 2019, Dmitriy Shchekotin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package ru.silverhammer.processor;
import java.lang.annotation.Annotation;
import java.util.List;
import ru.junkie.IInjector;
import ru.reflexio.IFieldReflection;
import ru.reflexio.IInstanceFieldReflection;
import ru.reflexio.MetaAnnotation;
import ru.sanatio.conversion.IStringConverter;
import ru.silverhammer.initializer.InitializerReference;
import ru.silverhammer.model.CategoryModel;
import ru.silverhammer.model.ControlModel;
import ru.silverhammer.model.GroupModel;
import ru.silverhammer.model.UiModel;
import ru.silverhammer.control.IControl;
import ru.silverhammer.decorator.IDecorator;
import ru.silverhammer.initializer.IInitializer;
import ru.silverhammer.resolver.IControlResolver;
public class ControlProcessor implements IProcessor<IInstanceFieldReflection, Annotation> {
private final IStringConverter converter;
private final IInjector injector;
private final IControlResolver controlResolver;
private final UiModel model;
public ControlProcessor(IInjector injector, IStringConverter converter, IControlResolver controlResolver, UiModel model) {
this.injector = injector;
this.converter = converter;
this.controlResolver = controlResolver;
this.model = model;
}
@SuppressWarnings("unchecked")
@Override
public void process(Object data, IInstanceFieldReflection reflection, Annotation annotation) {
Class<? extends IControl<?, ?>> controlClass = controlResolver.getControlClass(annotation.annotationType());
if (controlClass != null) {
IControl control = injector.instantiate(controlClass);
decorateControl(control, data, reflection);
addControlAttributes(reflection.getAnnotation(GroupId.class), createControlModel(control, data, reflection));
control.init(annotation);
initializeControl(control, data, reflection);
}
}
@SuppressWarnings("unchecked")
private void decorateControl(IControl<?, ?> control, Object data, IFieldReflection field) {
for (Annotation a : field.getAnnotations()) {
Class<? extends IDecorator<?, ?>> decoratorClass = controlResolver.getDecoratorClass(a.annotationType());
if (decoratorClass != null) {
IDecorator decorator = injector.instantiate(decoratorClass);
decorator.init(a, data);
decorator.setControl(control);
}
}
}
@SuppressWarnings("unchecked")
private void initializeControl(IControl<?, ?> control, Object data, IInstanceFieldReflection field) {
List<MetaAnnotation<InitializerReference>> marked = field.getMetaAnnotations(InitializerReference.class);
for (MetaAnnotation<InitializerReference> ma : marked) {
IInitializer<IControl<?, ?>, Annotation> initializer = (IInitializer<IControl<?, ?>, Annotation>) injector.instantiate(ma.getMetaAnnotation().value());
initializer.init(control, ma.getAnnotation(), data, field);
}
Object value = field.getValue(data);
value = model.getControlValue(value, field);
((IControl<Object, ?>) control).setValue(value);
}
private void addControlAttributes(GroupId gi, ControlModel controlModel) {
String groupId = gi == null ? null : gi.value();
GroupModel groupModel = model.findGroupModel(groupId);
if (groupModel == null) {
groupModel = new GroupModel(groupId);
if (model.getCategories().isEmpty()) {
model.getCategories().add(new CategoryModel()); // TODO: revisit
}
model.getCategories().get(0).getGroups().add(groupModel);
}
groupModel.getControls().add(controlModel);
}
private ControlModel createControlModel(IControl<?, ?> control, Object data, IInstanceFieldReflection field) {
ControlModel result = new ControlModel(control, data, field);
Caption caption = field.getAnnotation(Caption.class);
Description description = field.getAnnotation(Description.class);
if (caption != null) {
result.setCaption(converter.getString(caption.value()));
result.setCaptionLocation(caption.location());
result.setHorizontalAlignment(caption.horizontalAlignment());
result.setVerticalAlignment(caption.verticalAlignment());
}
if (description != null) {
result.setDescription(converter.getString(description.value()));
}
return result;
}
}
| bsd-2-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.