repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
TY231618/fizzbuzz-js | spec/fizzBuzzSpec.js | 1687 | describe('Fizzbuzz', function() {
var fizzbuzz;
beforeEach(function() {
fizzbuzz = new Fizzbuzz();
});
describe('a number', function() {
it('divisible by 3', function() {
expect(fizzbuzz.isDivisibleByThree(3)).toBe(true);
});
});
describe('a number not', function() {
it('divisible by 3', function() {
expect(fizzbuzz.isDivisibleByThree(1)).toBe(false);
})
})
describe('a number', function() {
it('divisible by 5', function() {
expect(fizzbuzz.isDivisibleByFive(5)).toBe(true);
});
});
describe('a number not', function() {
it('divisible by 5', function() {
expect(fizzbuzz.isDivisibleByFive(1)).toBe(false);
});
});
describe('a number', function() {
it('divisible by 15', function() {
expect(fizzbuzz.isDivisibleByFifteen(15)).toBe(true);
});
});
describe('a number not', function() {
it('divisible by 15', function() {
expect(fizzbuzz.isDivisibleByFifteen(20)).toBe(false);
});
});
describe('when playing, says', function() {
it('"Fizz" if number is divisible by 3', function() {
expect(fizzbuzz.says(3)).toEqual("Fizz");
});
});
describe('when playing, says', function() {
it('"Buzz" ifnumber is divisible by 5', function() {
expect(fizzbuzz.says(5)).toEqual("Buzz");
});
});
describe('when playing, says', function() {
it('"FizzBuzz" if number is divisible by 15', function() {
expect(fizzbuzz.says(15)).toEqual("FizzBuzz");
});
});
describe('when playing, says', function() {
it('number if not divisible by 3, 5 or 15', function() {
expect(fizzbuzz.says(7)).toEqual(7);
});
});
});
| mit |
iammck/ECalculon | app/src/androidTest/java/com/mck/ecalculon/OutputFragmentTest.java | 812 | package com.mck.ecalculon;
import android.test.ActivityInstrumentationTestCase2;
import org.junit.Test;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
/**
* Created by mike on 5/2/2015.
*/
public class OutputFragmentTest extends ActivityInstrumentationTestCase2<MainActivity> {
public OutputFragmentTest(){
super(MainActivity.class);
}
@Test
public void testInitialOutputText(){
getActivity();
onView(withId(R.id.output))
.check(matches(withText(R.string.default_output)));
}
}
| mit |
HaozheGuAsh/Undergraduate | 2013-2017/ECS165B/project/parser/sql_parser.tab.hh | 14909 | // A Bison parser, made by GNU Bison 3.0.2.
// Skeleton interface for Bison LALR(1) parsers in C++
// Copyright (C) 2002-2013 Free Software Foundation, Inc.
// This program 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.
// This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
// As a special exception, you may create a larger work that contains
// part or all of the Bison parser skeleton and distribute that work
// under terms of your choice, so long as that work isn't itself a
// parser generator using the skeleton or a modified version thereof
// as a parser skeleton. Alternatively, if you modify or redistribute
// the parser skeleton itself, you may (at your option) remove this
// special exception, which will cause the skeleton and the resulting
// Bison output files to be licensed under the GNU General Public
// License without this special exception.
// This special exception was added by the Free Software Foundation in
// version 2.2 of Bison.
/**
** \file sql_parser.tab.hh
** Define the UCD::parser class.
*/
// C++ LALR(1) parser skeleton written by Akim Demaille.
#ifndef YY_YY_SQL_PARSER_TAB_HH_INCLUDED
# define YY_YY_SQL_PARSER_TAB_HH_INCLUDED
// // "%code requires" blocks.
#line 8 "sql_parser.yy" // lalr1.cc:372
namespace UCD {
class SQLDriver;
class SQLScanner;
}
// The following definitions is missing when %locations isn't used
# ifndef YY_NULLPTR
# if defined __cplusplus && 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# endif
#line 61 "sql_parser.tab.hh" // lalr1.cc:372
# include <vector>
# include <iostream>
# include <stdexcept>
# include <string>
# include "stack.hh"
# include "location.hh"
#ifndef YY_ATTRIBUTE
# if (defined __GNUC__ \
&& (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
|| defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
# else
# define YY_ATTRIBUTE(Spec) /* empty */
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
#endif
#if !defined _Noreturn \
&& (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
# if defined _MSC_VER && 1200 <= _MSC_VER
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 1
#endif
#line 5 "sql_parser.yy" // lalr1.cc:372
namespace UCD {
#line 132 "sql_parser.tab.hh" // lalr1.cc:372
/// A Bison parser.
class SQLParser
{
public:
#ifndef YYSTYPE
/// Symbol semantic values.
union semantic_type
{
#line 49 "sql_parser.yy" // lalr1.cc:372
int num;
std::string* str;
//class UCD::SQLExpression* expr;
#line 152 "sql_parser.tab.hh" // lalr1.cc:372
};
#else
typedef YYSTYPE semantic_type;
#endif
/// Symbol locations.
typedef location location_type;
/// Syntax errors thrown from user actions.
struct syntax_error : std::runtime_error
{
syntax_error (const location_type& l, const std::string& m);
location_type location;
};
/// Tokens.
struct token
{
enum yytokentype
{
IDENT = 258,
NUMBER = 259,
STRING = 260,
NUL = 261,
SELECT = 262,
AS = 263,
FROM = 264,
WHERE = 265,
GROUP = 266,
BY = 267,
HAVING = 268,
ORDER = 269,
ASC = 270,
DESC = 271,
INSERT = 272,
INTO = 273,
VALUES = 274,
UPDATE = 275,
SET = 276,
DELETE = 277,
CREATE = 278,
TABLE = 279,
DESCRIBE = 280,
SHOW = 281,
TABLES = 282,
DROP = 283,
PRIMARY = 284,
DISTINCT = 285,
KEY = 286,
NOTEQ = 287,
GEQ = 288,
LEQ = 289,
AND = 290,
OR = 291,
NOT = 292,
ERROR = 293,
QUIT = 294
};
};
/// (External) token type, as returned by yylex.
typedef token::yytokentype token_type;
/// Internal symbol number.
typedef int symbol_number_type;
/// Internal symbol number for tokens (subsumed by symbol_number_type).
typedef unsigned char token_number_type;
/// A complete symbol.
///
/// Expects its Base type to provide access to the symbol type
/// via type_get().
///
/// Provide access to semantic value and location.
template <typename Base>
struct basic_symbol : Base
{
/// Alias to Base.
typedef Base super_type;
/// Default constructor.
basic_symbol ();
/// Copy constructor.
basic_symbol (const basic_symbol& other);
/// Constructor for valueless symbols.
basic_symbol (typename Base::kind_type t,
const location_type& l);
/// Constructor for symbols with semantic value.
basic_symbol (typename Base::kind_type t,
const semantic_type& v,
const location_type& l);
~basic_symbol ();
/// Destructive move, \a s is emptied into this.
void move (basic_symbol& s);
/// The semantic value.
semantic_type value;
/// The location.
location_type location;
private:
/// Assignment operator.
basic_symbol& operator= (const basic_symbol& other);
};
/// Type access provider for token (enum) based symbols.
struct by_type
{
/// Default constructor.
by_type ();
/// Copy constructor.
by_type (const by_type& other);
/// The symbol type as needed by the constructor.
typedef token_type kind_type;
/// Constructor from (external) token numbers.
by_type (kind_type t);
/// Steal the symbol type from \a that.
void move (by_type& that);
/// The (internal) type number (corresponding to \a type).
/// -1 when this symbol is empty.
symbol_number_type type_get () const;
/// The token.
token_type token () const;
enum { empty = 0 };
/// The symbol type.
/// -1 when this symbol is empty.
token_number_type type;
};
/// "External" symbols: returned by the scanner.
typedef basic_symbol<by_type> symbol_type;
/// Build a parser object.
SQLParser (UCD::SQLScanner &scanner_yyarg, UCD::SQLDriver &driver_yyarg);
virtual ~SQLParser ();
/// Parse.
/// \returns 0 iff parsing succeeded.
virtual int parse ();
#if YYDEBUG
/// The current debugging stream.
std::ostream& debug_stream () const YY_ATTRIBUTE_PURE;
/// Set the current debugging stream.
void set_debug_stream (std::ostream &);
/// Type for debugging levels.
typedef int debug_level_type;
/// The current debugging level.
debug_level_type debug_level () const YY_ATTRIBUTE_PURE;
/// Set the current debugging level.
void set_debug_level (debug_level_type l);
#endif
/// Report a syntax error.
/// \param loc where the syntax error is found.
/// \param msg a description of the syntax error.
virtual void error (const location_type& loc, const std::string& msg);
/// Report a syntax error.
void error (const syntax_error& err);
private:
/// This class is not copyable.
SQLParser (const SQLParser&);
SQLParser& operator= (const SQLParser&);
/// State numbers.
typedef int state_type;
/// Generate an error message.
/// \param yystate the state where the error occurred.
/// \param yytoken the lookahead token type, or yyempty_.
virtual std::string yysyntax_error_ (state_type yystate,
symbol_number_type yytoken) const;
/// Compute post-reduction state.
/// \param yystate the current state
/// \param yysym the nonterminal to push on the stack
state_type yy_lr_goto_state_ (state_type yystate, int yysym);
/// Whether the given \c yypact_ value indicates a defaulted state.
/// \param yyvalue the value to check
static bool yy_pact_value_is_default_ (int yyvalue);
/// Whether the given \c yytable_ value indicates a syntax error.
/// \param yyvalue the value to check
static bool yy_table_value_is_error_ (int yyvalue);
static const signed char yypact_ninf_;
static const signed char yytable_ninf_;
/// Convert a scanner token number \a t to a symbol number.
static token_number_type yytranslate_ (int t);
// Tables.
// YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
// STATE-NUM.
static const short int yypact_[];
// YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
// Performed when YYTABLE does not specify something else to do. Zero
// means the default is an error.
static const unsigned char yydefact_[];
// YYPGOTO[NTERM-NUM].
static const signed char yypgoto_[];
// YYDEFGOTO[NTERM-NUM].
static const short int yydefgoto_[];
// YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
// positive, shift that token. If negative, reduce the rule whose
// number is the opposite. If YYTABLE_NINF, syntax error.
static const short int yytable_[];
static const short int yycheck_[];
// YYSTOS[STATE-NUM] -- The (internal number of the) accessing
// symbol of state STATE-NUM.
static const unsigned char yystos_[];
// YYR1[YYN] -- Symbol number of symbol that rule YYN derives.
static const unsigned char yyr1_[];
// YYR2[YYN] -- Number of symbols on the right hand side of rule YYN.
static const unsigned char yyr2_[];
/// Convert the symbol name \a n to a form suitable for a diagnostic.
static std::string yytnamerr_ (const char *n);
/// For a symbol, its name in clear.
static const char* const yytname_[];
#if YYDEBUG
// YYRLINE[YYN] -- Source line where rule number YYN was defined.
static const unsigned short int yyrline_[];
/// Report on the debug stream that the rule \a r is going to be reduced.
virtual void yy_reduce_print_ (int r);
/// Print the state stack on the debug stream.
virtual void yystack_print_ ();
// Debugging.
int yydebug_;
std::ostream* yycdebug_;
/// \brief Display a symbol type, value and location.
/// \param yyo The output stream.
/// \param yysym The symbol.
template <typename Base>
void yy_print_ (std::ostream& yyo, const basic_symbol<Base>& yysym) const;
#endif
/// \brief Reclaim the memory associated to a symbol.
/// \param yymsg Why this token is reclaimed.
/// If null, print nothing.
/// \param yysym The symbol.
template <typename Base>
void yy_destroy_ (const char* yymsg, basic_symbol<Base>& yysym) const;
private:
/// Type access provider for state based symbols.
struct by_state
{
/// Default constructor.
by_state ();
/// The symbol type as needed by the constructor.
typedef state_type kind_type;
/// Constructor.
by_state (kind_type s);
/// Copy constructor.
by_state (const by_state& other);
/// Steal the symbol type from \a that.
void move (by_state& that);
/// The (internal) type number (corresponding to \a state).
/// "empty" when empty.
symbol_number_type type_get () const;
enum { empty = 0 };
/// The state.
state_type state;
};
/// "Internal" symbol: element of the stack.
struct stack_symbol_type : basic_symbol<by_state>
{
/// Superclass.
typedef basic_symbol<by_state> super_type;
/// Construct an empty symbol.
stack_symbol_type ();
/// Steal the contents from \a sym to build this.
stack_symbol_type (state_type s, symbol_type& sym);
/// Assignment, needed by push_back.
stack_symbol_type& operator= (const stack_symbol_type& that);
};
/// Stack type.
typedef stack<stack_symbol_type> stack_type;
/// The stack.
stack_type yystack_;
/// Push a new state on the stack.
/// \param m a debug message to display
/// if null, no trace is output.
/// \param s the symbol
/// \warning the contents of \a s.value is stolen.
void yypush_ (const char* m, stack_symbol_type& s);
/// Push a new look ahead token on the state on the stack.
/// \param m a debug message to display
/// if null, no trace is output.
/// \param s the state
/// \param sym the symbol (for its value and location).
/// \warning the contents of \a s.value is stolen.
void yypush_ (const char* m, state_type s, symbol_type& sym);
/// Pop \a n symbols the three stacks.
void yypop_ (unsigned int n = 1);
// Constants.
enum
{
yyeof_ = 0,
yylast_ = 249, ///< Last index in yytable_.
yynnts_ = 25, ///< Number of nonterminal symbols.
yyempty_ = -2,
yyfinal_ = 36, ///< Termination state number.
yyterror_ = 1,
yyerrcode_ = 256,
yyntokens_ = 51 ///< Number of tokens.
};
// User arguments.
UCD::SQLScanner &scanner;
UCD::SQLDriver &driver;
};
#line 5 "sql_parser.yy" // lalr1.cc:372
} // UCD
#line 517 "sql_parser.tab.hh" // lalr1.cc:372
#endif // !YY_YY_SQL_PARSER_TAB_HH_INCLUDED
| mit |
itsJoKr/LocalNetwork | localnet/src/main/java/dev/jokr/localnet/discovery/models/DiscoveryRequest.java | 462 | package dev.jokr.localnet.discovery.models;
import java.io.Serializable;
/**
* Created by JoKr on 8/27/2016.
*/
public class DiscoveryRequest<T> implements Serializable {
private String name;
private T payload;
public DiscoveryRequest(String name, T payload) {
this.name = name;
this.payload = payload;
}
public String getName() {
return name;
}
public T getPayload() {
return payload;
}
}
| mit |
iseki-masaya/spongycastle | pkix/src/test/java/org/spongycastle/cms/test/NewEnvelopedDataTest.java | 59689 | package org.spongycastle.cms.test;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Arrays;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import javax.crypto.SecretKey;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import javax.crypto.spec.SecretKeySpec;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.spongycastle.asn1.ASN1InputStream;
import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.ASN1OctetString;
import org.spongycastle.asn1.ASN1Sequence;
import org.spongycastle.asn1.DEROctetString;
import org.spongycastle.asn1.DERSet;
import org.spongycastle.asn1.DERUTF8String;
import org.spongycastle.asn1.cms.Attribute;
import org.spongycastle.asn1.cms.AttributeTable;
import org.spongycastle.asn1.kisa.KISAObjectIdentifiers;
import org.spongycastle.asn1.nist.NISTObjectIdentifiers;
import org.spongycastle.asn1.ntt.NTTObjectIdentifiers;
import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.spongycastle.asn1.pkcs.RC2CBCParameter;
import org.spongycastle.asn1.x500.X500Name;
import org.spongycastle.asn1.x509.AlgorithmIdentifier;
import org.spongycastle.asn1.x509.Extension;
import org.spongycastle.cert.X509CertificateHolder;
import org.spongycastle.cert.jcajce.JcaX509CertificateHolder;
import org.spongycastle.cms.CMSAlgorithm;
import org.spongycastle.cms.CMSEnvelopedData;
import org.spongycastle.cms.CMSEnvelopedDataGenerator;
import org.spongycastle.cms.CMSException;
import org.spongycastle.cms.CMSProcessableByteArray;
import org.spongycastle.cms.KeyTransRecipientInformation;
import org.spongycastle.cms.OriginatorInfoGenerator;
import org.spongycastle.cms.OriginatorInformation;
import org.spongycastle.cms.PasswordRecipient;
import org.spongycastle.cms.PasswordRecipientInformation;
import org.spongycastle.cms.RecipientId;
import org.spongycastle.cms.RecipientInformation;
import org.spongycastle.cms.RecipientInformationStore;
import org.spongycastle.cms.SimpleAttributeTableGenerator;
import org.spongycastle.cms.bc.BcCMSContentEncryptorBuilder;
import org.spongycastle.cms.bc.BcRSAKeyTransRecipientInfoGenerator;
import org.spongycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
import org.spongycastle.cms.jcajce.JceKEKEnvelopedRecipient;
import org.spongycastle.cms.jcajce.JceKEKRecipientInfoGenerator;
import org.spongycastle.cms.jcajce.JceKeyAgreeEnvelopedRecipient;
import org.spongycastle.cms.jcajce.JceKeyAgreeRecipientId;
import org.spongycastle.cms.jcajce.JceKeyAgreeRecipientInfoGenerator;
import org.spongycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
import org.spongycastle.cms.jcajce.JceKeyTransRecipientId;
import org.spongycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;
import org.spongycastle.cms.jcajce.JcePasswordEnvelopedRecipient;
import org.spongycastle.cms.jcajce.JcePasswordRecipientInfoGenerator;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.operator.OutputEncryptor;
import org.spongycastle.operator.jcajce.JcaAlgorithmParametersConverter;
import org.spongycastle.util.encoders.Base64;
import org.spongycastle.util.encoders.Hex;
public class NewEnvelopedDataTest
extends TestCase
{
private static final String BC = BouncyCastleProvider.PROVIDER_NAME;
private static String _signDN;
private static KeyPair _signKP;
private static X509Certificate _signCert;
private static String _origDN;
private static KeyPair _origKP;
private static X509Certificate _origCert;
private static String _reciDN;
private static String _reciDN2;
private static KeyPair _reciKP;
private static KeyPair _reciOaepKP;
private static X509Certificate _reciCert;
private static X509Certificate _reciCertOaep;
private static KeyPair _origEcKP;
private static KeyPair _reciEcKP;
private static X509Certificate _reciEcCert;
private static KeyPair _reciEcKP2;
private static X509Certificate _reciEcCert2;
private static boolean _initialised = false;
private byte[] oldKEK = Base64.decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQIxQaI/MD0CAQQwBwQFAQIDBAUwDQYJYIZIAWUDBAEFBQAEI"
+ "Fi2eHTPM4bQSjP4DUeDzJZLpfemW2gF1SPq7ZPHJi1mMIAGCSqGSIb3DQEHATAUBggqhkiG9w"
+ "0DBwQImtdGyUdGGt6ggAQYk9X9z01YFBkU7IlS3wmsKpm/zpZClTceAAAAAAAAAAAAAA==");
private byte[] ecKeyAgreeMsgAES256 = Base64.decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQIxgcShgcECAQOgQ6FBMAsGByqGSM49AgEF"
+ "AAMyAAPdXlSTpub+qqno9hUGkUDl+S3/ABhPziIB5yGU4678tgOgU5CiKG9Z"
+ "kfnabIJ3nZYwGgYJK4EFEIZIPwACMA0GCWCGSAFlAwQBLQUAMFswWTAtMCgx"
+ "EzARBgNVBAMTCkFkbWluLU1EU0UxETAPBgNVBAoTCDRCQ1QtMklEAgEBBCi/"
+ "rJRLbFwEVW6PcLLmojjW9lI/xGD7CfZzXrqXFw8iHaf3hTRau1gYMIAGCSqG"
+ "SIb3DQEHATAdBglghkgBZQMEASoEEMtCnKKPwccmyrbgeSIlA3qggAQQDLw8"
+ "pNJR97bPpj6baG99bQQQwhEDsoj5Xg1oOxojHVcYzAAAAAAAAAAAAAA=");
private byte[] ecKeyAgreeMsgAES128 = Base64.decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQIxgbShgbECAQOgQ6FBMAsGByqGSM49AgEF"
+ "AAMyAAL01JLEgKvKh5rbxI/hOxs/9WEezMIsAbUaZM4l5tn3CzXAN505nr5d"
+ "LhrcurMK+tAwGgYJK4EFEIZIPwACMA0GCWCGSAFlAwQBBQUAMEswSTAtMCgx"
+ "EzARBgNVBAMTCkFkbWluLU1EU0UxETAPBgNVBAoTCDRCQ1QtMklEAgEBBBhi"
+ "FLjc5g6aqDT3f8LomljOwl1WTrplUT8wgAYJKoZIhvcNAQcBMB0GCWCGSAFl"
+ "AwQBAgQQzXjms16Y69S/rB0EbHqRMaCABBAFmc/QdVW6LTKdEy97kaZzBBBa"
+ "fQuviUS03NycpojELx0bAAAAAAAAAAAAAA==");
private byte[] ecKeyAgreeMsgDESEDE = Base64.decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQIxgcahgcMCAQOgQ6FBMAsGByqGSM49AgEF"
+ "AAMyAALIici6Nx1WN5f0ThH2A8ht9ovm0thpC5JK54t73E1RDzCifePaoQo0"
+ "xd6sUqoyGaYwHAYJK4EFEIZIPwACMA8GCyqGSIb3DQEJEAMGBQAwWzBZMC0w"
+ "KDETMBEGA1UEAxMKQWRtaW4tTURTRTERMA8GA1UEChMINEJDVC0ySUQCAQEE"
+ "KJuqZQ1NB1vXrKPOnb4TCpYOsdm6GscWdwAAZlm2EHMp444j0s55J9wwgAYJ"
+ "KoZIhvcNAQcBMBQGCCqGSIb3DQMHBAjwnsDMsafCrKCABBjyPvqFOVMKxxut"
+ "VfTx4fQlNGJN8S2ATRgECMcTQ/dsmeViAAAAAAAAAAAAAA==");
private byte[] ecMQVKeyAgreeMsgAES128 = Base64.decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQIxgf2hgfoCAQOgQ6FBMAsGByqGSM49AgEF"
+ "AAMyAAPDKU+0H58tsjpoYmYCInMr/FayvCCkupebgsnpaGEB7qS9vzcNVUj6"
+ "mrnmiC2grpmhRwRFMEMwQTALBgcqhkjOPQIBBQADMgACZpD13z9c7DzRWx6S"
+ "0xdbq3S+EJ7vWO+YcHVjTD8NcQDcZcWASW899l1PkL936zsuMBoGCSuBBRCG"
+ "SD8AEDANBglghkgBZQMEAQUFADBLMEkwLTAoMRMwEQYDVQQDEwpBZG1pbi1N"
+ "RFNFMREwDwYDVQQKEwg0QkNULTJJRAIBAQQYFq58L71nyMK/70w3nc6zkkRy"
+ "RL7DHmpZMIAGCSqGSIb3DQEHATAdBglghkgBZQMEAQIEEDzRUpreBsZXWHBe"
+ "onxOtSmggAQQ7csAZXwT1lHUqoazoy8bhAQQq+9Zjj8iGdOWgyebbfj67QAA"
+ "AAAAAAAAAAA=");
private byte[] ecKeyAgreeKey = Base64.decode(
"MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDC8vp7xVTbKSgYVU5Wc"
+ "hGkWbzaj+yUFETIWP1Dt7+WSpq3ikSPdl7PpHPqnPVZfoIWhZANiAgSYHTgxf+Dd"
+ "Tt84dUvuSKkFy3RhjxJmjwIscK6zbEUzKhcPQG2GHzXhWK5x1kov0I74XpGhVkya"
+ "ElH5K6SaOXiXAzcyNGggTOk4+ZFnz5Xl0pBje3zKxPhYu0SnCw7Pcqw=");
private byte[] bobPrivRsaEncrypt = Base64.decode(
"MIIChQIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKnhZ5g/OdVf"
+ "8qCTQV6meYmFyDVdmpFb+x0B2hlwJhcPvaUi0DWFbXqYZhRBXM+3twg7CcmR"
+ "uBlpN235ZR572akzJKN/O7uvRgGGNjQyywcDWVL8hYsxBLjMGAgUSOZPHPtd"
+ "YMTgXB9T039T2GkB8QX4enDRvoPGXzjPHCyqaqfrAgMBAAECgYBnzUhMmg2P"
+ "mMIbZf8ig5xt8KYGHbztpwOIlPIcaw+LNd4Ogngwy+e6alatd8brUXlweQqg"
+ "9P5F4Kmy9Bnah5jWMIR05PxZbMHGd9ypkdB8MKCixQheIXFD/A0HPfD6bRSe"
+ "TmPwF1h5HEuYHD09sBvf+iU7o8AsmAX2EAnYh9sDGQJBANDDIsbeopkYdo+N"
+ "vKZ11mY/1I1FUox29XLE6/BGmvE+XKpVC5va3Wtt+Pw7PAhDk7Vb/s7q/WiE"
+ "I2Kv8zHCueUCQQDQUfweIrdb7bWOAcjXq/JY1PeClPNTqBlFy2bKKBlf4hAr"
+ "84/sajB0+E0R9KfEILVHIdxJAfkKICnwJAiEYH2PAkA0umTJSChXdNdVUN5q"
+ "SO8bKlocSHseIVnDYDubl6nA7xhmqU5iUjiEzuUJiEiUacUgFJlaV/4jbOSn"
+ "I3vQgLeFAkEAni+zN5r7CwZdV+EJBqRd2ZCWBgVfJAZAcpw6iIWchw+dYhKI"
+ "FmioNRobQ+g4wJhprwMKSDIETukPj3d9NDAlBwJAVxhn1grStavCunrnVNqc"
+ "BU+B1O8BiR4yPWnLMcRSyFRVJQA7HCp8JlDV6abXd8vPFfXuC9WN7rOvTKF8"
+ "Y0ZB9qANMAsGA1UdDzEEAwIAEA==");
private byte[] rfc4134ex5_1 = Base64.decode(
"MIIBHgYJKoZIhvcNAQcDoIIBDzCCAQsCAQAxgcAwgb0CAQAwJjASMRAwDgYD"
+ "VQQDEwdDYXJsUlNBAhBGNGvHgABWvBHTbi7NXXHQMA0GCSqGSIb3DQEBAQUA"
+ "BIGAC3EN5nGIiJi2lsGPcP2iJ97a4e8kbKQz36zg6Z2i0yx6zYC4mZ7mX7FB"
+ "s3IWg+f6KgCLx3M1eCbWx8+MDFbbpXadCDgO8/nUkUNYeNxJtuzubGgzoyEd"
+ "8Ch4H/dd9gdzTd+taTEgS0ipdSJuNnkVY4/M652jKKHRLFf02hosdR8wQwYJ"
+ "KoZIhvcNAQcBMBQGCCqGSIb3DQMHBAgtaMXpRwZRNYAgDsiSf8Z9P43LrY4O"
+ "xUk660cu1lXeCSFOSOpOJ7FuVyU=");
private byte[] rfc4134ex5_2 = Base64.decode(
"MIIBZQYJKoZIhvcNAQcDoIIBVjCCAVICAQIxggEAMIG9AgEAMCYwEjEQMA4G"
+ "A1UEAxMHQ2FybFJTQQIQRjRrx4AAVrwR024uzV1x0DANBgkqhkiG9w0BAQEF"
+ "AASBgJQmQojGi7Z4IP+CVypBmNFoCDoEp87khtgyff2N4SmqD3RxPx+8hbLQ"
+ "t9i3YcMwcap+aiOkyqjMalT03VUC0XBOGv+HYI3HBZm/aFzxoq+YOXAWs5xl"
+ "GerZwTOc9j6AYlK4qXvnztR5SQ8TBjlzytm4V7zg+TGrnGVNQBNw47Ewoj4C"
+ "AQQwDQQLTWFpbExpc3RSQzIwEAYLKoZIhvcNAQkQAwcCAToEGHcUr5MSJ/g9"
+ "HnJVHsQ6X56VcwYb+OfojTBJBgkqhkiG9w0BBwEwGgYIKoZIhvcNAwIwDgIC"
+ "AKAECJwE0hkuKlWhgCBeKNXhojuej3org9Lt7n+wWxOhnky5V50vSpoYRfRR"
+ "yw==");
private byte[] tooShort3DES = Base64.decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQAxgcQwgcECAQAwKjAlMRYwFAYDVQQKDA1C" +
"b3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJBVQIBCjANBgkqhkiG9w0BAQEFAASB" +
"gJIM2QN0o6iv8Ux018pVCJ8js+ROV4t6+KoMwLJ4DzRKLU8XCAb9BS+crP+F" +
"ghNTxTpTX8TaxPrO4wV0USgVHu2SvFnxNaWZjBDVIyZI2HR4QkSTqFMhsUB2" +
"6CuZIWBZkhqQ6ruDfvn9UuBWVnfsBD4iryZ1idr713sDeVo5TyvTMIAGCSqG" +
"SIb3DQEHATAUBggqhkiG9w0DBwQIQq9e4+WB3CqggAQIwU4cOlmkWUcAAAAA" +
"AAAAAAAA");
private byte[] tooShort3DESKey = Base64.decode(
"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAODZDCj0nQdV" +
"f0GGeFsPjjvPx1Vem0V6IkJ4SzazGKfddk0pX58ZDCnG+S+OPiXmPDqValiu" +
"9FtNy2/r9rrf/6qtcVQJkfSJv9E5Y7HgI98L/Y9lKxZWsfRqu/SlYO5zx0Dc" +
"2rzDvvZRtrtaq0uuHXWJlbWda2L9S65sv/Le/zvjAgMBAAECgYEAnn+iGMTG" +
"ZMMaH6Cg+t/uTa9cPougPMuplt2hd3+sY7izihUeONK5RkHiqmlE2gaAcnOd" +
"McKysiIWxGC73mPEnsOObPkaFlneVb5CtjTaTMdptuLNEQkwvtKhuW2HnMra" +
"4afEgFZdll3FyRpvW/CDooe4Bppjd4aGn/Sr/o9nOzECQQD4QKLwZssuclji" +
"nD/8gU1CqGMMnGNogTMpHm1269HUOE7r1y3MuapUqSWsVhpuEQ8P/Tko0haJ" +
"jeZn2eWTbZu/AkEA591snui8FMeGvkRgvyMFNvXZWDEjsh+N74XEL1lykTgZ" +
"FQJ+cmThnrdM/8yj1dKkdASYrk5kFJ4PVE6CzDI43QJAFS22eNncJZc9u/9m" +
"eg0x4SjqYk4JMQYsripZXlbZ7Mfs+7O8xYVlYZmYjC5ATPmJlmyc7r2VjKCd" +
"cmilbEFikwJBAMh7yf8BaBdjitubzjeW9VxXaa37F01eQWD5PfBfHFP6uJ1V" +
"AbayCfAtuHN6I7OwJih3DPmyqJC3NrQECs67IjUCQAb4TfVE/2G1s66SGnb4" +
"no34BspoV/i4f0uLhJap84bTHcF/ZRSXCmQOCRGdSvQkXHeNPI5Lus6lOHuU" +
"vUDbQC8=");
public NewEnvelopedDataTest()
{
}
private static void init()
throws Exception
{
if (!_initialised)
{
_initialised = true;
Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
_signDN = "O=Bouncy Castle, C=AU";
_signKP = CMSTestUtil.makeKeyPair();
_signCert = CMSTestUtil.makeCertificate(_signKP, _signDN, _signKP, _signDN);
_origDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU";
_origKP = CMSTestUtil.makeKeyPair();
_origCert = CMSTestUtil.makeCertificate(_origKP, _origDN, _signKP, _signDN);
_reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU";
_reciDN2 = "CN=Fred, OU=Sales, O=Bouncy Castle, C=AU";
_reciKP = CMSTestUtil.makeKeyPair();
_reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN);
_reciCertOaep = CMSTestUtil.makeOaepCertificate(_reciKP, _reciDN, _signKP, _signDN);
_origEcKP = CMSTestUtil.makeEcDsaKeyPair();
_reciEcKP = CMSTestUtil.makeEcDsaKeyPair();
_reciEcCert = CMSTestUtil.makeCertificate(_reciEcKP, _reciDN, _signKP, _signDN);
_reciEcKP2 = CMSTestUtil.makeEcDsaKeyPair();
_reciEcCert2 = CMSTestUtil.makeCertificate(_reciEcKP2, _reciDN2, _signKP, _signDN);
}
}
public static void main(
String args[])
throws Exception
{
junit.textui.TestRunner.run(NewEnvelopedDataTest.suite());
}
public static Test suite()
throws Exception
{
init();
return new CMSTestSetup(new TestSuite(NewEnvelopedDataTest.class));
}
public void testUnprotectedAttributes()
throws Exception
{
byte[] data = "WallaWallaWashington".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));
Hashtable attrs = new Hashtable();
attrs.put(PKCSObjectIdentifiers.id_aa_contentHint, new Attribute(PKCSObjectIdentifiers.id_aa_contentHint, new DERSet(new DERUTF8String("Hint"))));
attrs.put(PKCSObjectIdentifiers.id_aa_receiptRequest, new Attribute(PKCSObjectIdentifiers.id_aa_receiptRequest, new DERSet(new DERUTF8String("Request"))));
AttributeTable attrTable = new AttributeTable(attrs);
edGen.setUnprotectedAttributeGenerator(new SimpleAttributeTableGenerator(attrTable));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
attrTable = ed.getUnprotectedAttributes();
assertEquals(attrs.size(), 2);
assertEquals(new DERUTF8String("Hint"), attrTable.get(PKCSObjectIdentifiers.id_aa_contentHint).getAttrValues().getObjectAt(0));
assertEquals(new DERUTF8String("Request"), attrTable.get(PKCSObjectIdentifiers.id_aa_receiptRequest).getAttrValues().getObjectAt(0));
Collection c = recipients.getRecipients();
assertEquals(1, c.size());
Iterator it = c.iterator();
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId());
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
}
public void testKeyTrans()
throws Exception
{
byte[] data = "WallaWallaWashington".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(ASN1OctetString.getInstance(ASN1OctetString.getInstance(_reciCert.getExtensionValue(Extension.subjectKeyIdentifier.getId())).getOctets()).getOctets(), _reciCert.getPublicKey()).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
Collection c = recipients.getRecipients();
assertEquals(2, c.size());
Iterator it = c.iterator();
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId());
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
RecipientId id = new JceKeyTransRecipientId(_reciCert);
Collection collection = recipients.getRecipients(id);
if (collection.size() != 2)
{
fail("recipients not matched using general recipient ID.");
}
assertTrue(collection.iterator().next() instanceof RecipientInformation);
}
public void testKeyTransOAEPDefault()
throws Exception
{
byte[] data = "WallaWallaWashington".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
JcaAlgorithmParametersConverter paramsConverter = new JcaAlgorithmParametersConverter();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert, paramsConverter.getAlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP, OAEPParameterSpec.DEFAULT)).setProvider(BC));
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(ASN1OctetString.getInstance(ASN1OctetString.getInstance(_reciCert.getExtensionValue(Extension.subjectKeyIdentifier.getId())).getOctets()).getOctets(), paramsConverter.getAlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP, OAEPParameterSpec.DEFAULT), _reciCert.getPublicKey()).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
Collection c = recipients.getRecipients();
assertEquals(2, c.size());
Iterator it = c.iterator();
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(PKCSObjectIdentifiers.id_RSAES_OAEP, recipient.getKeyEncryptionAlgorithm().getAlgorithm());
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
RecipientId id = new JceKeyTransRecipientId(_reciCert);
Collection collection = recipients.getRecipients(id);
if (collection.size() != 2)
{
fail("recipients not matched using general recipient ID.");
}
assertTrue(collection.iterator().next() instanceof RecipientInformation);
}
public void testKeyTransOAEPSHA1()
throws Exception
{
doTestKeyTransOAEPDefaultNamed("SHA-1");
}
public void testKeyTransOAEPSHA224()
throws Exception
{
doTestKeyTransOAEPDefaultNamed("SHA-224");
}
public void testKeyTransOAEPSHA256()
throws Exception
{
doTestKeyTransOAEPDefaultNamed("SHA-256");
}
public void testKeyTransOAEPSHA1AndSHA256()
throws Exception
{
doTestKeyTransOAEPDefaultNamed("SHA-1", "SHA-256");
}
private void doTestKeyTransOAEPDefaultNamed(String digest)
throws Exception
{
doTestKeyTransOAEPDefaultNamed(digest, digest);
}
private void doTestKeyTransOAEPDefaultNamed(String digest, String mgfDigest)
throws Exception
{
byte[] data = "WallaWallaWashington".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
JcaAlgorithmParametersConverter paramsConverter = new JcaAlgorithmParametersConverter();
OAEPParameterSpec oaepSpec = new OAEPParameterSpec(digest, "MGF1", new MGF1ParameterSpec(mgfDigest), new PSource.PSpecified(new byte[]{1, 2, 3, 4, 5}));
AlgorithmIdentifier oaepAlgId = paramsConverter.getAlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP, oaepSpec);
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert, oaepAlgId).setProvider(BC));
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(ASN1OctetString.getInstance(ASN1OctetString.getInstance(_reciCert.getExtensionValue(Extension.subjectKeyIdentifier.getId())).getOctets()).getOctets(), oaepAlgId, _reciCert.getPublicKey()).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
Collection c = recipients.getRecipients();
assertEquals(2, c.size());
Iterator it = c.iterator();
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(PKCSObjectIdentifiers.id_RSAES_OAEP, recipient.getKeyEncryptionAlgorithm().getAlgorithm());
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
RecipientId id = new JceKeyTransRecipientId(_reciCert);
Collection collection = recipients.getRecipients(id);
if (collection.size() != 2)
{
fail("recipients not matched using general recipient ID.");
}
assertTrue(collection.iterator().next() instanceof RecipientInformation);
}
public void testKeyTransOAEPInCert()
throws Exception
{
byte[] data = "WallaWallaWashington".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCertOaep).setProvider(BC));
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(ASN1OctetString.getInstance(ASN1OctetString.getInstance(_reciCertOaep.getExtensionValue(Extension.subjectKeyIdentifier.getId())).getOctets()).getOctets(), _reciCertOaep.getPublicKey()).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
Collection c = recipients.getRecipients();
assertEquals(2, c.size());
Iterator it = c.iterator();
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(PKCSObjectIdentifiers.id_RSAES_OAEP, recipient.getKeyEncryptionAlgorithm().getAlgorithm());
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
RecipientId id = new JceKeyTransRecipientId(_reciCertOaep);
Collection collection = recipients.getRecipients(id);
if (collection.size() != 2)
{
fail("recipients not matched using general recipient ID.");
}
assertTrue(collection.iterator().next() instanceof RecipientInformation);
}
public void testKeyTransWithAlgMapping()
throws Exception
{
byte[] data = "WallaWallaWashington".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setAlgorithmMapping(PKCSObjectIdentifiers.rsaEncryption, "RSA/2/PKCS1Padding").setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
Collection c = recipients.getRecipients();
assertEquals(1, c.size());
Iterator it = c.iterator();
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId());
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setAlgorithmMapping(PKCSObjectIdentifiers.rsaEncryption, "RSA/2/PKCS1Padding").setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
RecipientId id = new JceKeyTransRecipientId(_reciCert);
Collection collection = recipients.getRecipients(id);
if (collection.size() != 1)
{
fail("recipients not matched using general recipient ID.");
}
assertTrue(collection.iterator().next() instanceof RecipientInformation);
}
public void testOriginatorInfoGeneration()
throws Exception
{
byte[] data = "WallaWallaWashington".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
X509CertificateHolder origCert = new X509CertificateHolder(_origCert.getEncoded());
edGen.setOriginatorInfo(new OriginatorInfoGenerator(origCert).generate());
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(ASN1OctetString.getInstance(ASN1OctetString.getInstance(_reciCert.getExtensionValue(Extension.subjectKeyIdentifier.getId())).getOctets()).getOctets(), _reciCert.getPublicKey()).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
assertTrue(ed.getOriginatorInfo().getCertificates().getMatches(null).contains(origCert));
Collection c = recipients.getRecipients();
assertEquals(2, c.size());
Iterator it = c.iterator();
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId());
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
RecipientId id = new JceKeyTransRecipientId(_reciCert);
Collection collection = recipients.getRecipients(id);
if (collection.size() != 2)
{
fail("recipients not matched using general recipient ID.");
}
assertTrue(collection.iterator().next() instanceof RecipientInformation);
}
public void testKeyTransRC2bit40()
throws Exception
{
byte[] data = "WallaWallaBouncyCastle".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC, 40).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getContentEncryptionAlgorithm().getAlgorithm(), CMSAlgorithm.RC2_CBC);
RC2CBCParameter rc2P = RC2CBCParameter.getInstance(ed.getContentEncryptionAlgorithm().getParameters());
assertEquals(160, rc2P.getRC2ParameterVersion().intValue());
Collection c = recipients.getRecipients();
assertEquals(1, c.size());
Iterator it = c.iterator();
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
}
public void testKeyTransRC4()
throws Exception
{
byte[] data = "WallaWallaBouncyCastle".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.2.840.113549.3.4")).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), "1.2.840.113549.3.4");
Collection c = recipients.getRecipients();
assertEquals(1, c.size());
Iterator it = c.iterator();
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
}
public void testKeyTrans128RC4()
throws Exception
{
byte[] data = "WallaWallaBouncyCastle".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.2.840.113549.3.4"), 128).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), "1.2.840.113549.3.4");
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
public void testKeyTransLight128RC4()
throws Exception
{
byte[] data = "WallaWallaBouncyCastle".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.2.840.113549.3.4"), 128).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), "1.2.840.113549.3.4");
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
public void testKeyTransODES()
throws Exception
{
byte[] data = "WallaWallaBouncyCastle".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier("1.3.14.3.2.7")).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), "1.3.14.3.2.7");
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
public void testKeyTransSmallAES()
throws Exception
{
byte[] data = new byte[] { 0, 1, 2, 3 };
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(),
CMSEnvelopedDataGenerator.AES128_CBC);
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
public void testKeyTransDESEDE3Short()
throws Exception
{
byte[] data = new byte[] { 0, 1, 2, 3 };
KeyFactory kf = KeyFactory.getInstance("RSA", BC);
PrivateKey kPriv = kf.generatePrivate(new PKCS8EncodedKeySpec(tooShort3DESKey));
CMSEnvelopedData ed = new CMSEnvelopedData(tooShort3DES);
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
try
{
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(kPriv).setKeySizeValidation(true).setProvider(BC));
fail("invalid 3DES-EDE key not picked up");
}
catch (CMSException e)
{
assertEquals("Expected key size for algorithm OID not found in recipient.", e.getMessage());
}
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(kPriv).setKeySizeValidation(false).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
public void testKeyTransDESEDE3Light()
throws Exception
{
byte[] data = new byte[] { 0, 1, 2, 3 };
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder(_reciCert)));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new BcCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC, 192).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setKeySizeValidation(true).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
public void testKeyTransDES()
throws Exception
{
tryKeyTrans(CMSAlgorithm.DES_CBC, CMSAlgorithm.DES_CBC, 8, DEROctetString.class);
}
public void testKeyTransCAST5()
throws Exception
{
tryKeyTrans(CMSAlgorithm.CAST5_CBC, CMSAlgorithm.CAST5_CBC, 16, ASN1Sequence.class);
}
public void testKeyTransAES128()
throws Exception
{
tryKeyTrans(CMSAlgorithm.AES128_CBC, NISTObjectIdentifiers.id_aes128_CBC, 16, DEROctetString.class);
}
public void testKeyTransAES192()
throws Exception
{
tryKeyTrans(CMSAlgorithm.AES192_CBC, NISTObjectIdentifiers.id_aes192_CBC, 24, DEROctetString.class);
}
public void testKeyTransAES256()
throws Exception
{
tryKeyTrans(CMSAlgorithm.AES256_CBC, NISTObjectIdentifiers.id_aes256_CBC, 32, DEROctetString.class);
}
public void testKeyTransSEED()
throws Exception
{
tryKeyTrans(CMSAlgorithm.SEED_CBC, KISAObjectIdentifiers.id_seedCBC, 16, DEROctetString.class);
}
public void testKeyTransCamellia128()
throws Exception
{
tryKeyTrans(CMSAlgorithm.CAMELLIA128_CBC, NTTObjectIdentifiers.id_camellia128_cbc, 16, DEROctetString.class);
}
public void testKeyTransCamellia192()
throws Exception
{
tryKeyTrans(CMSAlgorithm.CAMELLIA192_CBC, NTTObjectIdentifiers.id_camellia192_cbc, 24, DEROctetString.class);
}
public void testKeyTransCamellia256()
throws Exception
{
tryKeyTrans(CMSAlgorithm.CAMELLIA256_CBC, NTTObjectIdentifiers.id_camellia256_cbc, 32, DEROctetString.class);
}
private void tryKeyTrans(ASN1ObjectIdentifier generatorOID, ASN1ObjectIdentifier checkOID, int keySize, Class asn1Params)
throws Exception
{
byte[] data = "WallaWallaWashington".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));
OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(generatorOID).setProvider(BC).build();
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
encryptor);
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(checkOID.getId(), ed.getEncryptionAlgOID());
assertEquals(keySize, ((byte[])encryptor.getKey().getRepresentation()).length);
if (asn1Params != null)
{
ASN1InputStream aIn = new ASN1InputStream(ed.getEncryptionAlgParams());
assertTrue(asn1Params.isAssignableFrom(aIn.readObject().getClass()));
}
Collection c = recipients.getRecipients();
assertEquals(1, c.size());
Iterator it = c.iterator();
if (!it.hasNext())
{
fail("no recipients found");
}
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId());
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setKeySizeValidation(true).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
}
public void testErroneousKEK()
throws Exception
{
byte[] data = "WallaWallaWashington".getBytes();
SecretKey kek = new SecretKeySpec(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, "AES");
CMSEnvelopedData ed = new CMSEnvelopedData(oldKEK);
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(recipient.getKeyEncryptionAlgOID(), NISTObjectIdentifiers.id_aes128_wrap.getId());
byte[] recData = recipient.getContent(new JceKEKEnvelopedRecipient(kek).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
public void testDESKEK()
throws Exception
{
tryKekAlgorithm(CMSTestUtil.makeDesede192Key(), new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.3.6"));
}
public void testRC2128KEK()
throws Exception
{
tryKekAlgorithm(CMSTestUtil.makeRC2128Key(), new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.3.7"));
}
public void testAES128KEK()
throws Exception
{
tryKekAlgorithm(CMSTestUtil.makeAESKey(128), NISTObjectIdentifiers.id_aes128_wrap);
}
public void testAES192KEK()
throws Exception
{
tryKekAlgorithm(CMSTestUtil.makeAESKey(192), NISTObjectIdentifiers.id_aes192_wrap);
}
public void testAES256KEK()
throws Exception
{
tryKekAlgorithm(CMSTestUtil.makeAESKey(256), NISTObjectIdentifiers.id_aes256_wrap);
}
public void testSEED128KEK()
throws Exception
{
tryKekAlgorithm(CMSTestUtil.makeSEEDKey(), KISAObjectIdentifiers.id_npki_app_cmsSeed_wrap);
}
public void testCamellia128KEK()
throws Exception
{
tryKekAlgorithm(CMSTestUtil.makeCamelliaKey(128), NTTObjectIdentifiers.id_camellia128_wrap);
}
public void testCamellia192KEK()
throws Exception
{
tryKekAlgorithm(CMSTestUtil.makeCamelliaKey(192), NTTObjectIdentifiers.id_camellia192_wrap);
}
public void testCamellia256KEK()
throws Exception
{
tryKekAlgorithm(CMSTestUtil.makeCamelliaKey(256), NTTObjectIdentifiers.id_camellia256_wrap);
}
private void tryKekAlgorithm(SecretKey kek, ASN1ObjectIdentifier algOid)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
byte[] data = "WallaWallaWashington".getBytes();
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
byte[] kekId = new byte[] { 1, 2, 3, 4, 5 };
edGen.addRecipientInfoGenerator(new JceKEKRecipientInfoGenerator(kekId, kek).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC);
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals(algOid.getId(), recipient.getKeyEncryptionAlgOID());
byte[] recData = recipient.getContent(new JceKEKEnvelopedRecipient(kek).setKeySizeValidation(true).setProvider(BC));
assertTrue(Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
public void testECKeyAgree()
throws Exception
{
byte[] data = Hex.decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyAgreeRecipientInfoGenerator(CMSAlgorithm.ECDH_SHA1KDF,
_origEcKP.getPrivate(), _origEcKP.getPublic(),
CMSAlgorithm.AES128_WRAP).addRecipient(_reciEcCert).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.AES128_CBC);
RecipientInformationStore recipients = ed.getRecipientInfos();
confirmDataReceived(recipients, data, _reciEcCert, _reciEcKP.getPrivate(), BC);
confirmNumberRecipients(recipients, 1);
}
public void testECMQVKeyAgree()
throws Exception
{
byte[] data = Hex.decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JceKeyAgreeRecipientInfoGenerator(CMSAlgorithm.ECMQV_SHA1KDF,
_origEcKP.getPrivate(), _origEcKP.getPublic(),
CMSAlgorithm.AES128_WRAP).addRecipient(_reciEcCert).setProvider(BC));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.AES128_CBC);
RecipientInformationStore recipients = ed.getRecipientInfos();
confirmDataReceived(recipients, data, _reciEcCert, _reciEcKP.getPrivate(), BC);
confirmNumberRecipients(recipients, 1);
}
public void testECMQVKeyAgreeMultiple()
throws Exception
{
byte[] data = Hex.decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
JceKeyAgreeRecipientInfoGenerator recipientGenerator = new JceKeyAgreeRecipientInfoGenerator(CMSAlgorithm.ECMQV_SHA1KDF,
_origEcKP.getPrivate(), _origEcKP.getPublic(), CMSAlgorithm.AES128_WRAP).setProvider(BC);
recipientGenerator.addRecipient(_reciEcCert);
recipientGenerator.addRecipient(_reciEcCert2);
edGen.addRecipientInfoGenerator(recipientGenerator);
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
assertEquals(ed.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.AES128_CBC);
RecipientInformationStore recipients = ed.getRecipientInfos();
confirmDataReceived(recipients, data, _reciEcCert, _reciEcKP.getPrivate(), BC);
confirmDataReceived(recipients, data, _reciEcCert2, _reciEcKP2.getPrivate(), BC);
confirmNumberRecipients(recipients, 2);
}
private static void confirmDataReceived(RecipientInformationStore recipients,
byte[] expectedData, X509Certificate reciCert, PrivateKey reciPrivKey, String provider)
throws CMSException, NoSuchProviderException, CertificateEncodingException, IOException
{
RecipientId rid = new JceKeyAgreeRecipientId(reciCert);
RecipientInformation recipient = recipients.get(rid);
assertNotNull(recipient);
byte[] actualData = recipient.getContent(new JceKeyAgreeEnvelopedRecipient(reciPrivKey).setProvider(provider));
assertEquals(true, Arrays.equals(expectedData, actualData));
}
private static void confirmNumberRecipients(RecipientInformationStore recipients, int count)
{
assertEquals(count, recipients.getRecipients().size());
}
public void testECKeyAgreeVectors()
throws Exception
{
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(ecKeyAgreeKey);
KeyFactory fact = KeyFactory.getInstance("ECDH", BC);
PrivateKey privKey = fact.generatePrivate(privSpec);
verifyECKeyAgreeVectors(privKey, "2.16.840.1.101.3.4.1.42", ecKeyAgreeMsgAES256);
verifyECKeyAgreeVectors(privKey, "2.16.840.1.101.3.4.1.2", ecKeyAgreeMsgAES128);
verifyECKeyAgreeVectors(privKey, "1.2.840.113549.3.7", ecKeyAgreeMsgDESEDE);
}
public void testECMQVKeyAgreeVectors()
throws Exception
{
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(ecKeyAgreeKey);
KeyFactory fact = KeyFactory.getInstance("ECDH", BC);
PrivateKey privKey = fact.generatePrivate(privSpec);
verifyECMQVKeyAgreeVectors(privKey, "2.16.840.1.101.3.4.1.2", ecMQVKeyAgreeMsgAES128);
}
public void testPasswordAES256()
throws Exception
{
passwordTest(CMSEnvelopedDataGenerator.AES256_CBC);
passwordUTF8Test(CMSEnvelopedDataGenerator.AES256_CBC);
}
public void testPasswordDESEDE()
throws Exception
{
passwordTest(CMSEnvelopedDataGenerator.DES_EDE3_CBC);
passwordUTF8Test(CMSEnvelopedDataGenerator.DES_EDE3_CBC);
}
public void testRFC4134ex5_1()
throws Exception
{
byte[] data = Hex.decode("5468697320697320736f6d652073616d706c6520636f6e74656e742e");
KeyFactory kFact = KeyFactory.getInstance("RSA", BC);
Key key = kFact.generatePrivate(new PKCS8EncodedKeySpec(bobPrivRsaEncrypt));
CMSEnvelopedData ed = new CMSEnvelopedData(rfc4134ex5_1);
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals("1.2.840.113549.3.7", ed.getEncryptionAlgOID());
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JceKeyTransEnvelopedRecipient((PrivateKey)key).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
public void testRFC4134ex5_2()
throws Exception
{
byte[] data = Hex.decode("5468697320697320736f6d652073616d706c6520636f6e74656e742e");
KeyFactory kFact = KeyFactory.getInstance("RSA", BC);
PrivateKey key = kFact.generatePrivate(new PKCS8EncodedKeySpec(bobPrivRsaEncrypt));
CMSEnvelopedData ed = new CMSEnvelopedData(rfc4134ex5_2);
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals("1.2.840.113549.3.2", ed.getEncryptionAlgOID());
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData;
if (recipient instanceof KeyTransRecipientInformation)
{
recData = recipient.getContent(new JceKeyTransEnvelopedRecipient(key).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
}
}
else
{
fail("no recipient found");
}
}
public void testOriginatorInfo()
throws Exception
{
CMSEnvelopedData env = new CMSEnvelopedData(CMSSampleMessages.originatorMessage);
RecipientInformationStore recipients = env.getRecipientInfos();
OriginatorInformation origInfo = env.getOriginatorInfo();
assertEquals(new X500Name("C=US,O=U.S. Government,OU=HSPD12Lab,OU=Agents,CN=user1"), ((X509CertificateHolder)origInfo.getCertificates().getMatches(null).iterator().next()).getSubject());
assertEquals(CMSEnvelopedDataGenerator.DES_EDE3_CBC, env.getEncryptionAlgOID());
}
private void passwordTest(String algorithm)
throws Exception
{
byte[] data = Hex.decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JcePasswordRecipientInfoGenerator(new ASN1ObjectIdentifier(algorithm), "password".toCharArray()).setProvider(BC).setPasswordConversionScheme(PasswordRecipient.PKCS5_SCHEME2).setSaltAndIterationCount(new byte[20], 5));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(),
CMSEnvelopedDataGenerator.AES128_CBC);
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
PasswordRecipientInformation recipient = (PasswordRecipientInformation)it.next();
byte[] recData = recipient.getContent(new JcePasswordEnvelopedRecipient("password".toCharArray()).setPasswordConversionScheme(PasswordRecipient.PKCS5_SCHEME2).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
//
// try algorithm parameters constructor
//
it = c.iterator();
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JcePasswordEnvelopedRecipient("password".toCharArray()).setPasswordConversionScheme(PasswordRecipient.PKCS5_SCHEME2).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
private void passwordUTF8Test(String algorithm)
throws Exception
{
byte[] data = Hex.decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");
CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
edGen.addRecipientInfoGenerator(new JcePasswordRecipientInfoGenerator(new ASN1ObjectIdentifier(algorithm), "abc\u5639\u563b".toCharArray()).setProvider(BC).setSaltAndIterationCount(new byte[20], 5));
CMSEnvelopedData ed = edGen.generate(
new CMSProcessableByteArray(data),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
RecipientInformationStore recipients = ed.getRecipientInfos();
assertEquals(ed.getEncryptionAlgOID(),
CMSEnvelopedDataGenerator.AES128_CBC);
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JcePasswordEnvelopedRecipient("abc\u5639\u563b".toCharArray()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
//
// try algorithm parameters constructor
//
it = c.iterator();
RecipientInformation recipient = (RecipientInformation)it.next();
byte[] recData = recipient.getContent(new JcePasswordEnvelopedRecipient("abc\u5639\u563b".toCharArray()).setProvider(BC));
assertEquals(true, Arrays.equals(data, recData));
}
private void verifyECKeyAgreeVectors(PrivateKey privKey, String wrapAlg, byte[] message)
throws CMSException, GeneralSecurityException
{
byte[] data = Hex.decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");
CMSEnvelopedData ed = new CMSEnvelopedData(message);
RecipientInformationStore recipients = ed.getRecipientInfos();
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
assertEquals(wrapAlg, ed.getEncryptionAlgOID());
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals("1.3.133.16.840.63.0.2", recipient.getKeyEncryptionAlgOID());
byte[] recData = recipient.getContent(new JceKeyAgreeEnvelopedRecipient(privKey).setProvider(BC));
assertTrue(Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
private void verifyECMQVKeyAgreeVectors(PrivateKey privKey, String wrapAlg, byte[] message)
throws CMSException, GeneralSecurityException
{
byte[] data = Hex.decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");
CMSEnvelopedData ed = new CMSEnvelopedData(message);
RecipientInformationStore recipients = ed.getRecipientInfos();
Collection c = recipients.getRecipients();
Iterator it = c.iterator();
assertEquals(wrapAlg, ed.getEncryptionAlgOID());
if (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
assertEquals("1.3.133.16.840.63.0.16", recipient.getKeyEncryptionAlgOID());
byte[] recData = recipient.getContent(new JceKeyAgreeEnvelopedRecipient(privKey).setProvider(BC));
assertTrue(Arrays.equals(data, recData));
}
else
{
fail("no recipient found");
}
}
} | mit |
estorski/langlay | Langlay.Common/WindowsTheme.cs | 105 | namespace Product.Common {
public enum WindowsTheme {
Dark = 0,
Light = 1
}
}
| mit |
badboy/travis-after-all-rs | src/main.rs | 1853 | extern crate travis_after_all;
use std::process;
use std::error::Error as StdError;
use travis_after_all::{Build, Error};
fn human<T>(val: Result<T, Error>) -> T {
match val {
Ok(val) => val,
Err(e) => {
println!("travis_after_all failed.");
println!("");
println!("Error: {}", e.description());
process::exit(1);
}
}
}
fn main() {
let config = human(Build::from_env());
if config.is_leader() {
println!("I'm the leader.");
println!("Waiting for others to finish");
match config.wait_for_others() {
Ok(()) => println!("Build finished. Now it's my time"),
Err(Error::NotLeader) => {
println!("I'm not the leader. Bailing out.");
process::exit(3);
},
Err(Error::FailedBuilds) => {
println!("Some builds failed. Stopping here.");
process::exit(2);
},
Err(e) => {
println!("travis_after_all failed.");
println!("");
println!("Error: {}", e.description());
process::exit(1);
}
}
let matrix = config.build_matrix();
if let Ok(matrix) = matrix {
for build in matrix.builds() {
println!("== Build {}", build.id());
println!("Leader: {}", build.is_leader());
println!("Finished: {}", build.is_finished());
println!("Succeeded: {}", build.is_succeeded());
println!("==");
println!("");
}
println!("Matrix all except master finished: {}", matrix.others_finished());
println!("Matrix all except master succeeded: {}", matrix.others_succeeded());
}
}
}
| mit |
Slaiiz/Atom-42Header | lib/header-42.js | 1196 | 'use babel';
import {CompositeDisposable} from 'atom';
import {HeaderManager} from './header-manager';
import * as configSchema from './config-schema';
export default {
subscriptions: null,
config: configSchema,
activate(state) {
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.commands.add('atom-workspace', {
'header-42:create': () => this.create(),
'header-42:update': () => this.update()
}));
this.subscriptions.add(atom.workspace.observeTextEditors(
(editor) => makeNewManager(editor)
));
},
deactivate() {
this.subscriptions.dispose();
},
create() {
var current = atom.workspace.getActiveTextEditor();
editors.forEach(
(item) => item.editor == current && item.create());
},
update() {
var current = atom.workspace.getActiveTextEditor();
editors.forEach(
(item) => item.editor == current && item.update());
}
}
function makeNewManager(editor) {
var manager = new HeaderManager(editor);
manager.onDestroy = function(editor) {
editors.forEach(
(item, i) => item.editor == editor && editors.splice(i, 1));
}
editors.push(manager);
}
editors = [];
| mit |
judgegrubb/gopl-book | ch3/basename2.go | 307 | // Package basename removes directory componenets and a .suffix
package basename
import "strings"
func basename(s string) string {
slash := strings.LastIndex(s, "/") // -1 if "/" not found
s = s[slash+1:]
if dot := strings.LastIndex(s, "."); dot >= 0 {
s = s[:dot]
}
return s
} | mit |
meantheory/dotfiles | dos/src/dos/roles/role.py | 713 | from dos.providers import Provider
class Role:
def __init__(self, **kwargs):
self.cfg = {}
ctx = self.ctx
for k, v in kwargs.items():
self.cfg[k] = v
@property
def ctx(self):
return self.ns()
def ns(self):
return "role"
def role_setup(self):
pass
class Plans:
def __init__(self, *provider_instances):
self.plans = []
for plan in provider_instances:
if isinstance(plan, Provider):
self.plans.append(plan)
else:
raise ValueError("????#?$$@#$")
def __iter__(self):
for provider_instance in self.plans:
yield provider_instance
| mit |
LeviOfficalDriftingRealmsDev/DriftingRealmsWorldEditor | Include/NavigationMesh.hpp | 2094 | #pragma once
#include "GlobalVars.hpp"
#include "../TrollGameEngine/TrollFileSystem/FileHelp.hpp"
#include "NavMapLoadData.hpp"
using namespace TPath;
class NavigationMesh{
public:
NavigationMesh();
~NavigationMesh();
void Draw(Canvas &c, const int cam_x,const int cam_y,const float zoom);
bool Extrude(const int Line_Start_Id,const TMath::Point new_pos2,const TMath::Point new_pos1);
void Extrude(const int Point_Start_Id,const TMath::Point new_pos);
bool ExtrudeMerge(const int Line_Start_Id,const int snap_to_edge);
void Input(const clan::InputEvent &e,const int cam_x,const int cam_y, const float zoom);
std::vector<NavSaveLoadPoint> points;
std::vector<NavSaveLoadEdge> edges;
std::vector<NavSaveLoadTriangle> quads;
TMath::Point placment_point_a = TMath::Point(-100,-100);
TMath::Point placment_point_b = TMath::Point(-100,-100);
std::vector<TMath::Point> placment_points_a;
std::vector<TMath::Point> placment_points_b;
std::vector<TMath::Point> placment_points;
std::vector<int> edges_selected;
std::vector<int> points_selected;
bool is_point_selected = false;
bool Selection(const clan::InputEvent &e,const int cam_x,const int cam_y, const float zoom);
bool SelectionEdge(const clan::InputEvent &e,const int cam_x,const int cam_y, const float zoom);
bool is_extruding = false;
bool GetShortestTwoLines(const TMath::Point point_a,const TMath::Point point_b,const TMath::Point point_c,const TMath::Point point_d);
void MakeFace(const int edge1,const int edge2,const int edge3);
void MakeEdge(const int point_1,const int point_2);
void EraseEdge(const int i);
void ErasePoint(const int i);
void Save(clan::File &file);
void LoadFrom(TPath::NavSaveLoadData &data);
void GeneratePiece();
void MovedPiece(int i);
void CircleSelect(const int cam_x,const int cam_y, const float zoom);
Rectf GenerateBoundery();
Rectf MirrorX(Rectf map_rect);
void RemoveDoubles();
Vec2f CursorLoc;
bool circle_select = false;
int circle_select_radius = 10;
};
| mit |
iwaco/shja | test/parser/hc_test.rb | 10676 | require 'test_helper'
class ShjaParserHcIndexPageTest < Minitest::Test
def setup
@index_page = open(File.join(HC_FIXTURES_ROOT, 'models.2.html')).read
@parser = Shja::Parser::HcIndexPage.new(@index_page)
end
NAMES = [
"Sabina Sinn",
"Sable",
"Sabrina Alvez",
"Sabrina Xavier and Rafa",
"Sai & Alice",
"Saki",
"Sasha Skyes",
"Saya Koda",
"Sayaka",
"Sayaka Ayasaki",
"Sayaka Kohaku",
"Sayaka Taniguchi",
"Seira Mikami",
"Sena Kasaiwazaki",
"Serina",
"Sharon Fox & Bruno",
"Shay",
"Sheeba",
"Shiho Kanda",
"Shion Suzuhara",
"Shizuka Momose",
"Sienna Grace",
"Sofia Ferreira",
"Sofie",
]
IDS = [
"sabina-sinn",
"sable",
"sabrina-alvez",
"sabrina-xavier-and-rafa",
"sai--alice",
"saki",
"sasha-skyes",
"saya-koda",
"sayaka",
"sayaka-ayasaki",
"sayaka-kohaku",
"sayaka-taniguchi",
"seira-mikami",
"sena-kasaiwazaki",
"serina",
"sharon-fox--bruno",
"shay",
"sheeba",
"shiho-kanda",
"shion-suzuhara",
"shizuka-momose",
"sienna-grace",
"sofia-ferreira",
"sofie",
]
URLS = [
"http://ex.shemalejapanhardcore.com/members/models/sabina-sinn.html",
"http://ex.shemalejapanhardcore.com/members/models/sable.html",
"http://ex.shemalejapanhardcore.com/members/models/sabrina-alvez.html",
"http://ex.shemalejapanhardcore.com/members/models/sabrina-xavier-and-rafa.html",
"http://ex.shemalejapanhardcore.com/members/models/sai--alice.html",
"http://ex.shemalejapanhardcore.com/members/models/saki.html",
"http://ex.shemalejapanhardcore.com/members/models/sasha-skyes.html",
"http://ex.shemalejapanhardcore.com/members/models/saya-koda.html",
"http://ex.shemalejapanhardcore.com/members/models/sayaka.html",
"http://ex.shemalejapanhardcore.com/members/models/sayaka-ayasaki.html",
"http://ex.shemalejapanhardcore.com/members/models/sayaka-kohaku.html",
"http://ex.shemalejapanhardcore.com/members/models/sayaka-taniguchi.html",
"http://ex.shemalejapanhardcore.com/members/models/seira-mikami.html",
"http://ex.shemalejapanhardcore.com/members/models/sena-kasaiwazaki.html",
"http://ex.shemalejapanhardcore.com/members/models/serina.html",
"http://ex.shemalejapanhardcore.com/members/models/sharon-fox--bruno.html",
"http://ex.shemalejapanhardcore.com/members/models/shay.html",
"http://ex.shemalejapanhardcore.com/members/models/sheeba.html",
"http://ex.shemalejapanhardcore.com/members/models/shiho-kanda.html",
"http://ex.shemalejapanhardcore.com/members/models/shion-suzuhara.html",
"http://ex.shemalejapanhardcore.com/members/models/shizuka-momose.html",
"http://ex.shemalejapanhardcore.com/members/models/sienna-grace.html",
"http://ex.shemalejapanhardcore.com/members/models/sofia-ferreira.html",
"http://ex.shemalejapanhardcore.com/members/models/sofie.html",
]
THUMBNAILS = [
"http://ex.shemalejapanhardcore.com/images/p16.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2902-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2904-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2906-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2908-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2910-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/3176-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2912-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2915-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2917-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2918-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2921-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2923-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/3138-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2927-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/3140-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2930-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2932-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2935-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2936-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2938-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2940-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/3142-set.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2944-set.jpg",
]
def test_parse
actors = @parser.parse_actors
assert_equal(NAMES.size, actors.size)
actors.each_with_index do |actor, i|
assert_equal(IDS[i], actor['id'])
assert_equal(NAMES[i], actor['name'])
assert_equal(URLS[i], actor['url'])
assert_equal(THUMBNAILS[i], actor['thumbnail'])
end
end
PAGES = [
"http://ex.shemalejapanhardcore.com/members/categories/models/1/name/S/",
"http://ex.shemalejapanhardcore.com/members/categories/models/2/name/S/",
]
def test_parse_pagination
pages = @parser.parse_pagination
assert_equal(PAGES, pages)
end
end
class ShjaParserHcActorPageTest < Minitest::Test
def setup
@lisa_html = open(File.join(HC_FIXTURES_ROOT, 'lisa.html')).read
@parser = Shja::Parser::HcActorPage.new(@lisa_html)
@page = Nokogiri::HTML.parse(@lisa_html)
end
def test_parse_actor
actor = @parser.parse_actor
assert_kind_of(Hash, actor)
assert_equal('Lisa', actor['name'])
assert_equal('http://ex.shemalejapanhardcore.com/members/content/contentthumbs/2761-set.jpg', actor['thumbnail'])
end
def test_parse_movies
movies = @parser.parse_movies
assert_kind_of(Array, movies)
assert_equal(5, movies.size)
movies.each_with_index do |movie, i|
assert_kind_of(Hash, movie)
assert_equal(TITLES[i], movie['title'])
assert_equal(PHOTOSET_URLS[i], movie['photoset_url'])
assert_equal(MOVIE_URLS[i], movie['url'])
assert_equal(DATES[i], movie['date'].to_s)
end
end
def test__split_photoset_and_movie
divs = @parser._split_photoset_and_movie(@page)
assert_equal(2, divs.size)
end
TITLES = [
"Girl Next Door Lisa",
"Lisa's After School Delight",
"Lisa's Stimulating Guys",
"Friends With Benefits For Lisa",
"Down-To-Earth Lisa",
]
PHOTOSET_URLS = [
"http://ex.shemalejapanhardcore.com/members/scenes/Girl-Next-Door-Lisa_highres.html",
"http://ex.shemalejapanhardcore.com/members/scenes/Lisas-After-School-Delight_highres.html",
"http://ex.shemalejapanhardcore.com/members/scenes/Lisas-Stimulating-Guys_highres.html",
"http://ex.shemalejapanhardcore.com/members/scenes/Friends-With-Benefits-For-Lisa_highres.html",
"http://ex.shemalejapanhardcore.com/members/scenes/Down-To-Earth-Lisa_highres.html",
]
MOVIE_URLS = [
"http://ex.shemalejapanhardcore.com/members/scenes/Girl-Next-Door-Lisa_vids.html",
"http://ex.shemalejapanhardcore.com/members/scenes/Lisas-After-School-Delight_vids.html",
"http://ex.shemalejapanhardcore.com/members/scenes/Lisas-Stimulating-Guys_vids.html",
"http://ex.shemalejapanhardcore.com/members/scenes/Friends-With-Benefits-For-Lisa_vids.html",
"http://ex.shemalejapanhardcore.com/members/scenes/Down-To-Earth-Lisa_vids.html",
]
THUMBNAILS = [
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/4427.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/4435.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/4447.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/4455.jpg",
"http://ex.shemalejapanhardcore.com/members/content/contentthumbs/4462.jpg",
]
DATES = [
"2013-04-04",
"2012-10-25",
"2012-08-16",
"2012-01-06",
"2011-02-04",
]
def test__parse_photosets
sets, _ = @page.css('div.pattern_span')
sets = @parser._parse_set_div(sets)
assert_equal(5, sets.size)
sets.each_with_index do |set, i|
assert_kind_of(Hash, set)
assert_equal(TITLES[i], set['title'])
assert_equal(PHOTOSET_URLS[i], set['url'])
assert_equal(DATES[i], set['date'].to_s)
end
end
def test__parse_set_div
_, sets = @page.css('div.pattern_span')
sets = @parser._parse_set_div(sets)
assert_equal(5, sets.size)
sets.each_with_index do |set, i|
assert_kind_of(Hash, set)
assert_equal(TITLES[i], set['title'])
assert_equal(MOVIE_URLS[i], set['url'])
assert_equal(DATES[i], set['date'].to_s)
end
end
end
class ShjaParserHcZipPageTest < Minitest::Test
def setup
@zip_html = open(File.join(HC_FIXTURES_ROOT, 'uta.zip.html')).read
@parser = Shja::Parser::HcZipPage.new(@zip_html)
end
def test_parse_zip_url
zip_url = @parser.parse_zip_url
assert_equal('http://ex.shemalejapanhardcore.com/members/content/upload/uta/151224/151224_1440highres.zip', zip_url)
end
def test_parse_pictures
pictures = @parser.parse_pictures[:pictures]
assert_equal(30, pictures.size)
pictures.each_with_index do |pict, i|
assert_equal("http://ex.shemalejapanhardcore.com/members/content/upload/uta/151224/photos/UtaHC1.smjhc.tb.aj0#{sprintf('%02d', i+1)}.jpg", pict)
end
end
def test_parse_pages
pages = @parser.parse_pictures[:pages]
assert_equal(5, pages.size)
pages.each_with_index do |page, i|
assert_equal("http://ex.shemalejapanhardcore.com/members/scenes/Exclusive-Uta_highres_#{i+2}.html", page)
end
end
end
class ShjaParserHcMoviePageTest < Minitest::Test
FORMATS = {
"360p" => "http://ex.shemalejapanhardcore.com/members/content/upload/uta/151224//360p/utatbhc1_1_hdmp4.mp4",
"480p" => "http://ex.shemalejapanhardcore.com/members/content/upload/uta/151224//480p/utatbhc1_1_hdmp4.mp4",
"720p" => "http://ex.shemalejapanhardcore.com/members/content/upload/uta/151224//720p/utaTBHC1_1_hdmp4.mp4",
}
def setup
@video_html = open(File.join(HC_FIXTURES_ROOT, 'uta.video.html')).read
@parser = Shja::Parser::HcMoviePage.new(@video_html)
end
def test_parse
formats = @parser.parse
assert_equal(FORMATS, formats)
end
end
| mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_98/safe/CWE_98__fopen__func_FILTER-CLEANING-number_int_filter__include_file_id-sprintf_%d_simple_quote.php | 1522 | <?php
/*
Safe sample
input : use fopen to read /tmp/tainted.txt and put the first line in $tainted
Uses a number_int_filter via filter_var function
construction : use of sprintf via a %d with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$handle = @fopen("/tmp/tainted.txt", "r");
if ($handle) {
if(($tainted = fgets($handle, 4096)) == false) {
$tainted = "";
}
fclose($handle);
} else {
$tainted = "";
}
$sanitized = filter_var($tainted, FILTER_SANITIZE_NUMBER_INT);
if (filter_var($sanitized, FILTER_VALIDATE_INT))
$tainted = $sanitized ;
else
$tainted = "" ;
$var = include(sprintf("pages/'%d'.php", $tainted));
?> | mit |
absynce/Raven.Assure | src/Raven.Assure/BackUp/IBackUpDatabase.cs | 249 | using Raven.Assure.Fluent;
namespace Raven.Assure.BackUp
{
public interface IBackUpDatabase<out T> : IBackUp<IBackUpDatabase<T>>, IAssureDataBase, IRunAssure, ISetupAssure<T>
{
new IBackUpDatabase<T> From(string databaseName);
}
} | mit |
Nexperia/pcn-search | app/services/transform.js | 2703 | 'use strict';
angular.module('app').factory('Transform',
function () {
function getJsonLdContext(repo, plmType, contextProps) {
return {
'@context': angular.extend({
'@vocab': 'http://www.data.nexperia.com/def/' + repo + '/',
schema: 'http://schema.org/',
dc: 'http://purl.org/dc/terms/',
nfo: 'http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#',
xsd: 'http://www.w3.org/2001/XMLSchema#'
}, contextProps),
'@type': 'http://www.data.nexperia.com/def/' + repo + '/' + plmType
};
}
return {
rewriteJsonLdProperties: function (data) {
return data.map(function (res) {
for (var key in res) {
if (res.hasOwnProperty(key) && key.indexOf('/') !== -1) {
var newkey = key.split(/[\/#]/).pop();
res[newkey] = res[key];
delete res[key];
}
}
return res;
});
},
simplifyJsonLd: function (data, repo, plmType, contextProps, onSuccess) {
var callback = function (err, data) {
if (err) console.log(err);
else {
// console.log(JSON.stringify(data, null, 2));
onSuccess(data['@graph']);
}
};
return jsonld.compact(data, getJsonLdContext(repo, plmType, contextProps),
{ graph: true }, callback);
},
simplifySrj: function (data) {
return data.results.bindings.map(function (res) {
for (var key in res) {
if (res.hasOwnProperty(key)) {
res[key] = res[key].value;
}
}
return res;
});
},
fillRepeatedChildrenPropsJsonLd: function (data, childName) {
var map = {};
data.forEach(function (item) {
item[childName] = Array.isArray(item[childName]) ? item[childName] : [item[childName]];
item[childName].forEach(function (child) {
var id = child['@id'];
if (map[id]) angular.extend(child, map[id]);
else map[id] = child;
});
});
return data;
}
}
}
); | mit |
plumer/codana | tomcat_files/6.0.0/ContextEjb.java | 2838 | /*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.deploy;
import java.io.Serializable;
/**
* Representation of an EJB resource reference for a web application, as
* represented in a <code><ejb-ref></code> element in the
* deployment descriptor.
*
* @author Craig R. McClanahan
* @author Peter Rossbach (pero@apache.org)
* @version $Revision: 303342 $ $Date: 2004-10-05 09:56:49 +0200 (mar., 05 oct. 2004) $
*/
public class ContextEjb extends ResourceBase implements Serializable {
// ------------------------------------------------------------- Properties
/**
* The name of the EJB home implementation class.
*/
private String home = null;
public String getHome() {
return (this.home);
}
public void setHome(String home) {
this.home = home;
}
/**
* The link to a J2EE EJB definition.
*/
private String link = null;
public String getLink() {
return (this.link);
}
public void setLink(String link) {
this.link = link;
}
/**
* The name of the EJB remote implementation class.
*/
private String remote = null;
public String getRemote() {
return (this.remote);
}
public void setRemote(String remote) {
this.remote = remote;
}
// --------------------------------------------------------- Public Methods
/**
* Return a String representation of this object.
*/
public String toString() {
StringBuffer sb = new StringBuffer("ContextEjb[");
sb.append("name=");
sb.append(getName());
if (getDescription() != null) {
sb.append(", description=");
sb.append(getDescription());
}
if (getType() != null) {
sb.append(", type=");
sb.append(getType());
}
if (home != null) {
sb.append(", home=");
sb.append(home);
}
if (remote != null) {
sb.append(", remote=");
sb.append(remote);
}
if (link != null) {
sb.append(", link=");
sb.append(link);
}
sb.append("]");
return (sb.toString());
}
}
| mit |
ElectronicTheatreControlsLabs/LuminosusEosEdition | src/block_implementations/OSC/OscOutBlock.cpp | 4398 | // Copyright (c) 2016 Electronic Theatre Controls, Inc., http://www.etcconnect.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "OscOutBlock.h"
#include "core/MainController.h"
#include "core/Nodes.h"
OscOutBlock::OscOutBlock(MainController *controller, QString uid)
: OneInputBlock(controller, uid)
, m_message("")
, m_lastValue(0)
, m_minValue(0)
, m_maxValue(1)
, m_useInteger(false)
, m_negativeMinValue(this, "negativeMinValue", false)
, m_negativeMaxValue(this, "negativeMaxValue", false)
{
connect(m_inputNode, SIGNAL(dataChanged()), this, SLOT(onValueChanged()));
}
void OscOutBlock::getAdditionalState(QJsonObject& state) const {
state["message"] = getMessage();
state["minValue"] = getMinValue();
state["maxValue"] = getMaxValue();
state["useInteger"] = getUseInteger();
}
void OscOutBlock::setAdditionalState(const QJsonObject &state) {
setMessage(state["message"].toString());
setMinValue(state["minValue"].toDouble());
setMaxValue(state["maxValue"].toDouble());
setUseInteger(state["useInteger"].toBool());
}
void OscOutBlock::onValueChanged() {
double value = m_inputNode->getValue();
double absoluteValue = m_inputNode->getAbsoluteValue();
if (absoluteValue == m_lastValue) return;
QString message = m_message;
if (message.isEmpty()) return;
if (message.contains("<value>")) {
double scaledValue = 0;
if (m_inputNode->constData().absoluteMaximumIsProvided()) {
scaledValue = absoluteValue;
} else {
double realMin = m_minValue * (m_negativeMinValue ? -1 : 1);
double realMax = m_maxValue * (m_negativeMaxValue ? -1 : 1);
scaledValue = realMin + (value * (realMax - realMin));
}
if (m_useInteger) {
message.replace("<value>", QString::number(int(scaledValue)));
} else {
message.replace("<value>", QString::number(scaledValue, 'f', 4));
}
if (m_controller->getSendCustomOscToEos()) {
m_controller->lightingConsole()->sendMessage(message);
} else {
m_controller->customOsc()->sendMessage(message);
}
emit messageSent();
} else if (message.contains("<bpm>")) {
if (absoluteValue <= 0) {
absoluteValue = 0.1;
}
double scaledValue = 60.0 / absoluteValue;
if (m_useInteger) {
message.replace("<bpm>", QString::number(int(scaledValue)));
} else {
message.replace("<bpm>", QString::number(scaledValue, 'f', 4));
}
if (m_controller->getSendCustomOscToEos()) {
m_controller->lightingConsole()->sendMessage(message);
} else {
m_controller->customOsc()->sendMessage(message);
}
emit messageSent();
} else if (value >= LuminosusConstants::triggerThreshold && m_lastValue < LuminosusConstants::triggerThreshold) {
if (m_controller->getSendCustomOscToEos()) {
m_controller->lightingConsole()->sendMessage(message);
} else {
m_controller->customOsc()->sendMessage(message);
}
emit messageSent();
}
m_lastValue = absoluteValue;
}
void OscOutBlock::setMinValue(double value) {
if (value < 0) {
value = 0;
}
m_minValue = value;
}
void OscOutBlock::setMaxValue(double value) {
if (value < 0) {
value = 0;
}
m_maxValue = value;
}
| mit |
abusalimov/mrcalc | src/main/java/com/abusalimov/mrcalc/parse/Parser.java | 2062 | package com.abusalimov.mrcalc.parse;
import com.abusalimov.mrcalc.ast.ProgramNode;
import com.abusalimov.mrcalc.diagnostic.DiagnosticEmitter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* Parser analyzes input source code and constructs an AST rooted by a {@link ProgramNode}, emitting
* appropriate {@link com.abusalimov.mrcalc.diagnostic.Diagnostic}s whenever a syntax error occurs.
*
* @author Eldar Abusalimov
*/
public interface Parser extends DiagnosticEmitter {
/**
* Parses the input specified as a given reader and build the AST.
*
* @param reader the source code
* @return the AST root
* @throws IOException in case the specified reader encounters an error
* @throws SyntaxErrorException in case of malformed input
*/
ProgramNode parse(Reader reader) throws IOException, SyntaxErrorException;
/**
* Parses a given string.
*
* @see #parse(Reader)
*/
default ProgramNode parse(String s) throws SyntaxErrorException {
try {
return parse(new StringReader(Objects.requireNonNull(s)));
} catch (IOException e) {
/* StringReader never throws for non-null strings, relax. */
throw new RuntimeException(e);
}
}
/**
* Tokenizes the input specified as a given reader and build the AST.
*
* @param reader the source code
* @return the AST root
* @throws IOException in case the specified reader encounters an error
*/
default List<TokenSpan> tokenize(Reader reader) throws IOException {
return Collections.emptyList();
}
/**
* Tokenizes a given string.
*
* @see #tokenize(Reader)
*/
default List<TokenSpan> tokenize(String s) {
try {
return tokenize(new StringReader(Objects.requireNonNull(s)));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| mit |
ker2x/hyperloglog-sophia | lib/counter.rb | 1275 | module HyperLogLog
class Counter
include Algorithm
# This is the implementation of the standard HyperLogLog algorithm, storing
# counts in each byte of a string of length 2 ** b.
def add(counter_name, value)
hash, function_name, new_value = hash_info(value)
#TODO existing_value = @sophia.getrange(counter_name, function_name, function_name).unpack('C').first.to_i
#TODO @sophia.setrange(counter_name, function_name, new_value.chr) if new_value > existing_value
end
# Estimate the cardinality of a single set
def count(counter_name)
union_helper([counter_name])
end
# Estimate the cardinality of the union of several sets
def union(counter_names)
union_helper(counter_names)
end
# Store the union of several sets in *destination* so that it can be used as
# a HyperLogLog counter later.
def union_store(destination, counter_names)
#TODO @sophia.set(destination, raw_union(counter_names).inject('') {|a, e| a << e.chr})
end
private
def raw_union(counter_names, time=nil)
#TODO counters = @sophia.mget(*counter_names).compact
return [] if counters.none?
return counters.first.each_byte if counters.one?
counters.map{|c| c.unpack("C#{@m}")}.transpose.map {|e| e.compact.max.to_i}
end
end
end
| mit |
marcomd/Leonardo | lib/generators/rspec/leosca/templates/index_spec.rb | 2143 | require 'spec_helper'
<%
def value_for_check(attribute)
name = ":text"
([] <<
case attribute.type
when :boolean
"\"tr#tr\#{r.id}>td>img.\#{r.#{attribute.name} ? \"ico_true\" : \"ico_false\"}\""
else
"\"tr#tr\#{r.id}>td\""
end <<
case attribute.type
when :references, :belongs_to
"#{name} => (r.#{attribute.name}.try(:name) || r.#{attribute.name}.try(:id))"
when :boolean
nil
when :decimal
"#{name} => number_to_currency(r.#{attribute.name})"
when :integer
"#{name} => number_with_delimiter(r.#{attribute.name})"
when :float
"#{name} => number_with_precision(r.#{attribute.name})"
else
"#{name} => r.#{attribute.name}"
end
).compact.join(', ')
end
%>
<% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%>
describe "<%= formatted_namespace_path %><%= ns_table_name %>/index.html.<%= options[:template_engine] %>" do
before(:each) do
<%- parents = []; str_parents_create = str_parents_where = "" -%>
<%- base_parent_resources.each do |parent| -%>
@<%= parent %> = assign(:<%= parent %>, Factory(:<%= parent %>) )
<%- parents << ":#{parent}_id => @#{parent}.id" -%>
<%- end -%>
<%- str_parents_create = ", #{parents.join(', ')}" if parents.any? -%>
<%- str_parents_where = ".where(#{parents.join(', ')})" if parents.any? -%>
<%- if pagination? -%>
FactoryGirl.create_list(:<%= ns_file_name %>, 2<%= str_parents_create %>)
@records = assign(:<%= table_name %>, <%= class_name %><%= str_parents_where %>.order(:id).page(1) )
<%- else -%>
@records = assign(:<%= table_name %>, FactoryGirl.create_list(:<%= ns_file_name %>, 2<%= str_parents_create %>) )
<%- end -%>
assign(:<%= ns_file_name %>, Factory.build(:<%= ns_file_name %>) )
<<<<<<< HEAD
view.stub(:sort_column, :sort_direction)
=======
>>>>>>> 730e2ecf07a73945550e3f0ea4a337ed132a4798
end
it "renders a list of <%= ns_table_name %>" do
render
@records.each do |r|
<% for attribute in output_attributes -%>
assert_select <%= value_for_check(attribute) %>
<% end -%>
end
end
end | mit |
LandRegistry/land-registry-elements | src/land_registry_elements/back-link/controller.js | 182 | /* global $ */
'use strict'
import { BackLink } from './BackLink.js'
$('[data-back-link]').each(function (index, item) {
var instance = new BackLink(item)
instance.create()
})
| mit |
Leanty/tree-gateway | src/config/jsonata.ts | 681 | 'use strict';
import * as Joi from 'joi';
import { ValidationError } from './errors';
/**
* A [jsonata](https://www.npmjs.com/package/jsonata) expression, used by core interceptors
* to transform responses.
*/
export interface JSONAtaExpression {
/**
* The jsonata expressio
*/
expression: string;
}
const jsonataExpressionSchema = Joi.object().keys({
expression: Joi.string().required()
});
export function validateJsonAtaExpression(config: JSONAtaExpression) {
const result = Joi.validate(config, jsonataExpressionSchema);
if (result.error) {
throw new ValidationError(result.error);
} else {
return result.value;
}
}
| mit |
ClxS/Stardew-Farmhand | Libraries/Installers/Patcher/FarmhandPatcherCommon/Injection/Components/Hooks/ReturnableHookHandler.cs | 10009 | namespace Farmhand.Installers.Patcher.Injection.Components.Hooks
{
// ReSharper disable StyleCop.SA1600
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Farmhand.Installers.Patcher.Cecil;
using Farmhand.Installers.Patcher.Injection.Components.Hooks.Converters;
using Farmhand.Installers.Patcher.Injection.Components.Parameters;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
[Export(typeof(IHookHandler))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class ReturnableHookHandler<TParam> : IHookHandler
where TParam : Attribute
{
private readonly CecilContext cecilContext;
private readonly IEnumerable<IParameterHandler> parameterHandlers;
private readonly IReturnableHookHandlerAttributeConverter propertyConverter;
[ImportingConstructor]
public ReturnableHookHandler(
[ImportMany] IEnumerable<IParameterHandler> parameterHandlers,
IReturnableHookHandlerAttributeConverter propertyProvider,
IInjectionContext injectionContext)
{
this.parameterHandlers = parameterHandlers;
this.propertyConverter = propertyProvider;
var context = injectionContext as CecilContext;
if (context != null)
{
this.cecilContext = context;
}
else
{
throw new Exception(
$"CecilInjectionProcessor is only compatible with {nameof(CecilContext)}.");
}
}
#region IHookHandler Members
public void PerformAlteration(Attribute attribute, string type, string method)
{
this.propertyConverter.FromAttribute(attribute);
var orders = new List<InjectOrder>();
this.GatherInjectionOrders(type, method, orders);
foreach (var order in orders)
{
this.InjectMethod(order);
}
}
public bool Equals(string fullName)
{
return this.propertyConverter.FullName == fullName;
}
#endregion
private void GatherInjectionOrders(
string injectedType,
string injectedMethod,
List<InjectOrder> orders)
{
MethodReference method = this.cecilContext.GetMethodDefinition(
injectedType,
injectedMethod);
if (method.HasGenericParameters)
{
var injectReceiverMethodDef =
this.cecilContext.GetMethodDefinition(
this.propertyConverter.Type,
this.propertyConverter.Method);
var inst = new GenericInstanceMethod(method);
for (var i = 0; i < method.GenericParameters.Count; ++i)
{
inst.GenericArguments.Add(
injectReceiverMethodDef.DeclaringType.GenericParameters[i]);
}
method = inst;
}
var processor = this.cecilContext.GetMethodIlProcessor(
this.propertyConverter.Type,
this.propertyConverter.Method);
if (this.propertyConverter.IsExit)
{
foreach (var retInst in
processor.Body.Instructions.Where(i => i.OpCode == OpCodes.Ret))
{
orders.Add(
new InjectOrder
{
CecilContext = this.cecilContext,
InsertedMethod = method,
IsCancellable =
method.ReturnType != null
&& method.ReturnType.FullName
== typeof(bool).FullName,
IsExit = this.propertyConverter.IsExit,
ReceivingProcessor = processor,
Target = retInst
});
}
}
else
{
orders.Add(
new InjectOrder
{
CecilContext = this.cecilContext,
InsertedMethod = method,
IsCancellable =
method.ReturnType != null
&& method.ReturnType.FullName == typeof(bool).FullName,
IsExit = this.propertyConverter.IsExit,
ReceivingProcessor = processor,
Target = processor.Body.Instructions.First()
});
}
}
private void InjectMethod(InjectOrder order)
{
order.ReceivingProcessor.Body.SimplifyMacros();
// Add UseReturnVal variable
if (order.ReceivingProcessor.Body.Variables.All(n => n.Name != "UseReturnVal"))
{
var boolType = order.CecilContext.GetTypeReference(typeof(bool));
order.ReceivingProcessor.Body.Variables.Add(
new VariableDefinition("UseReturnVal", boolType));
}
var useOutputVariable =
order.ReceivingProcessor.Body.Variables.First(n => n.Name == "UseReturnVal");
if (
order.ReceivingProcessor.Body.Variables.All(
n => n.Name != "ReturnContainer-" + order.InsertedMethod.ReturnType.Name))
{
order.ReceivingProcessor.Body.Variables.Add(
new VariableDefinition(
"ReturnContainer-" + order.InsertedMethod.ReturnType.Name,
order.InsertedMethod.ReturnType));
}
if (order.IsExit)
{
if (order.ReceivingProcessor.Body.Variables.All(n => n.Name != "OldReturnContainer"))
{
order.ReceivingProcessor.Body.Variables.Add(
new VariableDefinition(
"OldReturnContainer",
order.InsertedMethod.ReturnType));
}
}
var containerVariable =
order.ReceivingProcessor.Body.Variables.First(
n => n.Name == "ReturnContainer-" + order.InsertedMethod.ReturnType.Name);
var oldContainerVariable =
order.ReceivingProcessor.Body.Variables.FirstOrDefault(
n => n.Name == "OldReturnContainer");
var instructions = new List<Instruction>();
if (order.IsExit)
{
instructions.Add(
order.ReceivingProcessor.Create(OpCodes.Stloc, oldContainerVariable));
}
if (order.InsertedMethod.HasParameters)
{
foreach (var parameter in order.InsertedMethod.Parameters)
{
this.GetParameterInstructions(order, parameter, instructions);
}
}
instructions.Add(order.ReceivingProcessor.Create(OpCodes.Call, order.InsertedMethod));
instructions.Add(order.ReceivingProcessor.Create(OpCodes.Stloc, containerVariable));
instructions.Add(order.ReceivingProcessor.Create(OpCodes.Ldloc, useOutputVariable));
if (!order.IsExit)
{
instructions.Add(order.ReceivingProcessor.Create(OpCodes.Brfalse, order.Target));
instructions.Add(order.ReceivingProcessor.Create(OpCodes.Ldloc, containerVariable));
instructions.Add(
order.ReceivingProcessor.Create(
OpCodes.Br,
order.ReceivingProcessor.Body.Instructions.Last()));
}
else
{
var branchToRet = order.ReceivingProcessor.Create(OpCodes.Br, order.Target);
var loadOld = order.ReceivingProcessor.Create(OpCodes.Ldloc, oldContainerVariable);
var loadNew = order.ReceivingProcessor.Create(OpCodes.Ldloc, containerVariable);
instructions.Add(order.ReceivingProcessor.Create(OpCodes.Brfalse, loadOld));
instructions.Add(loadNew);
instructions.Add(branchToRet);
instructions.Add(loadOld);
}
foreach (var inst in instructions)
{
order.ReceivingProcessor.InsertBefore(order.Target, inst);
}
order.ReceivingProcessor.Body.OptimizeMacros();
}
private void GetParameterInstructions(InjectOrder order, ParameterDefinition parameter, List<Instruction> instruction)
{
var attribute =
parameter.CustomAttributes.FirstOrDefault(
n =>
n.AttributeType.IsDefinition
&& n.AttributeType.Resolve().BaseType?.FullName == typeof(TParam).FullName);
if (attribute == null)
{
throw new Exception("Non API parameter type encountered");
}
var paramMatches =
this.parameterHandlers.Where(p => p.Equals(attribute.AttributeType.FullName)).ToArray();
if (!paramMatches.Any())
{
throw new Exception(
$"Found no parameter handlers for {attribute.AttributeType.FullName}");
}
if (paramMatches.Length > 1)
{
throw new Exception(
$"Encountered multiple parameter handlers for {attribute.AttributeType.FullName}");
}
paramMatches.First().GetInstructions(order, attribute, instruction);
}
}
} | mit |
tbranyen/house | apps/todos/web/iscroll.js | 33961 | /*!
* iScroll v4.2.5 ~ Copyright (c) 2012 Matteo Spinelli, http://cubiq.org
* Released under MIT license, http://cubiq.org/license
*/
(function(window, doc){
var m = Math,
dummyStyle = doc.createElement('div').style,
vendor = (function () {
var vendors = 't,webkitT,MozT,msT,OT'.split(','),
t,
i = 0,
l = vendors.length;
for ( ; i < l; i++ ) {
t = vendors[i] + 'ransform';
if ( t in dummyStyle ) {
return vendors[i].substr(0, vendors[i].length - 1);
}
}
return false;
})(),
cssVendor = vendor ? '-' + vendor.toLowerCase() + '-' : '',
// Style properties
transform = prefixStyle('transform'),
transitionProperty = prefixStyle('transitionProperty'),
transitionDuration = prefixStyle('transitionDuration'),
transformOrigin = prefixStyle('transformOrigin'),
transitionTimingFunction = prefixStyle('transitionTimingFunction'),
transitionDelay = prefixStyle('transitionDelay'),
// Browser capabilities
isAndroid = (/android/gi).test(navigator.appVersion),
isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
isTouchPad = (/hp-tablet/gi).test(navigator.appVersion),
has3d = prefixStyle('perspective') in dummyStyle,
hasTouch = 'ontouchstart' in window && !isTouchPad,
hasTransform = vendor !== false,
hasTransitionEnd = prefixStyle('transition') in dummyStyle,
RESIZE_EV = 'onorientationchange' in window ? 'orientationchange' : 'resize',
START_EV = hasTouch ? 'touchstart' : 'mousedown',
MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
END_EV = hasTouch ? 'touchend' : 'mouseup',
CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseup',
TRNEND_EV = (function () {
if ( vendor === false ) return false;
var transitionEnd = {
'' : 'transitionend',
'webkit' : 'webkitTransitionEnd',
'Moz' : 'transitionend',
'O' : 'otransitionend',
'ms' : 'MSTransitionEnd'
};
return transitionEnd[vendor];
})(),
nextFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) { return setTimeout(callback, 1); };
})(),
cancelFrame = (function () {
return window.cancelRequestAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout;
})(),
// Helpers
translateZ = has3d ? ' translateZ(0)' : '',
// Constructor
iScroll = function (el, options) {
var that = this,
i;
that.wrapper = typeof el == 'object' ? el : doc.getElementById(el);
that.wrapper.style.overflow = 'hidden';
that.scroller = that.wrapper.children[0];
// Default options
that.options = {
hScroll: true,
vScroll: true,
x: 0,
y: 0,
bounce: true,
bounceLock: false,
momentum: true,
lockDirection: true,
useTransform: true,
useTransition: false,
topOffset: 0,
checkDOMChanges: false, // Experimental
handleClick: true,
// Scrollbar
hScrollbar: true,
vScrollbar: true,
fixedScrollbar: isAndroid,
hideScrollbar: isIDevice,
fadeScrollbar: isIDevice && has3d,
scrollbarClass: '',
// Zoom
zoom: false,
zoomMin: 1,
zoomMax: 4,
doubleTapZoom: 2,
wheelAction: 'scroll',
// Snap
snap: false,
snapThreshold: 1,
// Events
onRefresh: null,
onBeforeScrollStart: function (e) { e.preventDefault(); },
onScrollStart: null,
onBeforeScrollMove: null,
onScrollMove: null,
onBeforeScrollEnd: null,
onScrollEnd: null,
onTouchEnd: null,
onDestroy: null,
onZoomStart: null,
onZoom: null,
onZoomEnd: null
};
// User defined options
for (i in options) that.options[i] = options[i];
// Set starting position
that.x = that.options.x;
that.y = that.options.y;
// Normalize options
that.options.useTransform = hasTransform && that.options.useTransform;
that.options.hScrollbar = that.options.hScroll && that.options.hScrollbar;
that.options.vScrollbar = that.options.vScroll && that.options.vScrollbar;
that.options.zoom = that.options.useTransform && that.options.zoom;
that.options.useTransition = hasTransitionEnd && that.options.useTransition;
// Helpers FIX ANDROID BUG!
// translate3d and scale doesn't work together!
// Ignoring 3d ONLY WHEN YOU SET that.options.zoom
if ( that.options.zoom && isAndroid ){
translateZ = '';
}
// Set some default styles
that.scroller.style[transitionProperty] = that.options.useTransform ? cssVendor + 'transform' : 'top left';
that.scroller.style[transitionDuration] = '0';
that.scroller.style[transformOrigin] = '0 0';
if (that.options.useTransition) that.scroller.style[transitionTimingFunction] = 'cubic-bezier(0.33,0.66,0.66,1)';
if (that.options.useTransform) that.scroller.style[transform] = 'translate(' + that.x + 'px,' + that.y + 'px)' + translateZ;
else that.scroller.style.cssText += ';position:absolute;top:' + that.y + 'px;left:' + that.x + 'px';
if (that.options.useTransition) that.options.fixedScrollbar = true;
that.refresh();
that._bind(RESIZE_EV, window);
that._bind(START_EV);
if (!hasTouch) {
if (that.options.wheelAction != 'none') {
that._bind('DOMMouseScroll');
that._bind('mousewheel');
}
}
if (that.options.checkDOMChanges) that.checkDOMTime = setInterval(function () {
that._checkDOMChanges();
}, 500);
};
// Prototype
iScroll.prototype = {
enabled: true,
x: 0,
y: 0,
steps: [],
scale: 1,
currPageX: 0, currPageY: 0,
pagesX: [], pagesY: [],
aniTime: null,
wheelZoomCount: 0,
handleEvent: function (e) {
var that = this;
switch(e.type) {
case START_EV:
if (!hasTouch && e.button !== 0) return;
that._start(e);
break;
case MOVE_EV: that._move(e); break;
case END_EV:
case CANCEL_EV: that._end(e); break;
case RESIZE_EV: that._resize(); break;
case 'DOMMouseScroll': case 'mousewheel': that._wheel(e); break;
case TRNEND_EV: that._transitionEnd(e); break;
}
},
_checkDOMChanges: function () {
if (this.moved || this.zoomed || this.animating ||
(this.scrollerW == this.scroller.offsetWidth * this.scale && this.scrollerH == this.scroller.offsetHeight * this.scale)) return;
this.refresh();
},
_scrollbar: function (dir) {
var that = this,
bar;
if (!that[dir + 'Scrollbar']) {
if (that[dir + 'ScrollbarWrapper']) {
if (hasTransform) that[dir + 'ScrollbarIndicator'].style[transform] = '';
that[dir + 'ScrollbarWrapper'].parentNode.removeChild(that[dir + 'ScrollbarWrapper']);
that[dir + 'ScrollbarWrapper'] = null;
that[dir + 'ScrollbarIndicator'] = null;
}
return;
}
if (!that[dir + 'ScrollbarWrapper']) {
// Create the scrollbar wrapper
bar = doc.createElement('div');
if (that.options.scrollbarClass) bar.className = that.options.scrollbarClass + dir.toUpperCase();
else bar.style.cssText = 'position:absolute;z-index:100;' + (dir == 'h' ? 'height:7px;bottom:1px;left:2px;right:' + (that.vScrollbar ? '7' : '2') + 'px' : 'width:7px;bottom:' + (that.hScrollbar ? '7' : '2') + 'px;top:2px;right:1px');
bar.style.cssText += ';pointer-events:none;' + cssVendor + 'transition-property:opacity;' + cssVendor + 'transition-duration:' + (that.options.fadeScrollbar ? '350ms' : '0') + ';overflow:hidden;opacity:' + (that.options.hideScrollbar ? '0' : '1');
that.wrapper.appendChild(bar);
that[dir + 'ScrollbarWrapper'] = bar;
// Create the scrollbar indicator
bar = doc.createElement('div');
if (!that.options.scrollbarClass) {
bar.style.cssText = 'position:absolute;z-index:100;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);' + cssVendor + 'background-clip:padding-box;' + cssVendor + 'box-sizing:border-box;' + (dir == 'h' ? 'height:100%' : 'width:100%') + ';' + cssVendor + 'border-radius:3px;border-radius:3px';
}
bar.style.cssText += ';pointer-events:none;' + cssVendor + 'transition-property:' + cssVendor + 'transform;' + cssVendor + 'transition-timing-function:cubic-bezier(0.33,0.66,0.66,1);' + cssVendor + 'transition-duration:0;' + cssVendor + 'transform: translate(0,0)' + translateZ;
if (that.options.useTransition) bar.style.cssText += ';' + cssVendor + 'transition-timing-function:cubic-bezier(0.33,0.66,0.66,1)';
that[dir + 'ScrollbarWrapper'].appendChild(bar);
that[dir + 'ScrollbarIndicator'] = bar;
}
if (dir == 'h') {
that.hScrollbarSize = that.hScrollbarWrapper.clientWidth;
that.hScrollbarIndicatorSize = m.max(m.round(that.hScrollbarSize * that.hScrollbarSize / that.scrollerW), 8);
that.hScrollbarIndicator.style.width = that.hScrollbarIndicatorSize + 'px';
that.hScrollbarMaxScroll = that.hScrollbarSize - that.hScrollbarIndicatorSize;
that.hScrollbarProp = that.hScrollbarMaxScroll / that.maxScrollX;
} else {
that.vScrollbarSize = that.vScrollbarWrapper.clientHeight;
that.vScrollbarIndicatorSize = m.max(m.round(that.vScrollbarSize * that.vScrollbarSize / that.scrollerH), 8);
that.vScrollbarIndicator.style.height = that.vScrollbarIndicatorSize + 'px';
that.vScrollbarMaxScroll = that.vScrollbarSize - that.vScrollbarIndicatorSize;
that.vScrollbarProp = that.vScrollbarMaxScroll / that.maxScrollY;
}
// Reset position
that._scrollbarPos(dir, true);
},
_resize: function () {
var that = this;
setTimeout(function () { that.refresh(); }, isAndroid ? 200 : 0);
},
_pos: function (x, y) {
if (this.zoomed) return;
x = this.hScroll ? x : 0;
y = this.vScroll ? y : 0;
if (this.options.useTransform) {
this.scroller.style[transform] = 'translate(' + x + 'px,' + y + 'px) scale(' + this.scale + ')' + translateZ;
} else {
x = m.round(x);
y = m.round(y);
this.scroller.style.left = x + 'px';
this.scroller.style.top = y + 'px';
}
this.x = x;
this.y = y;
this._scrollbarPos('h');
this._scrollbarPos('v');
},
_scrollbarPos: function (dir, hidden) {
var that = this,
pos = dir == 'h' ? that.x : that.y,
size;
if (!that[dir + 'Scrollbar']) return;
pos = that[dir + 'ScrollbarProp'] * pos;
if (pos < 0) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] + m.round(pos * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
}
pos = 0;
} else if (pos > that[dir + 'ScrollbarMaxScroll']) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] - m.round((pos - that[dir + 'ScrollbarMaxScroll']) * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
pos = that[dir + 'ScrollbarMaxScroll'] + (that[dir + 'ScrollbarIndicatorSize'] - size);
} else {
pos = that[dir + 'ScrollbarMaxScroll'];
}
}
that[dir + 'ScrollbarWrapper'].style[transitionDelay] = '0';
that[dir + 'ScrollbarWrapper'].style.opacity = hidden && that.options.hideScrollbar ? '0' : '1';
that[dir + 'ScrollbarIndicator'].style[transform] = 'translate(' + (dir == 'h' ? pos + 'px,0)' : '0,' + pos + 'px)') + translateZ;
},
_start: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
matrix, x, y,
c1, c2;
if (!that.enabled) return;
if (that.options.onBeforeScrollStart) that.options.onBeforeScrollStart.call(that, e);
if (that.options.useTransition || that.options.zoom) that._transitionTime(0);
that.moved = false;
that.animating = false;
that.zoomed = false;
that.distX = 0;
that.distY = 0;
that.absDistX = 0;
that.absDistY = 0;
that.dirX = 0;
that.dirY = 0;
// Gesture start
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX-e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY-e.touches[1].pageY);
that.touchesDistStart = m.sqrt(c1 * c1 + c2 * c2);
that.originX = m.abs(e.touches[0].pageX + e.touches[1].pageX - that.wrapperOffsetLeft * 2) / 2 - that.x;
that.originY = m.abs(e.touches[0].pageY + e.touches[1].pageY - that.wrapperOffsetTop * 2) / 2 - that.y;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
}
if (that.options.momentum) {
if (that.options.useTransform) {
// Very lame general purpose alternative to CSSMatrix
matrix = getComputedStyle(that.scroller, null)[transform].replace(/[^0-9\-.,]/g, '').split(',');
x = +(matrix[12] || matrix[4]);
y = +(matrix[13] || matrix[5]);
} else {
x = +getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '');
y = +getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '');
}
if (x != that.x || y != that.y) {
if (that.options.useTransition) that._unbind(TRNEND_EV);
else cancelFrame(that.aniTime);
that.steps = [];
that._pos(x, y);
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that);
}
}
that.absStartX = that.x; // Needed by snap threshold
that.absStartY = that.y;
that.startX = that.x;
that.startY = that.y;
that.pointX = point.pageX;
that.pointY = point.pageY;
that.startTime = e.timeStamp || Date.now();
if (that.options.onScrollStart) that.options.onScrollStart.call(that, e);
that._bind(MOVE_EV, window);
that._bind(END_EV, window);
that._bind(CANCEL_EV, window);
},
_move: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
deltaX = point.pageX - that.pointX,
deltaY = point.pageY - that.pointY,
newX = that.x + deltaX,
newY = that.y + deltaY,
c1, c2, scale,
timestamp = e.timeStamp || Date.now();
if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
// Zoom
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX - e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY - e.touches[1].pageY);
that.touchesDist = m.sqrt(c1*c1+c2*c2);
that.zoomed = true;
scale = 1 / that.touchesDistStart * that.touchesDist * this.scale;
if (scale < that.options.zoomMin) scale = 0.5 * that.options.zoomMin * Math.pow(2.0, scale / that.options.zoomMin);
else if (scale > that.options.zoomMax) scale = 2.0 * that.options.zoomMax * Math.pow(0.5, that.options.zoomMax / scale);
that.lastScale = scale / this.scale;
newX = this.originX - this.originX * that.lastScale + this.x,
newY = this.originY - this.originY * that.lastScale + this.y;
this.scroller.style[transform] = 'translate(' + newX + 'px,' + newY + 'px) scale(' + scale + ')' + translateZ;
if (that.options.onZoom) that.options.onZoom.call(that, e);
return;
}
that.pointX = point.pageX;
that.pointY = point.pageY;
// Slow down if outside of the boundaries
if (newX > 0 || newX < that.maxScrollX) {
newX = that.options.bounce ? that.x + (deltaX / 2) : newX >= 0 || that.maxScrollX >= 0 ? 0 : that.maxScrollX;
}
if (newY > that.minScrollY || newY < that.maxScrollY) {
newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= that.minScrollY || that.maxScrollY >= 0 ? that.minScrollY : that.maxScrollY;
}
that.distX += deltaX;
that.distY += deltaY;
that.absDistX = m.abs(that.distX);
that.absDistY = m.abs(that.distY);
if (that.absDistX < 6 && that.absDistY < 6) {
return;
}
// Lock direction
if (that.options.lockDirection) {
if (that.absDistX > that.absDistY + 5) {
newY = that.y;
deltaY = 0;
} else if (that.absDistY > that.absDistX + 5) {
newX = that.x;
deltaX = 0;
}
}
that.moved = true;
that._pos(newX, newY);
that.dirX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
that.dirY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
if (timestamp - that.startTime > 300) {
that.startTime = timestamp;
that.startX = that.x;
that.startY = that.y;
}
if (that.options.onScrollMove) that.options.onScrollMove.call(that, e);
},
_end: function (e) {
if (hasTouch && e.touches.length !== 0) return;
var that = this,
point = hasTouch ? e.changedTouches[0] : e,
target, ev,
momentumX = { dist:0, time:0 },
momentumY = { dist:0, time:0 },
duration = (e.timeStamp || Date.now()) - that.startTime,
newPosX = that.x,
newPosY = that.y,
distX, distY,
newDuration,
snap,
scale;
that._unbind(MOVE_EV, window);
that._unbind(END_EV, window);
that._unbind(CANCEL_EV, window);
if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);
if (that.zoomed) {
scale = that.scale * that.lastScale;
scale = Math.max(that.options.zoomMin, scale);
scale = Math.min(that.options.zoomMax, scale);
that.lastScale = scale / that.scale;
that.scale = scale;
that.x = that.originX - that.originX * that.lastScale + that.x;
that.y = that.originY - that.originY * that.lastScale + that.y;
that.scroller.style[transitionDuration] = '200ms';
that.scroller.style[transform] = 'translate(' + that.x + 'px,' + that.y + 'px) scale(' + that.scale + ')' + translateZ;
that.zoomed = false;
that.refresh();
if (that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
return;
}
if (!that.moved) {
if (hasTouch) {
if (that.doubleTapTimer && that.options.zoom) {
// Double tapped
clearTimeout(that.doubleTapTimer);
that.doubleTapTimer = null;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.zoom(that.pointX, that.pointY, that.scale == 1 ? that.options.doubleTapZoom : 1);
if (that.options.onZoomEnd) {
setTimeout(function() {
that.options.onZoomEnd.call(that, e);
}, 200); // 200 is default zoom duration
}
} else if (this.options.handleClick) {
that.doubleTapTimer = setTimeout(function () {
that.doubleTapTimer = null;
// Find the last touched element
target = point.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
ev = doc.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
point.screenX, point.screenY, point.clientX, point.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._fake = true;
target.dispatchEvent(ev);
}
}, that.options.zoom ? 250 : 0);
}
}
that._resetPos(400);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
if (duration < 300 && that.options.momentum) {
momentumX = newPosX ? that._momentum(newPosX - that.startX, duration, -that.x, that.scrollerW - that.wrapperW + that.x, that.options.bounce ? that.wrapperW : 0) : momentumX;
momentumY = newPosY ? that._momentum(newPosY - that.startY, duration, -that.y, (that.maxScrollY < 0 ? that.scrollerH - that.wrapperH + that.y - that.minScrollY : 0), that.options.bounce ? that.wrapperH : 0) : momentumY;
newPosX = that.x + momentumX.dist;
newPosY = that.y + momentumY.dist;
if ((that.x > 0 && newPosX > 0) || (that.x < that.maxScrollX && newPosX < that.maxScrollX)) momentumX = { dist:0, time:0 };
if ((that.y > that.minScrollY && newPosY > that.minScrollY) || (that.y < that.maxScrollY && newPosY < that.maxScrollY)) momentumY = { dist:0, time:0 };
}
if (momentumX.dist || momentumY.dist) {
newDuration = m.max(m.max(momentumX.time, momentumY.time), 10);
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) { that.scrollTo(that.absStartX, that.absStartY, 200); }
else {
snap = that._snap(newPosX, newPosY);
newPosX = snap.x;
newPosY = snap.y;
newDuration = m.max(snap.time, newDuration);
}
}
that.scrollTo(m.round(newPosX), m.round(newPosY), newDuration);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) that.scrollTo(that.absStartX, that.absStartY, 200);
else {
snap = that._snap(that.x, that.y);
if (snap.x != that.x || snap.y != that.y) that.scrollTo(snap.x, snap.y, snap.time);
}
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
that._resetPos(200);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
},
_resetPos: function (time) {
var that = this,
resetX = that.x >= 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x,
resetY = that.y >= that.minScrollY || that.maxScrollY > 0 ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
if (resetX == that.x && resetY == that.y) {
if (that.moved) {
that.moved = false;
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that); // Execute custom code on scroll end
}
if (that.hScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.hScrollbarWrapper.style[transitionDelay] = '300ms';
that.hScrollbarWrapper.style.opacity = '0';
}
if (that.vScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.vScrollbarWrapper.style[transitionDelay] = '300ms';
that.vScrollbarWrapper.style.opacity = '0';
}
return;
}
that.scrollTo(resetX, resetY, time || 0);
},
_wheel: function (e) {
var that = this,
wheelDeltaX, wheelDeltaY,
deltaX, deltaY,
deltaScale;
if ('wheelDeltaX' in e) {
wheelDeltaX = e.wheelDeltaX / 12;
wheelDeltaY = e.wheelDeltaY / 12;
} else if('wheelDelta' in e) {
wheelDeltaX = wheelDeltaY = e.wheelDelta / 12;
} else if ('detail' in e) {
wheelDeltaX = wheelDeltaY = -e.detail * 3;
} else {
return;
}
if (that.options.wheelAction == 'zoom') {
deltaScale = that.scale * Math.pow(2, 1/3 * (wheelDeltaY ? wheelDeltaY / Math.abs(wheelDeltaY) : 0));
if (deltaScale < that.options.zoomMin) deltaScale = that.options.zoomMin;
if (deltaScale > that.options.zoomMax) deltaScale = that.options.zoomMax;
if (deltaScale != that.scale) {
if (!that.wheelZoomCount && that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.wheelZoomCount++;
that.zoom(e.pageX, e.pageY, deltaScale, 400);
setTimeout(function() {
that.wheelZoomCount--;
if (!that.wheelZoomCount && that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
}, 400);
}
return;
}
deltaX = that.x + wheelDeltaX;
deltaY = that.y + wheelDeltaY;
if (deltaX > 0) deltaX = 0;
else if (deltaX < that.maxScrollX) deltaX = that.maxScrollX;
if (deltaY > that.minScrollY) deltaY = that.minScrollY;
else if (deltaY < that.maxScrollY) deltaY = that.maxScrollY;
if (that.maxScrollY < 0) {
that.scrollTo(deltaX, deltaY, 0);
}
},
_transitionEnd: function (e) {
var that = this;
if (e.target != that.scroller) return;
that._unbind(TRNEND_EV);
that._startAni();
},
/**
*
* Utilities
*
*/
_startAni: function () {
var that = this,
startX = that.x, startY = that.y,
startTime = Date.now(),
step, easeOut,
animate;
if (that.animating) return;
if (!that.steps.length) {
that._resetPos(400);
return;
}
step = that.steps.shift();
if (step.x == startX && step.y == startY) step.time = 0;
that.animating = true;
that.moved = true;
if (that.options.useTransition) {
that._transitionTime(step.time);
that._pos(step.x, step.y);
that.animating = false;
if (step.time) that._bind(TRNEND_EV);
else that._resetPos(0);
return;
}
animate = function () {
var now = Date.now(),
newX, newY;
if (now >= startTime + step.time) {
that._pos(step.x, step.y);
that.animating = false;
if (that.options.onAnimationEnd) that.options.onAnimationEnd.call(that); // Execute custom code on animation end
that._startAni();
return;
}
now = (now - startTime) / step.time - 1;
easeOut = m.sqrt(1 - now * now);
newX = (step.x - startX) * easeOut + startX;
newY = (step.y - startY) * easeOut + startY;
that._pos(newX, newY);
if (that.animating) that.aniTime = nextFrame(animate);
};
animate();
},
_transitionTime: function (time) {
time += 'ms';
this.scroller.style[transitionDuration] = time;
if (this.hScrollbar) this.hScrollbarIndicator.style[transitionDuration] = time;
if (this.vScrollbar) this.vScrollbarIndicator.style[transitionDuration] = time;
},
_momentum: function (dist, time, maxDistUpper, maxDistLower, size) {
var deceleration = 0.0006,
speed = m.abs(dist) / time,
newDist = (speed * speed) / (2 * deceleration),
newTime = 0, outsideDist = 0;
// Proportinally reduce speed if we are outside of the boundaries
if (dist > 0 && newDist > maxDistUpper) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistUpper = maxDistUpper + outsideDist;
speed = speed * maxDistUpper / newDist;
newDist = maxDistUpper;
} else if (dist < 0 && newDist > maxDistLower) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistLower = maxDistLower + outsideDist;
speed = speed * maxDistLower / newDist;
newDist = maxDistLower;
}
newDist = newDist * (dist < 0 ? -1 : 1);
newTime = speed / deceleration;
return { dist: newDist, time: m.round(newTime) };
},
_offset: function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
if (el != this.wrapper) {
left *= this.scale;
top *= this.scale;
}
return { left: left, top: top };
},
_snap: function (x, y) {
var that = this,
i, l,
page, time,
sizeX, sizeY;
// Check page X
page = that.pagesX.length - 1;
for (i=0, l=that.pagesX.length; i<l; i++) {
if (x >= that.pagesX[i]) {
page = i;
break;
}
}
if (page == that.currPageX && page > 0 && that.dirX < 0) page--;
x = that.pagesX[page];
sizeX = m.abs(x - that.pagesX[that.currPageX]);
sizeX = sizeX ? m.abs(that.x - x) / sizeX * 500 : 0;
that.currPageX = page;
// Check page Y
page = that.pagesY.length-1;
for (i=0; i<page; i++) {
if (y >= that.pagesY[i]) {
page = i;
break;
}
}
if (page == that.currPageY && page > 0 && that.dirY < 0) page--;
y = that.pagesY[page];
sizeY = m.abs(y - that.pagesY[that.currPageY]);
sizeY = sizeY ? m.abs(that.y - y) / sizeY * 500 : 0;
that.currPageY = page;
// Snap with constant speed (proportional duration)
time = m.round(m.max(sizeX, sizeY)) || 200;
return { x: x, y: y, time: time };
},
_bind: function (type, el, bubble) {
(el || this.scroller).addEventListener(type, this, !!bubble);
},
_unbind: function (type, el, bubble) {
(el || this.scroller).removeEventListener(type, this, !!bubble);
},
/**
*
* Public methods
*
*/
destroy: function () {
var that = this;
that.scroller.style[transform] = '';
// Remove the scrollbars
that.hScrollbar = false;
that.vScrollbar = false;
that._scrollbar('h');
that._scrollbar('v');
// Remove the event listeners
that._unbind(RESIZE_EV, window);
that._unbind(START_EV);
that._unbind(MOVE_EV, window);
that._unbind(END_EV, window);
that._unbind(CANCEL_EV, window);
if (!that.options.hasTouch) {
that._unbind('DOMMouseScroll');
that._unbind('mousewheel');
}
if (that.options.useTransition) that._unbind(TRNEND_EV);
if (that.options.checkDOMChanges) clearInterval(that.checkDOMTime);
if (that.options.onDestroy) that.options.onDestroy.call(that);
},
refresh: function () {
var that = this,
offset,
i, l,
els,
pos = 0,
page = 0;
if (that.scale < that.options.zoomMin) that.scale = that.options.zoomMin;
that.wrapperW = that.wrapper.clientWidth || 1;
that.wrapperH = that.wrapper.clientHeight || 1;
that.minScrollY = -that.options.topOffset || 0;
that.scrollerW = m.round(that.scroller.offsetWidth * that.scale);
that.scrollerH = m.round((that.scroller.offsetHeight + that.minScrollY) * that.scale);
that.maxScrollX = that.wrapperW - that.scrollerW;
that.maxScrollY = that.wrapperH - that.scrollerH + that.minScrollY;
that.dirX = 0;
that.dirY = 0;
if (that.options.onRefresh) that.options.onRefresh.call(that);
that.hScroll = that.options.hScroll && that.maxScrollX < 0;
that.vScroll = that.options.vScroll && (!that.options.bounceLock && !that.hScroll || that.scrollerH > that.wrapperH);
that.hScrollbar = that.hScroll && that.options.hScrollbar;
that.vScrollbar = that.vScroll && that.options.vScrollbar && that.scrollerH > that.wrapperH;
offset = that._offset(that.wrapper);
that.wrapperOffsetLeft = -offset.left;
that.wrapperOffsetTop = -offset.top;
// Prepare snap
if (typeof that.options.snap == 'string') {
that.pagesX = [];
that.pagesY = [];
els = that.scroller.querySelectorAll(that.options.snap);
for (i=0, l=els.length; i<l; i++) {
pos = that._offset(els[i]);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
that.pagesX[i] = pos.left < that.maxScrollX ? that.maxScrollX : pos.left * that.scale;
that.pagesY[i] = pos.top < that.maxScrollY ? that.maxScrollY : pos.top * that.scale;
}
} else if (that.options.snap) {
that.pagesX = [];
while (pos >= that.maxScrollX) {
that.pagesX[page] = pos;
pos = pos - that.wrapperW;
page++;
}
if (that.maxScrollX%that.wrapperW) that.pagesX[that.pagesX.length] = that.maxScrollX - that.pagesX[that.pagesX.length-1] + that.pagesX[that.pagesX.length-1];
pos = 0;
page = 0;
that.pagesY = [];
while (pos >= that.maxScrollY) {
that.pagesY[page] = pos;
pos = pos - that.wrapperH;
page++;
}
if (that.maxScrollY%that.wrapperH) that.pagesY[that.pagesY.length] = that.maxScrollY - that.pagesY[that.pagesY.length-1] + that.pagesY[that.pagesY.length-1];
}
// Prepare the scrollbars
that._scrollbar('h');
that._scrollbar('v');
if (!that.zoomed) {
that.scroller.style[transitionDuration] = '0';
that._resetPos(400);
}
},
scrollTo: function (x, y, time, relative) {
var that = this,
step = x,
i, l;
that.stop();
if (!step.length) step = [{ x: x, y: y, time: time, relative: relative }];
for (i=0, l=step.length; i<l; i++) {
if (step[i].relative) { step[i].x = that.x - step[i].x; step[i].y = that.y - step[i].y; }
that.steps.push({ x: step[i].x, y: step[i].y, time: step[i].time || 0 });
}
that._startAni();
},
scrollToElement: function (el, time) {
var that = this, pos;
el = el.nodeType ? el : that.scroller.querySelector(el);
if (!el) return;
pos = that._offset(el);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
pos.left = pos.left > 0 ? 0 : pos.left < that.maxScrollX ? that.maxScrollX : pos.left;
pos.top = pos.top > that.minScrollY ? that.minScrollY : pos.top < that.maxScrollY ? that.maxScrollY : pos.top;
time = time === undefined ? m.max(m.abs(pos.left)*2, m.abs(pos.top)*2) : time;
that.scrollTo(pos.left, pos.top, time);
},
scrollToPage: function (pageX, pageY, time) {
var that = this, x, y;
time = time === undefined ? 400 : time;
if (that.options.onScrollStart) that.options.onScrollStart.call(that);
if (that.options.snap) {
pageX = pageX == 'next' ? that.currPageX+1 : pageX == 'prev' ? that.currPageX-1 : pageX;
pageY = pageY == 'next' ? that.currPageY+1 : pageY == 'prev' ? that.currPageY-1 : pageY;
pageX = pageX < 0 ? 0 : pageX > that.pagesX.length-1 ? that.pagesX.length-1 : pageX;
pageY = pageY < 0 ? 0 : pageY > that.pagesY.length-1 ? that.pagesY.length-1 : pageY;
that.currPageX = pageX;
that.currPageY = pageY;
x = that.pagesX[pageX];
y = that.pagesY[pageY];
} else {
x = -that.wrapperW * pageX;
y = -that.wrapperH * pageY;
if (x < that.maxScrollX) x = that.maxScrollX;
if (y < that.maxScrollY) y = that.maxScrollY;
}
that.scrollTo(x, y, time);
},
disable: function () {
this.stop();
this._resetPos(0);
this.enabled = false;
// If disabled after touchstart we make sure that there are no left over events
this._unbind(MOVE_EV, window);
this._unbind(END_EV, window);
this._unbind(CANCEL_EV, window);
},
enable: function () {
this.enabled = true;
},
stop: function () {
if (this.options.useTransition) this._unbind(TRNEND_EV);
else cancelFrame(this.aniTime);
this.steps = [];
this.moved = false;
this.animating = false;
},
zoom: function (x, y, scale, time) {
var that = this,
relScale = scale / that.scale;
if (!that.options.useTransform) return;
that.zoomed = true;
time = time === undefined ? 200 : time;
x = x - that.wrapperOffsetLeft - that.x;
y = y - that.wrapperOffsetTop - that.y;
that.x = x - x * relScale + that.x;
that.y = y - y * relScale + that.y;
that.scale = scale;
that.refresh();
that.x = that.x > 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x;
that.y = that.y > that.minScrollY ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
that.scroller.style[transitionDuration] = time + 'ms';
that.scroller.style[transform] = 'translate(' + that.x + 'px,' + that.y + 'px) scale(' + scale + ')' + translateZ;
that.zoomed = false;
},
isReady: function () {
return !this.moved && !this.zoomed && !this.animating;
}
};
function prefixStyle (style) {
if ( vendor === '' ) return style;
style = style.charAt(0).toUpperCase() + style.substr(1);
return vendor + style;
}
dummyStyle = null; // for the sake of it
if (typeof exports !== 'undefined') exports.iScroll = iScroll;
else window.iScroll = iScroll;
})(window, document); | mit |
zekoff/1gam-breakout | js/callbacks/brick-ball-collision.js | 953 | define(['phaser', 'config', 'player-data'], function(Phaser, Config, playerData) {
return function(state, brick) {
brick.damage(1);
playerData.score += Config.scoreBrickDestroy;
state.add.audio('brick_hit').play();
switch (brick.health) {
case 2:
brick.setFrame(state.cache.getFrameData('atlas').getFrameByName('stone_chipped'));
break;
case 1:
brick.setFrame(state.cache.getFrameData('atlas').getFrameByName('stone_cracked'));
break;
case 0:
var emitter = state.add.emitter(brick.body.center.x, brick.body.center.y);
emitter.makeParticles('atlas', brick.frame);
emitter.setScale(0.2, 0.4, 0.2, 0.4);
emitter.setAlpha(1, 0, 500, Phaser.Easing.Quadratic.In);
emitter.start(true, 500, null, 20);
break;
}
};
}); | mit |
piscke/LearningLaravel | app/tests/MockeryTest.php | 584 | <?php
class MockeryTest extends TestCase {
public function testa_somar_memoria_mockery()
{
Calculadora::shouldReceive('somarMemoria')->once()->andReturn(4);
$this->assertEquals(4, Calculadora::somarMemoria());
}
public function testa_somar_memoria_mockery_times()
{
Calculadora::shouldReceive('somarMemoria')->times(3)->andReturn(4, 10, 22);
$this->assertEquals(4, Calculadora::somarMemoria());
$this->assertEquals(10, Calculadora::somarMemoria());
$this->assertEquals(22, Calculadora::somarMemoria());
}
}
| mit |
yuvrajb/InstaAPI | code/Endpoints/Authenticated/Relationships.cs | 19718 | using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Linq;
using System.Text;
using InstaAPI.Auth;
using InstaAPI.Entities;
using InstaAPI.Endpoints.OptionalParameters;
using InstaAPI.InstaException;
using Newtonsoft.Json;
namespace InstaAPI.Endpoints.Authenticated
{
[Serializable]
public class Relationships
{
private InstaConfig Config;
private AuthUser AuthorisedUser;
/****************************************************** CONSTRUCTORS *******************************************************/
/// <summary>
/// <para>instantiate with InstaConfig and AuthUser</para>
/// </summary>
/// <param name="Config"></param>
/// <param name="AuthorisedUser"></param>
public Relationships(InstaConfig Config, AuthUser AuthorisedUser)
{
this.Config = Config;
this.AuthorisedUser = AuthorisedUser;
}
/******************************************************** GETTERS *********************************************************/
/// <summary>
/// <para>gets the list of users that a user follows</para>
/// </summary>
/// <param name="UserId"></param>
/// <param name="Parameters"></param>
/// <returns></returns>
public UserFollows GetUserFollows(String UserId, GetUserFollowsParameters Parameters)
{
UserFollows Follows = null;
try
{
// SET UP REQUEST URI
UriBuilder BaseUri = new UriBuilder();
BaseUri.Scheme = Config.GetUriScheme();
BaseUri.Host = Config.GetApiUriString();
BaseUri.Path = "users/" + UserId + "/follows";
// SET UP QUERY String
NameValueCollection QueryString = System.Web.HttpUtility.ParseQueryString(String.Empty);
QueryString.Add("access_token", AuthorisedUser.AccessToken);
QueryString.Add("count", Parameters.Count.ToString());
QueryString.Add("cursor", Parameters.NextCursor);
// SET THE QUERY StringS
BaseUri.Query = QueryString.ToString();
// CREATE NEW USER FOLLOWS OBJECT
Follows = new UserFollows();
// SEND REQUEST
WebClient Client = new WebClient();
byte[] ResponseData = Client.DownloadData(BaseUri.Uri);
String Response = Encoding.UTF8.GetString(ResponseData);
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(Response);
// CREATE META OBJECT
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
Follows.Meta = Meta;
// CREATE PAGINATION OBJECT
PaginationCursorData Pagination = new PaginationCursorData();
Pagination.NextUrl = ParsedJson.pagination.next_url;
Pagination.NextCursor = ParsedJson.pagination.next_cursor;
Follows.Pagination = Pagination;
// CREATE DATA LIST
List<User> Data = new List<User>();
foreach (dynamic EachUser in ParsedJson.data)
{
// CREATE AND FILL USER OBJECT
User User = new User();
User.UserName = EachUser.username;
User.Bio = EachUser.bio;
User.Website = EachUser.website;
User.ProfilePicture = EachUser.profile_picture;
User.FullName = EachUser.full_name;
User.Id = EachUser.id;
// ADD USER TO THE LIST
Data.Add(User);
}
Follows.Data = Data;
}
catch (WebException WEx)
{
// FETCHES ANY ERROR THROWN BY INSTAGRAM API
Stream ResponseStream = WEx.Response.GetResponseStream();
if (ResponseStream != null)
{
StreamReader ResponseReader = new StreamReader(ResponseStream);
if (ResponseReader != null)
{
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(ResponseReader.ReadToEnd());
// CREATE NEW META OBJECT AND FILL IN DATA
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
Meta.ErrorType = ParsedJson.meta.error_type;
Meta.ErrorMessage = ParsedJson.meta.error_message;
Follows.Meta = Meta;
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.StackTrace);
}
return Follows;
}
/**************************************************************************************************************************/
/// <summary>
/// <para1>gets the list of users who follow the specified user</para1>
/// </summary>
/// <param name="UserId"></param>
/// <param name="Parameters"></param>
/// <returns></returns>
public UserFollowedBy GetUserFollowedBy(String UserId, GetUserFollowedByParameters Parameters)
{
UserFollowedBy FollowedBy = null;
try
{
// SET UP REQUEST URI
UriBuilder BaseUri = new UriBuilder();
BaseUri.Scheme = Config.GetUriScheme();
BaseUri.Host = Config.GetApiUriString();
BaseUri.Path = "users/" + UserId + "/followed-by";
// SET UP QUERY String
NameValueCollection QueryString = System.Web.HttpUtility.ParseQueryString(String.Empty);
QueryString.Add("access_token", AuthorisedUser.AccessToken);
QueryString.Add("count", Parameters.Count.ToString());
QueryString.Add("cursor", Parameters.NextCursor);
// SET THE QUERY StringS
BaseUri.Query = QueryString.ToString();
// CREATE NEW USER FOLLOWS OBJECT
FollowedBy = new UserFollowedBy();
// SEND REQUEST
WebClient Client = new WebClient();
byte[] ResponseData = Client.DownloadData(BaseUri.Uri);
String Response = Encoding.UTF8.GetString(ResponseData);
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(Response);
// CREATE META OBJECT
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
FollowedBy.Meta = Meta;
// CREATE PAGINATION OBJECT
PaginationCursorData Pagination = new PaginationCursorData();
Pagination.NextUrl = ParsedJson.pagination.next_url;
Pagination.NextCursor = ParsedJson.pagination.next_cursor;
FollowedBy.Pagination = Pagination;
// CREATE DATA LIST
List<User> Data = new List<User>();
foreach (dynamic EachUser in ParsedJson.data)
{
// CREATE AND FILL USER OBJECT
User User = new User();
User.UserName = EachUser.username;
User.Bio = EachUser.bio;
User.Website = EachUser.website;
User.ProfilePicture = EachUser.profile_picture;
User.FullName = EachUser.full_name;
User.Id = EachUser.id;
// ADD USER TO THE LIST
Data.Add(User);
}
FollowedBy.Data = Data;
}
catch (WebException WEx)
{
// FETCHES ANY ERROR THROWN BY INSTAGRAM API
Stream ResponseStream = WEx.Response.GetResponseStream();
if (ResponseStream != null)
{
StreamReader ResponseReader = new StreamReader(ResponseStream);
if (ResponseReader != null)
{
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(ResponseReader.ReadToEnd());
// CREATE NEW META OBJECT AND FILL IN DATA
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
Meta.ErrorType = ParsedJson.meta.error_type;
Meta.ErrorMessage = ParsedJson.meta.error_message;
FollowedBy.Meta = Meta;
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.StackTrace);
}
return FollowedBy;
}
/**************************************************************************************************************************/
/// <summary>
/// <para>gets the list of users who have requested to follow</para>
/// </summary>
/// <param name="Parameters"></param>
/// <returns></returns>
public UserRequestedBy GetUserRequestedBy(GetUserRequestedByParameters Parameters)
{
UserRequestedBy Requests = null;
try
{
// SET UP REQUEST URI
UriBuilder BaseUri = new UriBuilder();
BaseUri.Scheme = Config.GetUriScheme();
BaseUri.Host = Config.GetApiUriString();
BaseUri.Path = "users/self/requested-by";
// SET UP QUERY String
NameValueCollection QueryString = System.Web.HttpUtility.ParseQueryString(String.Empty);
QueryString.Add("access_token", AuthorisedUser.AccessToken);
QueryString.Add("count", Parameters.Count.ToString());
QueryString.Add("cursor", Parameters.NextCursor);
// SET THE QUERY StringS
BaseUri.Query = QueryString.ToString();
// CREATE NEW USER FOLLOWS OBJECT
Requests = new UserRequestedBy();
// SEND REQUEST
WebClient Client = new WebClient();
byte[] ResponseData = Client.DownloadData(BaseUri.Uri);
String Response = Encoding.UTF8.GetString(ResponseData);
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(Response);
// CREATE META OBJECT
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
Requests.Meta = Meta;
if (ParsedJson.pagination == null)
{
Requests.Pagination = null;
}
else
{
// CREATE PAGINATION OBJECT
PaginationCursorData Pagination = new PaginationCursorData();
Pagination.NextUrl = ParsedJson.pagination.next_url;
Pagination.NextCursor = ParsedJson.pagination.next_cursor;
Requests.Pagination = Pagination;
}
// CREATE DATA LIST
List<User> Data = new List<User>();
foreach (dynamic EachUser in ParsedJson.data)
{
// CREATE AND FILL USER OBJECT
User User = new User();
User.UserName = EachUser.username;
User.ProfilePicture = EachUser.profile_picture;
User.Id = EachUser.id;
// ADD USER TO THE LIST
Data.Add(User);
}
Requests.Data = Data;
}
catch (WebException WEx)
{
// FETCHES ANY ERROR THROWN BY INSTAGRAM API
Stream ResponseStream = WEx.Response.GetResponseStream();
if (ResponseStream != null)
{
StreamReader ResponseReader = new StreamReader(ResponseStream);
if (ResponseReader != null)
{
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(ResponseReader.ReadToEnd());
// CREATE NEW META OBJECT AND FILL IN DATA
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
Meta.ErrorType = ParsedJson.meta.error_type;
Meta.ErrorMessage = ParsedJson.meta.error_message;
Requests.Meta = Meta;
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.StackTrace);
}
return Requests;
}
/**************************************************************************************************************************/
/// <summary>
/// <para>gets information about relationship to another user</para>
/// </summary>
/// <param name="UserId"></param>
/// <returns></returns>
public UserRelationship GetUserRelationship(String UserId)
{
UserRelationship Relationship = null;
try
{
// SET UP REQUEST URI
UriBuilder BaseUri = new UriBuilder();
BaseUri.Scheme = Config.GetUriScheme();
BaseUri.Host = Config.GetApiUriString();
BaseUri.Path = "users/"+ UserId +"/relationship";
// SET UP QUERY String
NameValueCollection QueryString = System.Web.HttpUtility.ParseQueryString(String.Empty);
QueryString.Add("access_token", AuthorisedUser.AccessToken);
// SET THE QUERY StringS
BaseUri.Query = QueryString.ToString();
// CREATE NEW USER FOLLOWS OBJECT
Relationship = new UserRelationship();
// SEND REQUEST
WebClient Client = new WebClient();
byte[] ResponseData = Client.DownloadData(BaseUri.Uri);
String Response = Encoding.UTF8.GetString(ResponseData);
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(Response);
// CREATE META OBJECT
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
Relationship.Meta = Meta;
// CREATE DATA OBJECT
RelationshipData Data = new RelationshipData();
Data.OutgoingStatus = ParsedJson.data.outgoing_status;
Data.IncomingStatus = ParsedJson.data.incoming_status;
Data.TargetUserIsPrivate = ParsedJson.data.target_user_is_private;
Relationship.Data = Data;
}
catch (WebException WEx)
{
// FETCHES ANY ERROR THROWN BY INSTAGRAM API
Stream ResponseStream = WEx.Response.GetResponseStream();
if (ResponseStream != null)
{
StreamReader ResponseReader = new StreamReader(ResponseStream);
if (ResponseReader != null)
{
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(ResponseReader.ReadToEnd());
// CREATE NEW META OBJECT AND FILL IN DATA
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
Meta.ErrorType = ParsedJson.meta.error_type;
Meta.ErrorMessage = ParsedJson.meta.error_message;
Relationship.Meta = Meta;
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.StackTrace);
}
return Relationship;
}
/******************************************************** POSTERS *********************************************************/
/// <summary>
/// <post>pushes the new relationship data to the api</post>
/// </summary>
/// <param name="UserId"></param>
/// <param name="Type"></param>
/// <returns></returns>
public UserRelationship PostUserRelationship(String UserId, RelationshipTypes Type)
{
UserRelationship Relationship = null;
try
{
// SET UP REQUEST URI
UriBuilder BaseUri = new UriBuilder();
BaseUri.Scheme = Config.GetUriScheme();
BaseUri.Host = Config.GetApiUriString();
BaseUri.Path = "users/" + UserId + "/relationship";
// SET UP QUERY String
NameValueCollection PostStrings = System.Web.HttpUtility.ParseQueryString(String.Empty);
PostStrings.Add("access_token", AuthorisedUser.AccessToken);
PostStrings.Add("action", Type.ToString());
// CREATE NEW USER FOLLOWS OBJECT
Relationship = new UserRelationship();
// SEND REQUEST
WebClient Client = new WebClient();
byte[] ResponseData = Client.UploadValues(BaseUri.Uri, PostStrings);
String Response = Encoding.UTF8.GetString(ResponseData);
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(Response);
// CREATE META OBJECT
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
Relationship.Meta = Meta;
// CREATE DATA OBJECT
RelationshipData Data = new RelationshipData();
Data.OutgoingStatus = ParsedJson.data.outgoing_status;
Data.IncomingStatus = String.Empty;
Data.TargetUserIsPrivate = ParsedJson.data.target_user_is_private;
Relationship.Data = Data;
}
catch (WebException WEx)
{
// FETCHES ANY ERROR THROWN BY INSTAGRAM API
Stream ResponseStream = WEx.Response.GetResponseStream();
if (ResponseStream != null)
{
StreamReader ResponseReader = new StreamReader(ResponseStream);
if (ResponseReader != null)
{
// PARSE JSON
dynamic ParsedJson = JsonConvert.DeserializeObject(ResponseReader.ReadToEnd());
// CREATE NEW META OBJECT AND FILL IN DATA
MetaData Meta = new MetaData();
Meta.Code = ParsedJson.meta.code;
Meta.ErrorType = ParsedJson.meta.error_type;
Meta.ErrorMessage = ParsedJson.meta.error_message;
Relationship.Meta = Meta;
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.StackTrace);
}
return Relationship;
}
}
}
| mit |
hezedu/dw | test.js | 1507 | var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
var dw = require('./dw_pre');
var test = {
'start': 'astartbc',
arr: ['ggg', 'hehe'],
obj: {
a1: 'a1',
b1: 'b1'
},
arr_obj: [{
ao1: 'ao1',
ao2: 'ao1'
}],
obj_arr: {
oa1: ['oa2', 'oa3']
},
nu:null,
reg:/kkk/,
end: 'end'
}
/*dw.ite(test, function(v,i,isArray){
if(isArray){
console.log(i);
}else{
console.log('"' + i + '"');
}
//console.log(this);
})*/
/*dw.iteNew(test,{
arr: function(v,i){
console.log(i);
},
obj: function(v,i){
console.log(i);
}
})
dw._ite2(test,function(v,i){
console.log(i);
});*/
/*console.log(t2)
for(var i in t2){
if()
console.log(i)
}*/
var MAX = 1000000;
var t1 = dw.copy(test);
console.log(t1)
console.log('开始(一):');
var startTime = Date.now();
for(var i =0; i < MAX; i++){
dw.copy(test)
}
console.log('用时:', Date.now()-startTime);
console.log('开始(二):');
startTime = Date.now();
for(var i =0; i < MAX; i++){
//dw.copy2(test)
}
console.log('用时:', Date.now()-startTime);
/*suite
// add tests
.add('dw.copy2', function() {
dw.copy(t2);
})
.add('dw.copy', function() {
dw.copy(test);
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
function noop(){}
function noop2(v,i,isArray){
if(isArray){
}
}*/ | mit |
PanosK92/Directus3D | Runtime/Rendering/Gizmos/Grid.cpp | 6290 | /*
Copyright(c) 2016-2020 Panos Karabelas
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//= INCLUDES ================================
#include "Spartan.h"
#include "Grid.h"
#include "../../World/Components/Transform.h"
#include "../../RHI/RHI_VertexBuffer.h"
#include "../../RHI/RHI_IndexBuffer.h"
#include "../../RHI/RHI_Vertex.h"
//===========================================
//= NAMESPACES ================
using namespace std;
using namespace Spartan::Math;
//=============================
namespace Spartan
{
Grid::Grid(shared_ptr<RHI_Device> rhi_device)
{
m_indexCount = 0;
m_terrainHeight = 200;
m_terrainWidth = 200;
vector<RHI_Vertex_PosCol> vertices;
vector<unsigned> indices;
BuildGrid(&vertices, &indices);
CreateBuffers(vertices, indices, rhi_device);
}
const Matrix& Grid::ComputeWorldMatrix(Transform* camera)
{
// To get the grid to feel infinite, it has to follow the camera,
// but only by increments of the grid's spacing size. This gives the illusion
// that the grid never moves and if the grid is large enough, the user can't tell.
const auto gridSpacing = 1.0f;
const auto translation = Vector3
(
static_cast<int>(camera->GetPosition().x / gridSpacing) * gridSpacing,
0.0f,
static_cast<int>(camera->GetPosition().z / gridSpacing) * gridSpacing
);
m_world = Matrix::CreateScale(gridSpacing) * Matrix::CreateTranslation(translation);
return m_world;
}
void Grid::BuildGrid(vector<RHI_Vertex_PosCol>* vertices, vector<uint32_t>* indices)
{
const auto halfSizeW = int(m_terrainWidth * 0.5f);
const auto halfSizeH = int(m_terrainHeight * 0.5f);
for (auto j = -halfSizeH; j < halfSizeH; j++)
{
for (auto i = -halfSizeW; i < halfSizeW; i++)
{
// Become more transparent, the further out we go
const auto alphaWidth = 1.0f - static_cast<float>(Helper::Abs(j)) / static_cast<float>(halfSizeH);
const auto alphaHeight = 1.0f - static_cast<float>(Helper::Abs(i)) / static_cast<float>(halfSizeW);
auto alpha = (alphaWidth + alphaHeight) * 0.5f;
alpha = Helper::Pow(alpha, 10.0f);
// LINE 1
// Upper left.
auto positionX = static_cast<float>(i);
auto positionZ = static_cast<float>(j + 1);
vertices->emplace_back(Vector3(positionX, 0.0f, positionZ), Vector4(1.0f, 1.0f, 1.0f, alpha));
// Upper right.
positionX = static_cast<float>(i + 1);
positionZ = static_cast<float>(j + 1);
vertices->emplace_back(Vector3(positionX, 0.0f, positionZ), Vector4(1.0f, 1.0f, 1.0f, alpha));
// LINE 2
// Upper right.
positionX = static_cast<float>(i + 1);
positionZ = static_cast<float>(j + 1);
vertices->emplace_back(Vector3(positionX, 0.0f, positionZ), Vector4(1.0f, 1.0f, 1.0f, alpha));
// Bottom right.
positionX = static_cast<float>(i + 1);
positionZ = static_cast<float>(j);
vertices->emplace_back(Vector3(positionX, 0.0f, positionZ), Vector4(1.0f, 1.0f, 1.0f, alpha));
// LINE 3
// Bottom right.
positionX = static_cast<float>(i + 1);
positionZ = static_cast<float>(j);
vertices->emplace_back(Vector3(positionX, 0.0f, positionZ), Vector4(1.0f, 1.0f, 1.0f, alpha));
// Bottom left.
positionX = static_cast<float>(i);
positionZ = static_cast<float>(j);
vertices->emplace_back(Vector3(positionX, 0.0f, positionZ), Vector4(1.0f, 1.0f, 1.0f, alpha));
// LINE 4
// Bottom left.
positionX = static_cast<float>(i);
positionZ = static_cast<float>(j);
vertices->emplace_back(Vector3(positionX, 0.0f, positionZ), Vector4(1.0f, 1.0f, 1.0f, alpha));
// Upper left.
positionX = static_cast<float>(i);
positionZ = static_cast<float>(j + 1);
vertices->emplace_back(Vector3(positionX, 0.0f, positionZ), Vector4(1.0f, 1.0f, 1.0f, alpha));
}
}
for (uint32_t i = 0; i < vertices->size(); i++)
{
indices->emplace_back(i);
}
m_indexCount = static_cast<uint32_t>(indices->size());
}
bool Grid::CreateBuffers(vector<RHI_Vertex_PosCol>& vertices, vector<unsigned>& indices, shared_ptr<RHI_Device>& rhi_device)
{
m_vertexBuffer = make_shared<RHI_VertexBuffer>(rhi_device);
if (!m_vertexBuffer->Create(vertices))
{
LOG_ERROR("Failed to create vertex buffer.");
return false;
}
m_indexBuffer = make_shared<RHI_IndexBuffer>(rhi_device);
if (!m_indexBuffer->Create(indices))
{
LOG_ERROR("Failed to create index buffer.");
return false;
}
return true;
}
}
| mit |
binsoul/io-stream | tests/MinimalStreamTest.php | 3582 | <?php
namespace BinSoul\Test\IO\Stream;
use BinSoul\IO\Stream\Stream;
use BinSoul\IO\Stream\AccessMode;
abstract class MinimalStreamTest extends \PHPUnit_Framework_TestCase
{
/**
* @return Stream
*/
abstract protected function buildStream();
/**
* @expectedException \LogicException
*/
public function test_open_throws_exception_if_already_open()
{
$stream = $this->buildStream();
$accessMode = 'w';
try {
$stream->open(new AccessMode($accessMode));
} catch (\Exception $e) {
$accessMode = 'r';
$stream->open(new AccessMode($accessMode));
}
$stream->open(new AccessMode($accessMode));
}
/**
* @expectedException \LogicException
*/
public function test_close_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->close();
}
/**
* @expectedException \LogicException
*/
public function test_read_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->read(3);
}
/**
* @expectedException \LogicException
*/
public function test_write_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->write('abc');
}
/**
* @expectedException \LogicException
*/
public function test_seek_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->seek(0);
}
/**
* @expectedException \LogicException
*/
public function test_tell_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->tell();
}
/**
* @expectedException \LogicException
*/
public function test_flush_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->flush();
}
/**
* @expectedException \LogicException
*/
public function test_eof_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->isEof();
}
/**
* @expectedException \LogicException
*/
public function test_getSize_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->getSize();
}
/**
* @expectedException \LogicException
*/
public function test_getStatistics_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->getStatistics();
}
/**
* @expectedException \LogicException
*/
public function test_isReadable_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->isReadable();
}
/**
* @expectedException \LogicException
*/
public function test_isWritable_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->isWritable();
}
/**
* @expectedException \LogicException
*/
public function test_isSeekable_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->isSeekable();
}
/**
* @expectedException \LogicException
*/
public function test_getMetadata_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->getMetadata();
}
/**
* @expectedException \LogicException
*/
public function test_appendTo_throws_exception_if_not_open()
{
$stream = $this->buildStream();
$stream->appendTo($stream);
}
}
| mit |
Silverpop/node-engage | lib/xml-api/calculate-query.js | 763 | var Engage = require(__dirname + '/../engage-constants');
var validator = require(__dirname + '/../validator');
module.exports = {
options: {
queryId: {
required: true,
assert: validator.assertInteger
},
email: {
required: false,
assert: validator.assertString
}
},
generator: function (options) {
var params = {
"QUERY_ID": options.queryId
};
if (typeof options.email !== 'undefined') {
params["EMAIL"] = options.email;
}
return params;
},
result: {
"JOB_ID": {
rename: 'jobId',
required: true,
assert: validator.coerceInteger
}
}
};
| mit |
rudradevbasak/16384_hex | js/keyboard_input_manager.js | 3772 | function KeyboardInputManager() {
this.events = {};
if (window.navigator.msPointerEnabled) {
//Internet Explorer 10 style
this.eventTouchstart = "MSPointerDown";
this.eventTouchmove = "MSPointerMove";
this.eventTouchend = "MSPointerUp";
} else {
this.eventTouchstart = "touchstart";
this.eventTouchmove = "touchmove";
this.eventTouchend = "touchend";
}
this.listen();
}
KeyboardInputManager.prototype.on = function (event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
};
KeyboardInputManager.prototype.emit = function (event, data) {
var callbacks = this.events[event];
if (callbacks) {
callbacks.forEach(function (callback) {
callback(data);
});
}
};
KeyboardInputManager.prototype.listen = function () {
var self = this;
var map = {
39: 2, // Right
37: 3, // Left
87: 0, // W
69: 1, // E
65: 2, // A
68: 3, // D
90: 4, // Z
88: 5 // X
};
document.addEventListener("keydown", function (event) {
var modifiers = event.altKey || event.ctrlKey || event.metaKey ||
event.shiftKey;
var mapped = map[event.which];
if (!modifiers) {
if (mapped !== undefined) {
event.preventDefault();
self.emit("move", mapped);
}
if (event.which === 32){
var game_restart = confirm('Are you sure?');
if(game_restart == true){
self.restart.bind(self)(event);
}
};
}
});
var retry = document.querySelector(".retry-button");
retry.addEventListener("click", this.restart.bind(this));
retry.addEventListener(this.eventTouchend, this.restart.bind(this));
var keepPlaying = document.querySelector(".keep-playing-button");
keepPlaying.addEventListener("click", this.keepPlaying.bind(this));
keepPlaying.addEventListener("touchend", this.keepPlaying.bind(this));
// Listen to swipe events
var touchStartClientX, touchStartClientY;
var gameContainer = document.getElementsByClassName("game-container")[0];
gameContainer.addEventListener(this.eventTouchstart, function (event) {
if (( !window.navigator.msPointerEnabled && event.touches.length > 1) || event.targetTouches > 1) return;
if(window.navigator.msPointerEnabled){
touchStartClientX = event.pageX;
touchStartClientY = event.pageY;
} else {
touchStartClientX = event.touches[0].clientX;
touchStartClientY = event.touches[0].clientY;
}
event.preventDefault();
});
gameContainer.addEventListener(this.eventTouchmove, function (event) {
event.preventDefault();
});
gameContainer.addEventListener(this.eventTouchend, function (event) {
if (( !window.navigator.msPointerEnabled && event.touches.length > 0) || event.targetTouches > 0) return;
var touchEndClientX, touchEndClientY;
if(window.navigator.msPointerEnabled){
touchEndClientX = event.pageX;
touchEndClientY = event.pageY;
} else {
touchEndClientX = event.changedTouches[0].clientX;
touchEndClientY = event.changedTouches[0].clientY;
}
var dx = touchEndClientX - touchStartClientX;
var absDx = Math.abs(dx);
var dy = touchEndClientY - touchStartClientY;
var absDy = Math.abs(dy);
if (Math.max(absDx, absDy) > 10) {
// (right : left) : (down : up)
self.emit("move", absDx > absDy ? (dx > 0 ? 3 : 2) : (dy > 0 ? (dx > 0 ? 5 : 4) : (dx > 0 ? 1 : 0)));
}
});
};
KeyboardInputManager.prototype.restart = function (event) {
event.preventDefault();
this.emit("restart");
};
KeyboardInputManager.prototype.keepPlaying = function (event) {
event.preventDefault();
this.emit("keepPlaying");
};
| mit |
HappyChapMedia/be-in-the-show | parts/hc-colophon.php | 1268 | <?php
/**
* HappyChap Colophon Credit
*
*/
?>
<div class="hc-colophon">
<div class="colophon-container">
<a href="http://www.happychap.co" target="_blank" title="Those Chaps are at it again!"><svg id="hc-icon" data-name="hc-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 676 675.99" width="50px" height="50px"><defs><style>.hc-icon-fill{fill:#231f20;}</style></defs><title>HappyChap Creative Co.</title><path class="hc-icon-fill" d="M626.53,315.4L683.77,2.47H7.77L65,315.4v39.24L7.77,678.45h676L626.53,354.64V315.4ZM304.65,469.59H250.09v-98.5H198.36v98.5H143.8V235.18h54.56v92h51.73v-92h54.56v234.4ZM545.7,429.28c-15.16,26.93-50.17,43.09-93.26,43.09-35.36,0-65.32-10.1-86.19-29.28-21.55-19.53-33-51.18-33-90.58,0-32.65,8.08-60.26,23.56-80.8q26.79-35.36,79.8-35.34c20.54,0,39.06,5,50.84,14.14,5.4,4.37,8.42,7.75,13.47,16.16V236.37h53.53v88.88H496.21c-1-31-17.17-48.48-44.1-48.48-33.34,0-51.51,28.29-51.51,80.13,0,48.48,18.18,75.09,51.17,75.09,24.58,0,39.73-15.82,41.08-42.43h63.3c-0.68,16.16-3.71,27.94-10.44,39.73" transform="translate(-7.77 -2.47)"/></svg></a>
<p class="hc-credit">A <a href="http://www.happychap.co" target="_blank" title="Why not see what those Chaps are up to?"><strong>Happy</strong>Chap Creative Co.</a> jam.</p>
</div>
</div>
| mit |
LeanKit-Labs/hyped | spec/behavior/actionWithEmbeddedResources.js | 2400 | module.exports = {
id: 2,
parentId: 1,
title: "child",
_origin: { href: "/test/api/parent/1/child/2", method: "GET" },
_resource: "child",
_action: "self",
_version: 1,
_links: {
self: { href: "/test/api/parent/1/child/2", method: "GET" },
change: { href: "/test/api/parent/1/child/2", method: "PUT" }
},
_embedded: {
grandChildren: [
{ id: 1,
_origin: { href: "/test/api/parent/1/child/2/grand/1", method: "GET" },
_resource: "grandChild",
_action: "self",
_links: {
self: { href: "/test/api/parent/1/child/2/grand/1", method: "GET" },
create: { href: "/test/api/parent/1/child/2/grand", method: "POST" },
delete: { href: "/test/api/parent/1/child/2/grand/1", method: "DELETE" }
},
_version: 1
},
{ id: 2,
_origin: { href: "/test/api/parent/1/child/2/grand/2", method: "GET" },
_resource: "grandChild",
_action: "self",
_links: {
self: { href: "/test/api/parent/1/child/2/grand/2", method: "GET" },
create: { href: "/test/api/parent/1/child/2/grand", method: "POST" },
delete: { href: "/test/api/parent/1/child/2/grand/2", method: "DELETE" }
},
_version: 1
},
{ id: 3,
_origin: { href: "/test/api/parent/1/child/2/grand/3", method: "GET" },
_resource: "grandChild",
_action: "self",
_links: {
self: { href: "/test/api/parent/1/child/2/grand/3", method: "GET" },
create: { href: "/test/api/parent/1/child/2/grand", method: "POST" },
delete: { href: "/test/api/parent/1/child/2/grand/3", method: "DELETE" }
},
_version: 1
},
{ id: 4,
_origin: { href: "/test/api/parent/1/child/2/grand/4", method: "GET" },
_resource: "grandChild",
_action: "self",
_links: {
self: { href: "/test/api/parent/1/child/2/grand/4", method: "GET" },
create: { href: "/test/api/parent/1/child/2/grand", method: "POST" },
delete: { href: "/test/api/parent/1/child/2/grand/4", method: "DELETE" }
},
_version: 1
},
{ id: 5,
_origin: { href: "/test/api/parent/1/child/2/grand/5", method: "GET" },
_resource: "grandChild",
_action: "self",
_links: {
self: { href: "/test/api/parent/1/child/2/grand/5", method: "GET" },
create: { href: "/test/api/parent/1/child/2/grand", method: "POST" },
delete: { href: "/test/api/parent/1/child/2/grand/5", method: "DELETE" }
},
_version: 1
}
]
}
};
| mit |
Ara95/user | src/Admin/AdminController.php | 3175 | <?php
namespace Ara\Admin;
use \Anax\Configure\ConfigureInterface;
use \Anax\Configure\ConfigureTrait;
use \Anax\DI\InjectionAwareInterface;
use \Anax\DI\InjectionAwareTrait;
use \Ara\Admin\HTMLForm\AdminLoginForm;
use \Ara\Admin\HTMLForm\CreateAdminForm;
use \Ara\Admin\HTMLForm\EditAdminForm;
use \Ara\Admin\HTMLForm\DeleteAdminForm;
use \Ara\User\User;
/**
* A controller class for the Admin.
*/
class AdminController implements
ConfigureInterface,
InjectionAwareInterface
{
use ConfigureTrait,
InjectionAwareTrait;
/**
* Get the Admin indexpage.
*
* @throws Exception
*
* @return void
*/
public function getIndex()
{
$this->di->get("auth")->isAdmin(true);
$user = new User();
$user->setDb($this->di->get("db"));
$title = "Min sida";
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
$data = [
"title" => $title,
"users" => $user->findAll(),
];
$view->add("admin/index", $data);
$pageRender->renderPage(["title" => $title]);
}
/**
* Create new users as admin
*
* @return void
*/
public function getPostCreateAdmin()
{
$this->di->get("auth")->isAdmin(true);
$title = "Admin - Skapa en ny användare";
$card = "Användarinformation";
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
$form = new CreateAdminForm($this->di);
$form->check();
$data = [
"form" => $form->getHTML(),
"title" => $title,
"card" => $card
];
$view->add("admin/create", $data);
$pageRender->renderPage(["title" => $title]);
}
/**
* Edit a user as admin.
*
* @return void
*/
public function getPostEditAdmin($id)
{
$this->di->get("auth")->isAdmin(true);
$title = "Admin - Redigera profil";
$card = "Redigera";
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
$form = new EditAdminForm($this->di, $id);
$form->check();
$data = [
"form" => $form->getHTML(),
"card" => $card,
"title" => $title,
];
$view->add("admin/edit", $data);
$pageRender->renderPage(["title" => $title]);
}
/**
* Delete a user
*
* @return void
*/
public function getPostDeleteAdmin($id)
{
$this->di->get("auth")->isAdmin(true);
$title = "Admin - Radera användare";
$card = "Radera användare";
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
$form = new DeleteAdminForm($this->di, $id);
$form->check();
$data = [
"form" => $form->getHTML(),
"card" => $card,
"title" => $title,
];
$view->add("admin/delete", $data);
$pageRender->renderPage(["title" => $title]);
}
}
| mit |
darrencheng0817/AlgorithmLearning | Python/array/twoSum.py | 787 | '''
Created on 2015.11.30
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
@author: Darren
'''
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map={}
for i in range(len(nums)):
if nums[i] in map:
return map[nums[i]]+1,i+1
else:
map[target-nums[i]]=i
return -1,-1 | mit |
groupdocs-metadata/GroupDocs.Metadata-for-.NET | Examples/GroupDocs.Metadata.Examples.CSharp/BasicUsage/FindMetadataProperties.cs | 1208 | // <copyright company="Aspose Pty Ltd">
// Copyright (C) 2011-2021 GroupDocs. All Rights Reserved.
// </copyright>
namespace GroupDocs.Metadata.Examples.CSharp.BasicUsage
{
using System;
using Tagging;
/// <summary>
/// This example demonstrates how to search for specific metadata properties using tags.
/// </summary>
public static class FindMetadataProperties
{
public static void Run()
{
// Constants.InputPptx is an absolute or relative path to your document. Ex: @"C:\Docs\source.pptx"
using (Metadata metadata = new Metadata(Constants.InputPptx))
{
// Fetch all the properties satisfying the predicate:
// property contains the name of the last document editor OR the date/time the document was last modified
var properties = metadata.FindProperties(p => p.Tags.Contains(Tags.Person.Editor) || p.Tags.Contains(Tags.Time.Modified));
foreach (var property in properties)
{
Console.WriteLine("Property name: {0}, Property value: {1}", property.Name, property.Value);
}
}
}
}
}
| mit |
GluuFederation/oxTrust | service/src/main/java/org/gluu/oxtrust/service/uma/UmaScopeService.java | 5766 | /*
* oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxtrust.service.uma;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.gluu.oxtrust.service.OrganizationService;
import org.gluu.oxtrust.util.OxTrustConstants;
import org.gluu.persist.PersistenceEntryManager;
import org.gluu.persist.model.base.SimpleBranch;
import org.gluu.search.filter.Filter;
import org.gluu.util.StringHelper;
import org.oxauth.persistence.model.Scope;
import org.slf4j.Logger;
/**
* Provides operations with scope descriptions
*
* @author Yuriy Movchan Date: 12/07/2012
*/
@ApplicationScoped
public class UmaScopeService implements Serializable {
private static final long serialVersionUID = -3537567020929600777L;
@Inject
private PersistenceEntryManager persistenceEntryManager;
@Inject
private OrganizationService organizationService;
@Inject
private Logger log;
public void addBranch() {
String branchDn = getDnForScope(null);
if (!persistenceEntryManager.hasBranchesSupport(branchDn)) {
return;
}
SimpleBranch branch = new SimpleBranch();
branch.setOrganizationalUnitName("scopes");
branch.setDn(branchDn);
persistenceEntryManager.persist(branch);
}
public boolean containsBranch() {
String branchDn = getDnForScope(null);
if (!persistenceEntryManager.hasBranchesSupport(branchDn)) {
return true;
}
return persistenceEntryManager.contains(branchDn, SimpleBranch.class);
}
public void prepareScopeDescriptionBranch() {
if (!containsBranch()) {
addBranch();
}
}
public Scope getUmaScopeByDn(String dn) {
return persistenceEntryManager.find(Scope.class, dn);
}
public void addUmaScope(Scope scope) {
persistenceEntryManager.persist(scope);
}
public void updateUmaScope(Scope scope) {
persistenceEntryManager.merge(scope);
}
/**
* Remove scope description entry
*
* @param scopeDescription
* Scope description
*/
public void removeUmaScope(Scope scope) {
persistenceEntryManager.remove(scope);
}
/**
* Check if LDAP server contains scope description with specified attributes
*
* @return True if scope description with specified attributes exist
*/
public boolean containsUmaScope(String dn) {
return persistenceEntryManager.contains(dn, Scope.class);
}
/**
* Get all scope descriptions
*
* @return List of scope descriptions
*/
public List<Scope> getAllUmaScope(String... ldapReturnAttributes) {
List<Scope> scopes = persistenceEntryManager.findEntries(getDnForScope(null), Scope.class, null, ldapReturnAttributes);
return filter(scopes);
}
/**
* Search scope descriptions by pattern
*
* @param pattern
* Pattern
* @param sizeLimit
* Maximum count of results
* @return List of scope descriptions
*/
public List<Scope> findUmaScopes(String pattern, int sizeLimit) {
String[] targetArray = new String[] { pattern };
Filter oxIdFilter = Filter.createSubstringFilter("oxId", null, targetArray, null);
Filter displayNameFilter = Filter.createSubstringFilter(OxTrustConstants.displayName, null, targetArray, null);
Filter searchFilter = Filter.createORFilter(oxIdFilter, displayNameFilter);
List<Scope> scopes = persistenceEntryManager.findEntries(getDnForScope(null), Scope.class, searchFilter, sizeLimit);
return filter(scopes);
}
private List<Scope> filter(List<Scope> scopes) {
if (scopes != null) {
return scopes.stream().filter(Scope::isUmaType).collect(Collectors.toList());
} else {
return new ArrayList<>();
}
}
public List<Scope> getAllUmaScopes(int sizeLimit) {
List<Scope> scopes = persistenceEntryManager.findEntries(getDnForScope(null), Scope.class, null, sizeLimit);
return filter(scopes);
}
/**
* Get scope descriptions by example
*
* @param scopeDescription
* Scope description
* @return List of ScopeDescription which conform example
*/
public List<Scope> findScope(Scope scopeDescription) {
List<Scope> scopes = persistenceEntryManager.findEntries(scopeDescription);
return filter(scopes);
}
/**
* Get scope descriptions by Id
*
* @param id
* Id
* @return List of ScopeDescription which specified id
*/
public List<Scope> findUmaScopeById(String id) {
return persistenceEntryManager.findEntries(getDnForScope(null), Scope.class, Filter.createEqualityFilter("oxId", id));
}
/**
* Generate new inum for scope description
*
* @return New inum for scope description
*/
public String generateInumForNewScope() {
String newDn = null;
String newInum = null;
do {
newInum = generateInumForNewScopeImpl();
newDn = getDnForScope(newInum);
} while (containsUmaScope(newDn));
return newInum;
}
private String generateInumForNewScopeImpl() {
return UUID.randomUUID().toString();
}
public String getDnForScope(String inum) {
String orgDn = organizationService.getDnForOrganization();
if (StringHelper.isEmpty(inum)) {
return String.format("ou=scopes,%s", orgDn);
}
return String.format("inum=%s,ou=scopes,%s", inum, orgDn);
}
public Scope getUmaScopeByInum(String inum) {
Scope umaScope = null;
try {
umaScope = persistenceEntryManager.find(Scope.class, getDnForScope(inum));
} catch (Exception e) {
log.error("Failed to find scope by Inum " + inum, e);
}
return umaScope;
}
public Scope getScopeByDn(String Dn) {
try {
return persistenceEntryManager.find(Scope.class, Dn);
} catch (Exception e) {
log.warn("", e);
return null;
}
}
}
| mit |
brakmic/OpenUI5_Table_Demo | Scripts/vendor/sap/resources/sap/ui/commons/form/GridContainerData-dbg.js | 1707 | /*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.commons.form.GridContainerData.
sap.ui.define(['jquery.sap.global', 'sap/ui/commons/library', 'sap/ui/layout/form/GridContainerData'],
function(jQuery, library, GridContainerData1) {
"use strict";
/**
* Constructor for a new form/GridContainerData.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Grid layout specific properties for FormContainers.
* The width and height properties of the elements are ignored since the witdh and heights are defined by the grid cells.
* @extends sap.ui.layout.form.GridContainerData
*
* @author SAP SE
* @version 1.26.8
*
* @constructor
* @public
* @since 1.9.1
* @deprecated Since version 1.16.0.
* moved to sap.ui.layout library. Please use this one.
* @alias sap.ui.commons.form.GridContainerData
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var GridContainerData = GridContainerData1.extend("sap.ui.commons.form.GridContainerData", /** @lends sap.ui.commons.form.GridContainerData.prototype */ { metadata : {
deprecated : true,
library : "sap.ui.commons"
}});
///**
// * This file defines behavior for the control,
// */
//sap.ui.commons.form.GridLayoutdata.prototype.init = function(){
// // do something for initialization...
//};
return GridContainerData;
}, /* bExport= */ true);
| mit |
pdkramer/Chris40 | Properties/AssemblyInfo.cs | 1072 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Chris40")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Vulcan Software LLC")]
[assembly: AssemblyProduct("Chris40")]
[assembly: AssemblyCopyright("Copyright © 2016 Vulcan Software LLC")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | mit |
InnovateUKGitHub/innovation-funding-service | common/ifs-error-util/src/main/java/org/innovateuk/ifs/commons/error/ValidationMessages.java | 9856 | package org.innovateuk.ifs.commons.error;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import javax.validation.ConstraintViolation;
import java.io.Serializable;
import java.util.*;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.commons.error.Error.fieldError;
import static org.innovateuk.ifs.commons.error.Error.globalError;
import static org.innovateuk.ifs.commons.error.ErrorConverterFactory.asGlobalErrors;
import static org.innovateuk.ifs.commons.error.ErrorConverterFactory.fieldErrorsToFieldErrors;
import static org.innovateuk.ifs.util.CollectionFunctions.*;
/**
* Resource object to return validation messages on rest calls.
*/
@EqualsAndHashCode
@ToString
public class ValidationMessages implements ErrorHolder, Serializable {
private String objectName;
private Long objectId;
private Set<Error> errors = new LinkedHashSet<>();
public ValidationMessages() {
}
public ValidationMessages(Long objectId) {
this.objectId = objectId;
}
public ValidationMessages(BindingResult bindingResult) {
populateFromBindingResult(null, bindingResult);
}
public ValidationMessages(Long objectId, BindingResult bindingResult) {
populateFromBindingResult(objectId, bindingResult);
}
public ValidationMessages(Long objectId, ValidationMessages messages) {
this.objectId = objectId;
this.errors = new LinkedHashSet<>(messages.getErrors());
}
public <T> ValidationMessages(Set<ConstraintViolation<T>> constraintViolations) {
List<Error> fieldErrors = simpleMap(constraintViolations,
violation -> fieldError(violation.getPropertyPath().toString(),
violation.getInvalidValue(),
stripCurlyBrackets(violation.getMessageTemplate()),
asList(violation.getConstraintDescriptor().getAttributes().get("value"))));
errors.addAll(fieldErrors);
}
public ValidationMessages(Error... errors) {
this(asList(errors));
}
public ValidationMessages(List<Error> errors) {
this.errors.addAll(errors);
}
public boolean hasErrorWithKey(Object key) {
return errors.stream().anyMatch(e -> e.getErrorKey().equals(key + ""));
}
public boolean hasFieldErrors(String fieldName) {
return errors.stream().anyMatch(e -> fieldName.equals(e.getFieldName()));
}
public List<Error> getFieldErrors(String fieldName) {
return simpleFilter(errors, e -> fieldName.equals(e.getFieldName()));
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public Long getObjectId() {
return objectId;
}
public void setObjectId(Long objectId) {
this.objectId = objectId;
}
public List<Error> getErrors() {
return new ArrayList<>(errors);
}
public void setErrors(List<Error> errors) {
this.errors.clear();
this.errors.addAll(errors);
}
public boolean hasErrors() {
return !getErrors().isEmpty();
}
public void addError(Error error) {
errors.add(error);
}
public void addAll(ErrorHolder messages) {
if (messages != null) {
addAnyErrors(messages.getErrors());
}
}
public void addAll(ErrorHolder messages, ErrorConverter converter, ErrorConverter... otherConverters) {
if (messages != null) {
addAnyErrors(messages.getErrors(), converter, otherConverters);
}
}
public void addAll(List<ValidationMessages> messages) {
messages.forEach(list -> addAnyErrors(list.getErrors()));
}
public void addAll(List<ValidationMessages> messages, ErrorConverter converter, ErrorConverter... otherConverters) {
messages.forEach(list -> addAnyErrors(list.getErrors(), converter, otherConverters));
}
private void addAnyErrors(List<Error> errors) {
addAnyErrors(errors, fieldErrorsToFieldErrors(), asGlobalErrors());
}
private void addAnyErrors(List<Error> errors, ErrorConverter converter, ErrorConverter... otherConverters) {
errors.forEach(e -> {
List<Optional<Error>> optionalConversionsForThisError = simpleMap(combineLists(converter, otherConverters), fn -> fn.apply(e));
Optional<Optional<Error>> successfullyConvertedErrorList = simpleFindFirst(optionalConversionsForThisError, Optional::isPresent);
successfullyConvertedErrorList.ifPresent(error -> this.errors.add(error.get()));
});
}
public void addErrors(List<Error> errors) {
this.errors.addAll(errors);
}
public static ValidationMessages noErrors() {
return new ValidationMessages();
}
public static ValidationMessages noErrors(Long objectId) {
return new ValidationMessages(objectId);
}
public static ValidationMessages fromErrors(List<Error> errors) {
return new ValidationMessages(errors);
}
public static ValidationMessages fromBindingResult(BindingResult bindingResult) {
return new ValidationMessages(bindingResult);
}
public static ValidationMessages collectValidationMessages(List<ValidationMessages> messages) {
ValidationMessages combined = new ValidationMessages();
combined.addAll(messages);
return combined;
}
private void populateFromBindingResult(Long objectId, BindingResult bindingResult) {
List<Error> fieldErrors = simpleMap(bindingResult.getFieldErrors(), e -> fieldError(e.getField(), e.getRejectedValue(),
getErrorKeyFromBindingError(e), getArgumentsFromBindingError(e)));
List<Error> globalErrors = simpleMap(bindingResult.getGlobalErrors(), e -> globalError(getErrorKeyFromBindingError(e),
getArgumentsFromBindingError(e)));
errors.addAll(combineLists(fieldErrors, globalErrors));
objectName = bindingResult.getObjectName();
this.objectId = objectId;
}
// The Binding Errors in the API contain error keys which can be looked up in the web layer (or used in another client
// of this API) to produce plain english messages, but it is not the responsibility of the API to produce plain
// english messages. Therefore, the "defaultMessage" value in these errors is actually the key that is needed by
// the web layer to produce the appropriate messages e.g. "validation.standard.email.length.max".
//
// The format we receive these in at this point is "{validation.standard.email.length.max}", so we need to ensure
// that the curly brackets are stripped off before returning to the web layer
private String getErrorKeyFromBindingError(ObjectError e) {
String messageKey = e.getDefaultMessage();
if (messageKey == null) {
return null;
}
return stripCurlyBrackets(messageKey);
}
private String stripCurlyBrackets(String key) {
if (key.startsWith("{") && key.endsWith("}")) {
return key.substring(1, key.length() - 1);
}
return key;
}
//
// The arguments provided by the Binding Errors here include as their first argument a version of all the error message
// information itself stored as a MessageSourceResolvable. We don't want to be sending this across to the web layer
// as it's useless information. We also can't really filter it out entirely because the resource bundle entries in the
// web layer expect the useful arguments from a Binding Error to be in a particular position in order to work (for instance,
//
// "validation.standard.lastname.length.min=Your last name should have at least {2} characters"
//
// expects the actual useful argument to be in array index 2, and this is a resource bundle argument that potentially
// could be got from either the data layer or the web layer, so it's best that we retain the original order of arguments
// in the data layer to make these resource bundle entries reusable. Therefore, we're best off just replacing the
// MessageSourceResolvable argument with a blank entry.
//
private List<Object> getArgumentsFromBindingError(ObjectError e) {
Object[] originalArguments = e.getArguments();
if (originalArguments == null || originalArguments.length == 0) {
return emptyList();
}
return simpleMap(asList(originalArguments), arg -> getValidMessageArgument(arg).orElse(""));
}
private Optional<Object> getValidMessageArgument(Object arg) {
if (arg == null) {
return Optional.ofNullable(arg);
}
if(arg instanceof DefaultMessageSourceResolvable) {
return Optional.empty();
}
if (arg instanceof MessageSourceResolvable) {
return Optional.of((((MessageSourceResolvable) arg).getDefaultMessage()));
}
if (arg.getClass().isArray() && ((Object[]) arg).length == 0) {
return Optional.empty();
}
return Optional.of(arg);
}
public static void rejectValue(Errors errors, String fieldName, String errorKey, Object... arguments) {
errors.rejectValue(fieldName, errorKey, arguments, errorKey);
}
public static void reject(Errors errors, String errorKey, Object... arguments) {
errors.reject(errorKey, arguments, errorKey);
}
}
| mit |
MaaZtyle/Averroes-Angular | app/home/ordonnance.component.ts | 976 | /**
* Created by Maazouza on 07/05/2017.
*/
import {Component, Input, OnInit} from "@angular/core";
import {DossierMedical} from "../_models/dossierMedical";
import {OrdonnanceService} from "../_services/ordonnance.service";
import {Ordonnance} from "../_models/ordonnance";
@Component({
selector: 'ordonnances',
moduleId: module.id,
templateUrl: 'ordonnance.component.html',
})
export class OrdonnanceComponent {
@Input()
dossierMedical: DossierMedical;
ordonnances: Ordonnance[];
constructor(private ordonnanceService: OrdonnanceService) { }
getOrdonnances() {
//console.log(dossierMedical.idDos);
this.ordonnanceService.getOrdonnances(this.dossierMedical.idDos.toString())
.subscribe(reponse => {
this.ordonnances = reponse;
console.log(this.ordonnances);
})
}
ngOnInit() {
// reset ordonnances
this.getOrdonnances();
}
}
| mit |
ruigomeseu/rescue-rover | src/rescuerover/test/MapUnitTest.java | 4872 | package rescuerover.test;
import static org.junit.Assert.*;
import org.junit.Test;
import rescuerover.gui.TileMap;
import rescuerover.logic.*;
import java.awt.*;
public class MapUnitTest {
Hero hero;
TileSet tileSet;
TileMap tileMap;
Map map;
public void setUp(int heroX, int heroY) {
tileSet = new TileSet(32, 25, 18, "/tileset.png");
tileSet.loadTile();
tileSet.loadTilesProperties("/tileproperties", ",");
tileMap = new TileMap(new Dimension(30, 30), "/map");
tileMap.setTileSet(tileSet);
// Set different position to start showing map
tileMap.setPosition(-3, -1);
tileMap.setTileDimension(new Dimension(Constants.WIDTH / Constants.VISIBLE_TILES, Constants.HEIGHT / Constants.VISIBLE_TILES));
tileMap.setShowDimension(new Dimension(Constants.VISIBLE_TILES, Constants.VISIBLE_TILES));
// loads the map from map file
tileMap.loadMap(0, ",");
map = new Map(tileMap);
hero = new Hero(heroX, heroY, Constants.UP, map);
map.addMapObject(hero);
tileMap.setHero(hero);
}
/**
* Adds a new hero and moves it to the left
*/
@Test
public void testHeroMoveLeft() {
setUp(2, 4);
int heroLastX = hero.getX();
int heroLastY = hero.getY();
hero.move(Constants.LEFT);
//simulate the 6 sprites moving from one block to the next one
for(int i = 0; i<6; i++)
hero.step();
assertEquals(heroLastY, hero.getY());
assertEquals(heroLastX - 1, hero.getX());
assertEquals(hero.getDirection(), Constants.LEFT);
}
/**
* Adds a new hero and moves it to the right
*/
@Test
public void testHeroMoveRight() {
setUp(2, 4);
int heroLastX = hero.getX();
int heroLastY = hero.getY();
hero.move(Constants.RIGHT);
//simulate the 6 sprites moving from one block to the next one
for(int i = 0; i<6; i++)
hero.step();
assertEquals(heroLastY, hero.getY());
assertEquals(heroLastX + 1, hero.getX());
assertEquals(hero.getDirection(), Constants.RIGHT);
}
/**
* Adds a new hero and moves it up
*/
@Test
public void testHeroMoveUp() {
setUp(2, 4);
int heroLastX = hero.getX();
int heroLastY = hero.getY();
hero.move(Constants.UP);
//simulate the 6 sprites moving from one block to the next one
for(int i = 0; i<6; i++)
hero.step();
assertEquals(heroLastY - 1, hero.getY());
assertEquals(heroLastX, hero.getX());
assertEquals(hero.getDirection(), Constants.UP);
}
/**
* Adds a new hero and moves it down
*/
@Test
public void testHeroMoveDown() {
setUp(2, 4);
int heroLastX = hero.getX();
int heroLastY = hero.getY();
hero.move(Constants.DOWN);
//simulate the 6 sprites moving from one block to the next one
for(int i = 0; i<6; i++)
hero.step();
assertEquals(heroLastY + 1, hero.getY());
assertEquals(heroLastX, hero.getX());
assertEquals(hero.getDirection(), Constants.DOWN);
}
/**
* Adds a new hero and moves (invalidly) it to the left
* The position remains the same but the direction that
* the hero's facing changes accordingly to the failed
* movement.
*/
@Test
public void testHeroInvalidMovement() {
setUp(1, 4);
int heroLastX = hero.getX();
int heroLastY = hero.getY();
hero.move(Constants.LEFT);
assertFalse(hero.isMoving());
assertEquals(heroLastY, hero.getY());
assertEquals(heroLastX, hero.getX());
assertEquals(hero.getDirection(), Constants.LEFT);
}
/**
* Adds a new hero next to the dog. The hero
* moves to the dog position and catches
* the dog.
*/
@Test
public void testHeroCatchDog() {
setUp(1, 4);
Dog dog = new Dog(2, 4, Constants.LEFT);
map.addMapObject(dog);
assertFalse(hero.hasDog());
hero.move(Constants.RIGHT);
//simulate the 6 sprites moving from one block to the next one
for(int i = 0; i<6; i++)
hero.step();
assertTrue(hero.hasDog());
assertTrue(dog.getWithHero());
}
/**
* Adds a new hero next to the key. The hero
* moves to the key position and catches
* the key.
*/
@Test
public void testHeroCatchKey() {
setUp(1, 4);
Key key = new Key(2, 4, Constants.LEFT, "real");
map.addMapObject(key);
assertFalse(hero.hasKey());
hero.move(Constants.RIGHT);
//simulate the 6 sprites moving from one block to the next one
for(int i = 0; i<6; i++)
hero.step();
assertTrue(hero.hasKey());
assertTrue(key.getWithHero());
}
} | mit |
WestLangley/three.js | test/unit/src/extras/core/Path.tests.js | 1625 | /* global QUnit */
import { Path } from '../../../../../src/extras/core/Path.js';
export default QUnit.module( 'Extras', () => {
QUnit.module( 'Core', () => {
QUnit.module( 'Path', () => {
// INHERITANCE
QUnit.todo( 'Extending', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
// INSTANCING
QUnit.todo( 'Instancing', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
// PUBLIC STUFF
QUnit.todo( 'fromPoints', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'moveTo', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'lineTo', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'quadraticCurveTo', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'bezierCurveTo', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'splineThru', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'arc', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'absarc', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'ellipse', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'absellipse', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
} );
} );
} );
| mit |
tommo/gii | lib/mock/asset/helper/simple_psd_writer.py | 11811 | # -*- coding: utf-8 -*-
from struct import *
BLENDMODES = {
'pass through' : 'pass',
'normal' : 'norm',
'dissolve' : 'diss',
'darken' : 'dark',
'multiply' : 'mul ',
'color burn' : 'idiv',
'linear burn' : 'lbrn',
'darker color' : 'dkCl',
'lighten' : 'lite',
'screen' : 'scrn',
'color dodge' : 'div ',
'linear dodge' : 'lddg',
'lighter color' : 'lgCl',
'overlay' : 'over',
'soft light' : 'sLit',
'hard light' : 'hLit',
'vivid light' : 'vLit',
'linear light' : 'lLit',
'pin light' : 'pLit',
'hard mix' : 'hMix',
'difference' : 'diff',
'exclusion' : 'smud',
'subtract' : 'fsub',
'divide' : 'fdiv',
'hue' : 'hue ',
'saturation' : 'sat ',
'color' : 'colr',
'luminosity' : 'lum '
}
COMPRESSION = {
'raw': 0,
'rle': 1,
'zip without prediction': 2,
'zip with prediction': 3
}
class DataView():
def __init__( self, buf, off = 0 ):
self.buf = buf
self.offset = off
def setU8( self, offset, n ):
self.buf[offset] = pack('B', n)
def setU16( self, offset, n ):
self.buf[offset:offset+2] = pack('>H', n)
def setU32( self, offset, n ):
self.buf[offset:offset+4] = pack('>I', n)
def setByteData( self, offset, bytearr, length ):
self.buf[offset:offset+length] = bytearr
def setByteArray( self, offset, bytearr ):
l = len( bytearr )
self.setU32( offset, l )
self.setByteData( offset + 4, bytearr, l )
def pad2(l):
return l % 2
def pad4(l):
return (4 - (l % 4)) % 4
def unicodeString(value): # 4 byte length + ucs2
raw = value.encode( 'utf-16-be' )
output = bytearray( len(raw) + 4 )
output[0:4] = pack('>I', len( value ) )
output[4:] = bytes(raw)
return output
def pascalString(value): # 1 byte length + asc
value = value.encode('utf-8')
value = value[0:255]
output = bytearray( len(value) + 1 )
output[0] = len(value)
output[1:] = value
return output
def copyArray( tgt, src ):
#TODO
pass
def writeSignature(view, offset, value):
data = bytearray( value )
view.setU8( offset, data[0] )
view.setU8( offset + 1, data[1] )
view.setU8( offset + 2, data[2] )
view.setU8( offset + 3, data[3] )
def buildImageResource(resourceId, resourceData):
buf = bytearray(12 + len(resourceData))
view = DataView(buf)
writeSignature(view, 0, '8BIM')
view.setU16(4, resourceId | 0)
# two zero byte for null name
view.setByteArray( 12, resourceData )
return buf
def extractChannelImageData(imageData, channelCount, channelOffset, compression):
if compression != COMPRESSION['raw']:
compression = COMPRESSION['raw'] # TODO: support rle
pixelCount = len(imageData) / channelCount
data = bytearray(2 + pixelCount)
data[1] = compression
i = 2
j = channelOffset
l = len( imageData )
while j < l:
data[i] = imageData[j]
i += 1
j += channelCount
return data
def buildAdditionalLayerInformation(key, data):
dataLength = len(data) + pad2(len(data)) # length of data with padding
buf = bytearray(
4 + # signature
4 + # key
4 + # length of data
dataLength
)
view = DataView(buf)
writeSignature(view, 0, '8BIM')
writeSignature(view, 4, key)
view.setByteArray( 8, data )
return buf
def addByteLength( prev, curr ):
return prev + len(curr)
def addLength( prev, curr ):
return prev + len(curr)
def buildLayerRecord(top, left, bottom, right,
name, opacity, blendMode,
rLen, gLen, bLen, aLen,
additionalLayerInformationList):
nameData = pascalString(name)
padding = pad4(len(nameData))
additionalLayerInformationArrayByteLength = \
reduce( addByteLength, additionalLayerInformationList, 0 )
extraDataFieldLength = 4 # no mask data
extraDataFieldLength+= 44 # 4 byte for length + src, dst blending ranges per channel (gray + g + b + a)
extraDataFieldLength+= len(nameData) + padding # name
extraDataFieldLength+= additionalLayerInformationArrayByteLength
buf = bytearray(
16 + # top, left, bottom, right
2 + # number of channels. 4
24 + # channel information(6) * number of channels(4)
4 + # signature
4 + # blend mode key
1 + # opacity
1 + # clipping
1 + # flags
1 + # filler
4 + # length of extra data field
extraDataFieldLength
)
view = DataView(buf)
view.setU32(0, top)
view.setU32(4, left)
view.setU32(8, bottom)
view.setU32(12, right)
view.setU16(16, 4) # number of channels
view.setU16(18, 0) # red
view.setU32(20, rLen) # red channel data length
view.setU16(24, 1) # green
view.setU32(26, gLen) # green channel data length
view.setU16(30, 2) # blue
view.setU32(32, bLen) # blue channel data length
view.setU16(36, 0xffff) # alpha
view.setU32(38, aLen) # alpha channel data length
writeSignature(view, 42, '8BIM')
writeSignature(view, 46, BLENDMODES[blendMode])
view.setU8(50, (opacity * 0xff) | 0) # opacity
view.setU8(51, 0) # clipping
view.setU8(52, 8) # flags. TODO: visibility
view.setU8(53, 0) # filler
view.setU32(54, extraDataFieldLength)
view.setU32(58, 0) # no mask data
view.setU32(62, 40) # length of layer blending ranges data
view.setU32(66, 0x0000ffff) # gray src range
view.setU32(70, 0x0000ffff) # gray dst range
view.setU32(74, 0x0000ffff) # red src range
view.setU32(78, 0x0000ffff) # red dst range
view.setU32(82, 0x0000ffff) # green src range
view.setU32(86, 0x0000ffff) # green dst range
view.setU32(90, 0x0000ffff) # blue src range
view.setU32(94, 0x0000ffff) # blue dst range
view.setU32(98, 0x0000ffff) # alpha src range
view.setU32(102, 0x0000ffff) # alpha dst range
view.setByteData( 106, nameData, len(nameData) )
offset = 106 + len(nameData) + padding
for additionalLayerInformation in additionalLayerInformationList:
view.setByteData( offset, additionalLayerInformation, len(additionalLayerInformation) )
offset += len(additionalLayerInformation)
return buf
def buildLayerInfo(layers):
channelImageDataList = []
layerRecordList = []
for layer in layers:
top = layer.get( 'y', 0 )
left = layer.get( 'x', 0 )
bottom = top + (layer.get( 'height', 0) )
right = left + (layer.get( 'width', 0) )
name = layer.get( 'name', '' )
opacity = layer.get( 'opacity', 1 )
blendMode = layer.get( 'blendMode', 'normal' )
additionalLayerInformationList = []
imageData = layer.get( 'imageData', None )
compression = COMPRESSION['raw']
rImageData = extractChannelImageData( imageData, 4, 0, compression )
gImageData = extractChannelImageData( imageData, 4, 1, compression )
bImageData = extractChannelImageData( imageData, 4, 2, compression )
aImageData = extractChannelImageData( imageData, 4, 3, compression )
channelImageDataList += [ rImageData, gImageData, bImageData, aImageData ]
data = unicodeString(name)
additionalLayerInformationList.append(
buildAdditionalLayerInformation('luni', data)
)
# TODO? fx: drop shadow, glow, bevel...
record = buildLayerRecord(
top, left, bottom, right,
name, opacity, blendMode,
len(rImageData), len(gImageData), len(bImageData), len(aImageData),
additionalLayerInformationList
)
layerRecordList.append( record )
layerRecordArrayByteLength = reduce( addByteLength, layerRecordList, 0 )
channelImageDataArrayByteLength = reduce( addLength, channelImageDataList, 0 )
layerInfoLength = ( 2 + # layer count
layerRecordArrayByteLength +
channelImageDataArrayByteLength +
pad2(channelImageDataArrayByteLength) )# padding
buf = bytearray(
4 + # length
layerInfoLength
)
view = DataView(buf)
view.setU32(0, layerInfoLength)
view.setU16(4, len(layers))
offset = 6
for layerRecord in layerRecordList: #buf
view.setByteData( offset, layerRecord, len( layerRecord ) )
offset += len( layerRecord )
for channelImageData in channelImageDataList:
view.setByteData( offset, channelImageData, len( channelImageData ) )
offset += len(channelImageData)
return buf
class PsdWriter():
def __init__( self, **option ):
self.layers = []
self.width = option[ 'width' ]
self.height = option[ 'height' ]
self.backgroundColor = option[ 'backgroundColor' ]
self.layers = option[ 'layers' ]
self.flattenedImageData = option[ 'flattenedImageData' ]
def writeFileHeader( self ):
data = bytearray(4 + 2 + 6 + 2 + 4 + 4 + 2 + 2)
view = DataView(data)
writeSignature(view, 0, '8BPS') # 0 Signature
view.setU16(4, 1) # version
view.setU16(12, 4) # number of channels, RGBA
view.setU32(14, self.height | 0) # height of the image in pixels
view.setU32(18, self.width | 0) # width of the image in pixels
view.setU16(22, 8) # depth, 1 byte per channel
view.setU16(24, 3) # color mode, RGB
return data
def writeColorModeData( self ):
buf = bytearray(4)
return buf
def writeImageResources( self ):
self = self
imageResourceArray = []
# if (self.backgroundColor != undefined):
# (def ():
# buf = bytearray(8)
# view = DataView(buf)
# view.setU16(0, 0) # RGB
# view.setU16(2, (self.backgroundColor.r * 0xffff) | 0)
# view.setU16(4, (self.backgroundColor.g * 0xffff) | 0)
# view.setU16(6, (self.backgroundColor.b * 0xffff) | 0)
# imageResourceArray.append(buildImageResource(0x03f2, buf))
# })()
# }
totalLength = reduce( addByteLength, imageResourceArray, 0 )
buf = bytearray(totalLength + 4)
view = DataView(buf)
view.setU32(0, totalLength)
offset = 4
for imageResource in imageResourceArray:
view.setByteArray( offset, imageResource )
uint8array.set(newUint8Array(imageResource), offset)
offset += len(imageResource)
return buf
def writeLayerAndMaskInformation( self ):
layerInfo = buildLayerInfo(self.layers)
layerAndMaskInformationByteLength = len(layerInfo) + 4 # no global layer mask information
buf = bytearray(
4 + # length of the layer and mask information section
layerAndMaskInformationByteLength
)
view = DataView(buf)
view.setU32(0, layerAndMaskInformationByteLength)
view.setByteData( 4, layerInfo, len( layerInfo ) )
return buf
def writeImageData( self ):
flattenedImageData = self.flattenedImageData
compression = COMPRESSION['raw']
length = len( flattenedImageData )
buf = bytearray(
2 + # compression
length
)
view = DataView(buf)
view.setU16(0, compression)
offset = 2
# for (i = 0 i < length i += 4) buf[offset++] = flattenedImageData[i]
for i in range( 0, length, 4 ):
buf[offset] = flattenedImageData[i]
offset+=1
# for (i = 1 i < length i += 4) buf[offset++] = flattenedImageData[i]
for i in range( 1, length, 4 ):
buf[offset] = flattenedImageData[i]
offset+=1
# for (i = 2 i < length i += 4) buf[offset++] = flattenedImageData[i]
for i in range( 2, length, 4 ):
buf[offset] = flattenedImageData[i]
offset+=1
# for (i = 3 i < length i += 4) buf[offset++] = flattenedImageData[i]
for i in range( 3, length, 4 ):
buf[offset] = flattenedImageData[i]
offset+=1
return buf
def write( self, path ):
f = file( path, 'w' )
header = self.writeFileHeader()
print( len( header ) )
f.write( self.writeFileHeader() )
f.write( self.writeColorModeData() )
f.write( self.writeImageResources() )
f.write( self.writeLayerAndMaskInformation() )
f.write( self.writeImageData( ) )
f.close()
if __name__ == '__main__':
writer = PsdWriter(
width = 2,
height = 1,
backgroundColor = 1,
flattenedImageData = bytearray([255,0,0,0, 0,255,0,0]),
layers = [
dict(
name = u'我是好人',
imageData = bytearray([0,0,0,0]), #data...
width = 1, # pixel unit
height = 1, # pixel unit
x = 0, # pixel unit
y = 0, # pixel unit
opacity = 1, # 0(transparent) ~ 1(opaque)
blendMode = 'normal' # see below (blend modes)
),
]
)
writer.write( 'test.psd' )
| mit |
innogames/gitlabhq | lib/gitlab/metrics/subscribers/external_http.rb | 3008 | # frozen_string_literal: true
module Gitlab
module Metrics
module Subscribers
# Class for tracking the total time spent in external HTTP
# See more at https://gitlab.com/gitlab-org/labkit-ruby/-/blob/v0.14.0/lib/gitlab-labkit.rb#L18
class ExternalHttp < ActiveSupport::Subscriber
attach_to :external_http
DEFAULT_STATUS_CODE = 'undefined'
DETAIL_STORE = :external_http_detail_store
COUNTER = :external_http_count
DURATION = :external_http_duration_s
def self.detail_store
::Gitlab::SafeRequestStore[DETAIL_STORE] ||= []
end
def self.duration
Gitlab::SafeRequestStore[DURATION].to_f
end
def self.request_count
Gitlab::SafeRequestStore[COUNTER].to_i
end
def self.payload
{
COUNTER => request_count,
DURATION => duration
}
end
def request(event)
payload = event.payload
add_to_detail_store(event.time, payload)
add_to_request_store(payload)
expose_metrics(payload)
end
private
def current_transaction
::Gitlab::Metrics::Transaction.current
end
def add_to_detail_store(start, payload)
return unless Gitlab::PerformanceBar.enabled_for_request?
self.class.detail_store << {
start: start,
duration: payload[:duration],
scheme: payload[:scheme],
method: payload[:method],
host: payload[:host],
port: payload[:port],
path: payload[:path],
query: payload[:query],
code: payload[:code],
exception_object: payload[:exception_object],
backtrace: Gitlab::BacktraceCleaner.clean_backtrace(caller)
}
end
def add_to_request_store(payload)
return unless Gitlab::SafeRequestStore.active?
Gitlab::SafeRequestStore[COUNTER] = Gitlab::SafeRequestStore[COUNTER].to_i + 1
Gitlab::SafeRequestStore[DURATION] = Gitlab::SafeRequestStore[DURATION].to_f + payload[:duration].to_f
end
def expose_metrics(payload)
return unless current_transaction
labels = { method: payload[:method], code: payload[:code] || DEFAULT_STATUS_CODE }
current_transaction.increment(:gitlab_external_http_total, 1, labels) do
docstring 'External HTTP calls'
label_keys labels.keys
end
current_transaction.observe(:gitlab_external_http_duration_seconds, payload[:duration]) do
docstring 'External HTTP time'
buckets [0.001, 0.01, 0.1, 1.0, 2.0, 5.0]
end
if payload[:exception_object].present?
current_transaction.increment(:gitlab_external_http_exception_total, 1) do
docstring 'External HTTP exceptions'
end
end
end
end
end
end
end
| mit |
aykutyaman/meteor1.3-react-flowrouter-demo | node_modules/material-ui/lib/TextField/TextFieldUnderline.js | 3752 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _transitions = require('../styles/transitions');
var _transitions2 = _interopRequireDefault(_transitions);
var _styles = require('../utils/styles');
var _styles2 = _interopRequireDefault(_styles);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var propTypes = {
/**
* True if the parent `TextField` is disabled.
*/
disabled: _react2.default.PropTypes.bool,
/**
* Override the inline-styles of the underline when parent `TextField` is disabled.
*/
disabledStyle: _react2.default.PropTypes.object,
/**
* True if the parent `TextField` has an error.
*/
error: _react2.default.PropTypes.bool,
/**
* Override the inline-styles of the underline when parent `TextField` has an error.
*/
errorStyle: _react2.default.PropTypes.object,
/**
* True if the parent `TextField` is focused.
*/
focus: _react2.default.PropTypes.bool,
/**
* Override the inline-styles of the underline when parent `TextField` is focused.
*/
focusStyle: _react2.default.PropTypes.object,
/**
* The material-ui theme applied to this component.
*/
muiTheme: _react2.default.PropTypes.object.isRequired,
/**
* Override the inline-styles of the underline.
*/
style: _react2.default.PropTypes.object
};
var defaultProps = {
disabled: false,
disabledStyle: {},
error: false,
errorStyle: {},
focus: false,
focusStyle: {},
style: {}
};
var TextFieldUnderline = function TextFieldUnderline(props) {
var disabled = props.disabled;
var disabledStyle = props.disabledStyle;
var error = props.error;
var errorStyle = props.errorStyle;
var focus = props.focus;
var focusStyle = props.focusStyle;
var muiTheme = props.muiTheme;
var style = props.style;
var errorStyleColor = errorStyle.color;
var _muiTheme$textField = muiTheme.textField;
var borderColor = _muiTheme$textField.borderColor;
var disabledTextColor = _muiTheme$textField.disabledTextColor;
var errorColor = _muiTheme$textField.errorColor;
var focusColor = _muiTheme$textField.focusColor;
var styles = {
root: {
border: 'none',
borderBottom: 'solid 1px',
borderColor: borderColor,
bottom: 8,
boxSizing: 'content-box',
margin: 0,
position: 'absolute',
width: '100%'
},
disabled: {
borderBottom: 'dotted 2px',
borderColor: disabledTextColor
},
focus: {
borderBottom: 'solid 2px',
borderColor: focusColor,
transform: 'scaleX(0)',
transition: _transitions2.default.easeOut()
},
error: {
borderColor: errorStyleColor ? errorStyleColor : errorColor,
transform: 'scaleX(1)'
}
};
var underline = _styles2.default.merge(styles.root, style);
var focusedUnderline = _styles2.default.merge(underline, styles.focus, focusStyle);
if (disabled) underline = _styles2.default.merge(underline, styles.disabled, disabledStyle);
if (focus) focusedUnderline = _styles2.default.merge(focusedUnderline, { transform: 'scaleX(1)' });
if (error) focusedUnderline = _styles2.default.merge(focusedUnderline, styles.error);
return _react2.default.createElement(
'div',
null,
_react2.default.createElement('hr', { style: _styles2.default.prepareStyles(muiTheme, underline) }),
_react2.default.createElement('hr', { style: _styles2.default.prepareStyles(muiTheme, focusedUnderline) })
);
};
TextFieldUnderline.propTypes = propTypes;
TextFieldUnderline.defaultProps = defaultProps;
exports.default = TextFieldUnderline;
module.exports = exports['default']; | mit |
chweeks/theatre-web | app/menuView/menuView.js | 286 | 'use strict';
angular.module('myApp.menuView', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/menuView', {
templateUrl: 'menuView/menuView.html',
controller: 'MenuViewCtrl'
});
}])
.controller('MenuViewCtrl', [function() {
}]);
| mit |
lukhinsama/TSSM | linealert/alertImageWeather.php | 5846 | <?php
ini_set('display_errors', 'on');
ini_set('error_reporting', E_ALL);
$con = connectDB_BigHead();
//$tokenLineTestGroup = "AdSnqZWqrq1KsKCnlzDFiwPvEu73XBZkixb5sFZG1DB";
//$tokenTessLukhin = 'TgX4Mj5uao3IJz9O6PdkCk5tCy9cEkIg3jysVOCm3AC';
//ส่งรูปภาพ ฝ่ายขาย
$line_api = 'https://notify-api.line.me/api/notify';
$tokenSale = "IwKC3Z39TdQMlWNCGX6nCheXrQnNaytijEJf1hXezIK";
//$access_token = $tokenLineTestGroup;
$message = "รายงานสภาพอากาศ"; //text max 1,000 charecter
$image_thumbnail_url = 'https://www.tmd.go.th/programs/uploads/satda/latest.jpg'; // max size 240x240px JPEG
$image_fullsize_url = 'https://www.tmd.go.th/programs/uploads/satda/latest.jpg'; //max size 1024x1024px JPEG
$imageFile = 'copy/240.jpg';
$sticker_package_id = ''; // Package ID sticker
$sticker_id = ''; // ID sticker
if (function_exists('curl_file_create')) {
$cFile = curl_file_create($imageFile );
} else {
$cFile = '@'.realpath($imageFile );
}
$message_data = array(
'imageThumbnail' => $image_thumbnail_url,
'imageFullsize' => $image_fullsize_url,
'message' => $message,
'imageFile' => $imageFile,
//'imageFile' => $cFile ,
'stickerPackageId' => $sticker_package_id,
'stickerId' => $sticker_id
);
$result = send_notify_message($line_api, $tokenSale, $message_data);
//echo '<pre>';
//print_r($result);
//echo '</pre>';
//ส่งรูปภาพ ฝ่ายขาย
//ส่งรูปภาพ ฝ่ายสาขา
$line_api = 'https://notify-api.line.me/api/notify';
$tokenBrn = "IwKC3Z39TdQMlWNCGX6nCheXrQnNaytijEJf1hXezIK";
//$access_token = $tokenLineTestGroup;
$message = "รายงานสภาพอากาศ"; //text max 1,000 charecter
$image_thumbnail_url = 'https://www.tmd.go.th/programs/uploads/satda/latest.jpg'; // max size 240x240px JPEG
$image_fullsize_url = 'https://www.tmd.go.th/programs/uploads/satda/latest.jpg'; //max size 1024x1024px JPEG
$imageFile = 'copy/240.jpg';
$sticker_package_id = ''; // Package ID sticker
$sticker_id = ''; // ID sticker
if (function_exists('curl_file_create')) {
$cFile = curl_file_create($imageFile );
} else {
$cFile = '@'.realpath($imageFile );
}
$message_data = array(
'imageThumbnail' => $image_thumbnail_url,
'imageFullsize' => $image_fullsize_url,
'message' => $message,
'imageFile' => $imageFile,
//'imageFile' => $cFile ,
'stickerPackageId' => $sticker_package_id,
'stickerId' => $sticker_id
);
$result = send_notify_message($line_api, $tokenBrn, $message_data);
//echo '<pre>';
//print_r($result);
//echo '</pre>';
//ส่งรูปภาพ ฝ่ายสาขา
sqlsrv_close($con);
function send_notify_message($line_api, $access_token, $message_data){
$headers = array('Method: POST', 'Content-type: multipart/form-data', 'Authorization: Bearer '.$access_token );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $line_api);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
// Check Error
if(curl_error($ch))
{
$return_array = array( 'status' => '000: send fail', 'message' => curl_error($ch) );
}
else
{
$return_array = json_decode($result, true);
}
curl_close($ch);
return $return_array;
}
function notify_message($message,$stickerPkg,$stickerId,$token){
$queryData = array(
'message' => $message,
'stickerPackageId'=>$stickerPkg,
'stickerId'=>$stickerId
);
$queryData = http_build_query($queryData,'','&');
$headerOptions = array(
'http'=>array(
'method'=>'POST',
'header'=> "Content-Type: application/x-www-form-urlencoded\r\n"
."Authorization: Bearer ".$token."\r\n"
."Content-Length: ".strlen($queryData)."\r\n",
'content' => $queryData
),
);
$context = stream_context_create($headerOptions);
$result = file_get_contents(LINE_API,FALSE,$context);
$res = json_decode($result);
return $res;
}
function connectDB_BigHead(){
$db_host = "192.168.110.133";
$db_name = "Bighead_Mobile";
$db_username = "TsrApp";
$db_password = "6z3sNrCzWp";
$connectionInfo = array("Database"=>$db_name, "UID"=>$db_username, "PWD"=>$db_password, 'CharacterSet' => 'UTF-8', "MultipleActiveResultSets"=>true);
$conn = sqlsrv_connect( $db_host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
return $conn;
}
function DateThai($strDate){
$strDate = date_format(date_create($strDate),"Y-m-d H:i:s");
$strYear = date("Y",strtotime($strDate))+543;
$strMonth= date("n",strtotime($strDate));
$strDay= date("j",strtotime($strDate));
$strHour= date("H",strtotime($strDate));
$strMinute= date("i",strtotime($strDate));
$strSeconds= date("s",strtotime($strDate));
$strMonthCut = Array("","ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค.");
$strMonthThai=$strMonthCut[$strMonth];
//return "$strDay $strMonthThai $strYear, $strHour:$strMinute";
return "$strDay $strMonthThai $strYear";
}
?>
| mit |
StevenLiekens/Hls | src/Hls/tag/TagLexerFactory.cs | 6039 | using System;
using Hls.EXTINF;
using Hls.EXT_X_ENDLIST;
using Hls.EXT_X_I_FRAME_STREAM_INF;
using Hls.EXT_X_KEY;
using Hls.EXT_X_MEDIA;
using Hls.EXT_X_MEDIA_SEQUENCE;
using Hls.EXT_X_STREAM_INF;
using Hls.EXT_X_TARGETDURATION;
using Hls.EXT_X_VERSION;
using Hls.ignored_tag;
using Txt.ABNF;
using Txt.Core;
namespace Hls.tag
{
public class TagLexerFactory : LexerFactory<Tag>
{
private readonly IAlternationLexerFactory alternationLexerFactory;
private readonly ILexerFactory<ExtEndList> extEndListLexerFactory;
private readonly ILexerFactory<ExtIFrameStreamInf> extIFrameStreamInfLexerFactory;
private readonly ILexerFactory<ExtInf> extInfLexerFactory;
private readonly ILexerFactory<ExtKey> extKeyLexerFactory;
private readonly ILexerFactory<ExtMedia> extMediaLexerFactory;
private readonly ILexerFactory<ExtMediaSequence> extMediaSequenceLexerFactory;
private readonly ILexerFactory<ExtStreamInf> extStreamInfLexerFactory;
private readonly ILexerFactory<ExtTargetDuration> extTargetDurationLexerFactory;
private readonly ILexerFactory<ExtVersion> extVersionLexerFactory;
private readonly ILexerFactory<IgnoredTag> ignoredTagLexerFactory;
static TagLexerFactory()
{
Default = new TagLexerFactory(
AlternationLexerFactory.Default,
ExtVersionLexerFactory.Default.Singleton(),
ExtInfLexerFactory.Default.Singleton(),
ExtTargetDurationLexerFactory.Default.Singleton(),
ExtStreamInfLexerFactory.Default.Singleton(),
ExtMediaSequenceLexerFactory.Default.Singleton(),
IgnoredTagLexerFactory.Default.Singleton(),
ExtEndListLexerFactory.Default.Singleton(),
ExtMediaLexerFactory.Default.Singleton(),
ExtIFrameStreamInfLexerFactory.Default.Singleton(),
ExtKeyLexerFactory.Default.Singleton());
}
public TagLexerFactory(
IAlternationLexerFactory alternationLexerFactory,
ILexerFactory<ExtVersion> extVersionLexerFactory,
ILexerFactory<ExtInf> extInfLexerFactory,
ILexerFactory<ExtTargetDuration> extTargetDurationLexerFactory,
ILexerFactory<ExtStreamInf> extStreamInfLexerFactory,
ILexerFactory<ExtMediaSequence> extMediaSequenceLexerFactory,
ILexerFactory<IgnoredTag> ignoredTagLexerFactory,
ILexerFactory<ExtEndList> extEndListLexerFactory,
ILexerFactory<ExtMedia> extMediaLexerFactory,
ILexerFactory<ExtIFrameStreamInf> extIFrameStreamInfLexerFactory,
ILexerFactory<ExtKey> extKeyLexerFactory)
{
if (alternationLexerFactory == null)
{
throw new ArgumentNullException(nameof(alternationLexerFactory));
}
if (extVersionLexerFactory == null)
{
throw new ArgumentNullException(nameof(extVersionLexerFactory));
}
if (extInfLexerFactory == null)
{
throw new ArgumentNullException(nameof(extInfLexerFactory));
}
if (extTargetDurationLexerFactory == null)
{
throw new ArgumentNullException(nameof(extTargetDurationLexerFactory));
}
if (extStreamInfLexerFactory == null)
{
throw new ArgumentNullException(nameof(extStreamInfLexerFactory));
}
if (extMediaSequenceLexerFactory == null)
{
throw new ArgumentNullException(nameof(extMediaSequenceLexerFactory));
}
if (ignoredTagLexerFactory == null)
{
throw new ArgumentNullException(nameof(ignoredTagLexerFactory));
}
if (extEndListLexerFactory == null)
{
throw new ArgumentNullException(nameof(extEndListLexerFactory));
}
if (extMediaLexerFactory == null)
{
throw new ArgumentNullException(nameof(extMediaLexerFactory));
}
if (extIFrameStreamInfLexerFactory == null)
{
throw new ArgumentNullException(nameof(extIFrameStreamInfLexerFactory));
}
if (extKeyLexerFactory == null)
{
throw new ArgumentNullException(nameof(extKeyLexerFactory));
}
this.alternationLexerFactory = alternationLexerFactory;
this.extVersionLexerFactory = extVersionLexerFactory;
this.extInfLexerFactory = extInfLexerFactory;
this.extTargetDurationLexerFactory = extTargetDurationLexerFactory;
this.extStreamInfLexerFactory = extStreamInfLexerFactory;
this.extMediaSequenceLexerFactory = extMediaSequenceLexerFactory;
this.ignoredTagLexerFactory = ignoredTagLexerFactory;
this.extEndListLexerFactory = extEndListLexerFactory;
this.extMediaLexerFactory = extMediaLexerFactory;
this.extIFrameStreamInfLexerFactory = extIFrameStreamInfLexerFactory;
this.extKeyLexerFactory = extKeyLexerFactory;
}
public static TagLexerFactory Default { get; }
public override ILexer<Tag> Create()
{
return new TagLexer(
alternationLexerFactory.Create(
extVersionLexerFactory.Create(),
extKeyLexerFactory.Create(),
extInfLexerFactory.Create(),
extTargetDurationLexerFactory.Create(),
extStreamInfLexerFactory.Create(),
extIFrameStreamInfLexerFactory.Create(),
extMediaSequenceLexerFactory.Create(),
extEndListLexerFactory.Create(),
extMediaLexerFactory.Create(),
ignoredTagLexerFactory.Create()));
}
}
}
| mit |
romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/DICOM/InterscanDelay.php | 791 | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class InterscanDelay extends AbstractTag
{
protected $Id = '0019,1044';
protected $Name = 'InterscanDelay';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Interscan Delay';
}
| mit |
romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/SonyIDC/ToneCurveBlueX.php | 843 | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\SonyIDC;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class ToneCurveBlueX extends AbstractTag
{
protected $Id = 36867;
protected $Name = 'ToneCurveBlueX';
protected $FullName = 'SonyIDC::Main';
protected $GroupName = 'SonyIDC';
protected $g0 = 'MakerNotes';
protected $g1 = 'SonyIDC';
protected $g2 = 'Image';
protected $Type = 'int16u';
protected $Writable = true;
protected $Description = 'Tone Curve Blue X';
protected $flag_Permanent = true;
}
| mit |
DonJayamanne/pythonVSCode | src/test/common/utils/regexp.unit.test.ts | 1754 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { expect } from 'chai';
import { verboseRegExp } from '../../../client/common/utils/regexp';
suite('Utils for regular expressions - verboseRegExp()', () => {
test('whitespace removed in multiline pattern (example of typical usage)', () => {
const regex = verboseRegExp(`
^
(?:
spam \\b .*
) |
(?:
eggs \\b .*
)
$
`);
expect(regex.source).to.equal('^(?:spam\\b.*)|(?:eggs\\b.*)$', 'mismatch');
});
const whitespaceTests = [
['spam eggs', 'spameggs'],
[
`spam
eggs`,
'spameggs',
],
// empty
[' ', '(?:)'],
[
`
`,
'(?:)',
],
];
for (const [pat, expected] of whitespaceTests) {
test(`whitespace removed ("${pat}")`, () => {
const regex = verboseRegExp(pat);
expect(regex.source).to.equal(expected, 'mismatch');
});
}
const noopPatterns = ['^(?:spam\\b.*)$', 'spam', '^spam$', 'spam$', '^spam'];
for (const pat of noopPatterns) {
test(`pattern not changed ("${pat}")`, () => {
const regex = verboseRegExp(pat);
expect(regex.source).to.equal(pat, 'mismatch');
});
}
const emptyPatterns = [
'',
`
`,
' ',
];
for (const pat of emptyPatterns) {
test(`no pattern ("${pat}")`, () => {
const regex = verboseRegExp(pat);
expect(regex.source).to.equal('(?:)', 'mismatch');
});
}
});
| mit |
Ptomaine/nstd | include/external/agg/agg/src/agg_gsv_text.cpp | 33776 | //----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Class gsv_text
//
//----------------------------------------------------------------------------
#include <cstring>
#include <cstdio>
#include "agg_gsv_text.h"
#include "agg_bounding_rect.h"
namespace agg
{
int8u gsv_default_font[] =
{
0x40,0x00,0x6c,0x0f,0x15,0x00,0x0e,0x00,0xf9,0xff,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x0d,0x0a,0x0d,0x0a,0x46,0x6f,0x6e,0x74,0x20,0x28,
0x63,0x29,0x20,0x4d,0x69,0x63,0x72,0x6f,0x50,0x72,
0x6f,0x66,0x20,0x32,0x37,0x20,0x53,0x65,0x70,0x74,
0x65,0x6d,0x62,0x2e,0x31,0x39,0x38,0x39,0x00,0x0d,
0x0a,0x0d,0x0a,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,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,0x00,
0x02,0x00,0x12,0x00,0x34,0x00,0x46,0x00,0x94,0x00,
0xd0,0x00,0x2e,0x01,0x3e,0x01,0x64,0x01,0x8a,0x01,
0x98,0x01,0xa2,0x01,0xb4,0x01,0xba,0x01,0xc6,0x01,
0xcc,0x01,0xf0,0x01,0xfa,0x01,0x18,0x02,0x38,0x02,
0x44,0x02,0x68,0x02,0x98,0x02,0xa2,0x02,0xde,0x02,
0x0e,0x03,0x24,0x03,0x40,0x03,0x48,0x03,0x52,0x03,
0x5a,0x03,0x82,0x03,0xec,0x03,0xfa,0x03,0x26,0x04,
0x4c,0x04,0x6a,0x04,0x7c,0x04,0x8a,0x04,0xb6,0x04,
0xc4,0x04,0xca,0x04,0xe0,0x04,0xee,0x04,0xf8,0x04,
0x0a,0x05,0x18,0x05,0x44,0x05,0x5e,0x05,0x8e,0x05,
0xac,0x05,0xd6,0x05,0xe0,0x05,0xf6,0x05,0x00,0x06,
0x12,0x06,0x1c,0x06,0x28,0x06,0x36,0x06,0x48,0x06,
0x4e,0x06,0x60,0x06,0x6e,0x06,0x74,0x06,0x84,0x06,
0xa6,0x06,0xc8,0x06,0xe6,0x06,0x08,0x07,0x2c,0x07,
0x3c,0x07,0x68,0x07,0x7c,0x07,0x8c,0x07,0xa2,0x07,
0xb0,0x07,0xb6,0x07,0xd8,0x07,0xec,0x07,0x10,0x08,
0x32,0x08,0x54,0x08,0x64,0x08,0x88,0x08,0x98,0x08,
0xac,0x08,0xb6,0x08,0xc8,0x08,0xd2,0x08,0xe4,0x08,
0xf2,0x08,0x3e,0x09,0x48,0x09,0x94,0x09,0xc2,0x09,
0xc4,0x09,0xd0,0x09,0xe2,0x09,0x04,0x0a,0x0e,0x0a,
0x26,0x0a,0x34,0x0a,0x4a,0x0a,0x66,0x0a,0x70,0x0a,
0x7e,0x0a,0x8e,0x0a,0x9a,0x0a,0xa6,0x0a,0xb4,0x0a,
0xd8,0x0a,0xe2,0x0a,0xf6,0x0a,0x18,0x0b,0x22,0x0b,
0x32,0x0b,0x56,0x0b,0x60,0x0b,0x6e,0x0b,0x7c,0x0b,
0x8a,0x0b,0x9c,0x0b,0x9e,0x0b,0xb2,0x0b,0xc2,0x0b,
0xd8,0x0b,0xf4,0x0b,0x08,0x0c,0x30,0x0c,0x56,0x0c,
0x72,0x0c,0x90,0x0c,0xb2,0x0c,0xce,0x0c,0xe2,0x0c,
0xfe,0x0c,0x10,0x0d,0x26,0x0d,0x36,0x0d,0x42,0x0d,
0x4e,0x0d,0x5c,0x0d,0x78,0x0d,0x8c,0x0d,0x8e,0x0d,
0x90,0x0d,0x92,0x0d,0x94,0x0d,0x96,0x0d,0x98,0x0d,
0x9a,0x0d,0x9c,0x0d,0x9e,0x0d,0xa0,0x0d,0xa2,0x0d,
0xa4,0x0d,0xa6,0x0d,0xa8,0x0d,0xaa,0x0d,0xac,0x0d,
0xae,0x0d,0xb0,0x0d,0xb2,0x0d,0xb4,0x0d,0xb6,0x0d,
0xb8,0x0d,0xba,0x0d,0xbc,0x0d,0xbe,0x0d,0xc0,0x0d,
0xc2,0x0d,0xc4,0x0d,0xc6,0x0d,0xc8,0x0d,0xca,0x0d,
0xcc,0x0d,0xce,0x0d,0xd0,0x0d,0xd2,0x0d,0xd4,0x0d,
0xd6,0x0d,0xd8,0x0d,0xda,0x0d,0xdc,0x0d,0xde,0x0d,
0xe0,0x0d,0xe2,0x0d,0xe4,0x0d,0xe6,0x0d,0xe8,0x0d,
0xea,0x0d,0xec,0x0d,0x0c,0x0e,0x26,0x0e,0x48,0x0e,
0x64,0x0e,0x88,0x0e,0x92,0x0e,0xa6,0x0e,0xb4,0x0e,
0xd0,0x0e,0xee,0x0e,0x02,0x0f,0x16,0x0f,0x26,0x0f,
0x3c,0x0f,0x58,0x0f,0x6c,0x0f,0x6c,0x0f,0x6c,0x0f,
0x6c,0x0f,0x6c,0x0f,0x6c,0x0f,0x6c,0x0f,0x6c,0x0f,
0x6c,0x0f,0x6c,0x0f,0x6c,0x0f,0x6c,0x0f,0x6c,0x0f,
0x6c,0x0f,0x6c,0x0f,0x6c,0x0f,0x6c,0x0f,0x10,0x80,
0x05,0x95,0x00,0x72,0x00,0xfb,0xff,0x7f,0x01,0x7f,
0x01,0x01,0xff,0x01,0x05,0xfe,0x05,0x95,0xff,0x7f,
0x00,0x7a,0x01,0x86,0xff,0x7a,0x01,0x87,0x01,0x7f,
0xfe,0x7a,0x0a,0x87,0xff,0x7f,0x00,0x7a,0x01,0x86,
0xff,0x7a,0x01,0x87,0x01,0x7f,0xfe,0x7a,0x05,0xf2,
0x0b,0x95,0xf9,0x64,0x0d,0x9c,0xf9,0x64,0xfa,0x91,
0x0e,0x00,0xf1,0xfa,0x0e,0x00,0x04,0xfc,0x08,0x99,
0x00,0x63,0x04,0x9d,0x00,0x63,0x04,0x96,0xff,0x7f,
0x01,0x7f,0x01,0x01,0x00,0x01,0xfe,0x02,0xfd,0x01,
0xfc,0x00,0xfd,0x7f,0xfe,0x7e,0x00,0x7e,0x01,0x7e,
0x01,0x7f,0x02,0x7f,0x06,0x7e,0x02,0x7f,0x02,0x7e,
0xf2,0x89,0x02,0x7e,0x02,0x7f,0x06,0x7e,0x02,0x7f,
0x01,0x7f,0x01,0x7e,0x00,0x7c,0xfe,0x7e,0xfd,0x7f,
0xfc,0x00,0xfd,0x01,0xfe,0x02,0x00,0x01,0x01,0x01,
0x01,0x7f,0xff,0x7f,0x10,0xfd,0x15,0x95,0xee,0x6b,
0x05,0x95,0x02,0x7e,0x00,0x7e,0xff,0x7e,0xfe,0x7f,
0xfe,0x00,0xfe,0x02,0x00,0x02,0x01,0x02,0x02,0x01,
0x02,0x00,0x02,0x7f,0x03,0x7f,0x03,0x00,0x03,0x01,
0x02,0x01,0xfc,0xf2,0xfe,0x7f,0xff,0x7e,0x00,0x7e,
0x02,0x7e,0x02,0x00,0x02,0x01,0x01,0x02,0x00,0x02,
0xfe,0x02,0xfe,0x00,0x07,0xf9,0x15,0x8d,0xff,0x7f,
0x01,0x7f,0x01,0x01,0x00,0x01,0xff,0x01,0xff,0x00,
0xff,0x7f,0xff,0x7e,0xfe,0x7b,0xfe,0x7d,0xfe,0x7e,
0xfe,0x7f,0xfd,0x00,0xfd,0x01,0xff,0x02,0x00,0x03,
0x01,0x02,0x06,0x04,0x02,0x02,0x01,0x02,0x00,0x02,
0xff,0x02,0xfe,0x01,0xfe,0x7f,0xff,0x7e,0x00,0x7e,
0x01,0x7d,0x02,0x7d,0x05,0x79,0x02,0x7e,0x03,0x7f,
0x01,0x00,0x01,0x01,0x00,0x01,0xf1,0xfe,0xfe,0x01,
0xff,0x02,0x00,0x03,0x01,0x02,0x02,0x02,0x00,0x86,
0x01,0x7e,0x08,0x75,0x02,0x7e,0x02,0x7f,0x05,0x80,
0x05,0x93,0xff,0x01,0x01,0x01,0x01,0x7f,0x00,0x7e,
0xff,0x7e,0xff,0x7f,0x06,0xf1,0x0b,0x99,0xfe,0x7e,
0xfe,0x7d,0xfe,0x7c,0xff,0x7b,0x00,0x7c,0x01,0x7b,
0x02,0x7c,0x02,0x7d,0x02,0x7e,0xfe,0x9e,0xfe,0x7c,
0xff,0x7d,0xff,0x7b,0x00,0x7c,0x01,0x7b,0x01,0x7d,
0x02,0x7c,0x05,0x85,0x03,0x99,0x02,0x7e,0x02,0x7d,
0x02,0x7c,0x01,0x7b,0x00,0x7c,0xff,0x7b,0xfe,0x7c,
0xfe,0x7d,0xfe,0x7e,0x02,0x9e,0x02,0x7c,0x01,0x7d,
0x01,0x7b,0x00,0x7c,0xff,0x7b,0xff,0x7d,0xfe,0x7c,
0x09,0x85,0x08,0x95,0x00,0x74,0xfb,0x89,0x0a,0x7a,
0x00,0x86,0xf6,0x7a,0x0d,0xf4,0x0d,0x92,0x00,0x6e,
0xf7,0x89,0x12,0x00,0x04,0xf7,0x06,0x81,0xff,0x7f,
0xff,0x01,0x01,0x01,0x01,0x7f,0x00,0x7e,0xff,0x7e,
0xff,0x7f,0x06,0x84,0x04,0x89,0x12,0x00,0x04,0xf7,
0x05,0x82,0xff,0x7f,0x01,0x7f,0x01,0x01,0xff,0x01,
0x05,0xfe,0x00,0xfd,0x0e,0x18,0x00,0xeb,0x09,0x95,
0xfd,0x7f,0xfe,0x7d,0xff,0x7b,0x00,0x7d,0x01,0x7b,
0x02,0x7d,0x03,0x7f,0x02,0x00,0x03,0x01,0x02,0x03,
0x01,0x05,0x00,0x03,0xff,0x05,0xfe,0x03,0xfd,0x01,
0xfe,0x00,0x0b,0xeb,0x06,0x91,0x02,0x01,0x03,0x03,
0x00,0x6b,0x09,0x80,0x04,0x90,0x00,0x01,0x01,0x02,
0x01,0x01,0x02,0x01,0x04,0x00,0x02,0x7f,0x01,0x7f,
0x01,0x7e,0x00,0x7e,0xff,0x7e,0xfe,0x7d,0xf6,0x76,
0x0e,0x00,0x03,0x80,0x05,0x95,0x0b,0x00,0xfa,0x78,
0x03,0x00,0x02,0x7f,0x01,0x7f,0x01,0x7d,0x00,0x7e,
0xff,0x7d,0xfe,0x7e,0xfd,0x7f,0xfd,0x00,0xfd,0x01,
0xff,0x01,0xff,0x02,0x11,0xfc,0x0d,0x95,0xf6,0x72,
0x0f,0x00,0xfb,0x8e,0x00,0x6b,0x07,0x80,0x0f,0x95,
0xf6,0x00,0xff,0x77,0x01,0x01,0x03,0x01,0x03,0x00,
0x03,0x7f,0x02,0x7e,0x01,0x7d,0x00,0x7e,0xff,0x7d,
0xfe,0x7e,0xfd,0x7f,0xfd,0x00,0xfd,0x01,0xff,0x01,
0xff,0x02,0x11,0xfc,0x10,0x92,0xff,0x02,0xfd,0x01,
0xfe,0x00,0xfd,0x7f,0xfe,0x7d,0xff,0x7b,0x00,0x7b,
0x01,0x7c,0x02,0x7e,0x03,0x7f,0x01,0x00,0x03,0x01,
0x02,0x02,0x01,0x03,0x00,0x01,0xff,0x03,0xfe,0x02,
0xfd,0x01,0xff,0x00,0xfd,0x7f,0xfe,0x7e,0xff,0x7d,
0x10,0xf9,0x11,0x95,0xf6,0x6b,0xfc,0x95,0x0e,0x00,
0x03,0xeb,0x08,0x95,0xfd,0x7f,0xff,0x7e,0x00,0x7e,
0x01,0x7e,0x02,0x7f,0x04,0x7f,0x03,0x7f,0x02,0x7e,
0x01,0x7e,0x00,0x7d,0xff,0x7e,0xff,0x7f,0xfd,0x7f,
0xfc,0x00,0xfd,0x01,0xff,0x01,0xff,0x02,0x00,0x03,
0x01,0x02,0x02,0x02,0x03,0x01,0x04,0x01,0x02,0x01,
0x01,0x02,0x00,0x02,0xff,0x02,0xfd,0x01,0xfc,0x00,
0x0c,0xeb,0x10,0x8e,0xff,0x7d,0xfe,0x7e,0xfd,0x7f,
0xff,0x00,0xfd,0x01,0xfe,0x02,0xff,0x03,0x00,0x01,
0x01,0x03,0x02,0x02,0x03,0x01,0x01,0x00,0x03,0x7f,
0x02,0x7e,0x01,0x7c,0x00,0x7b,0xff,0x7b,0xfe,0x7d,
0xfd,0x7f,0xfe,0x00,0xfd,0x01,0xff,0x02,0x10,0xfd,
0x05,0x8e,0xff,0x7f,0x01,0x7f,0x01,0x01,0xff,0x01,
0x00,0xf4,0xff,0x7f,0x01,0x7f,0x01,0x01,0xff,0x01,
0x05,0xfe,0x05,0x8e,0xff,0x7f,0x01,0x7f,0x01,0x01,
0xff,0x01,0x01,0xf3,0xff,0x7f,0xff,0x01,0x01,0x01,
0x01,0x7f,0x00,0x7e,0xff,0x7e,0xff,0x7f,0x06,0x84,
0x14,0x92,0xf0,0x77,0x10,0x77,0x04,0x80,0x04,0x8c,
0x12,0x00,0xee,0xfa,0x12,0x00,0x04,0xfa,0x04,0x92,
0x10,0x77,0xf0,0x77,0x14,0x80,0x03,0x90,0x00,0x01,
0x01,0x02,0x01,0x01,0x02,0x01,0x04,0x00,0x02,0x7f,
0x01,0x7f,0x01,0x7e,0x00,0x7e,0xff,0x7e,0xff,0x7f,
0xfc,0x7e,0x00,0x7d,0x00,0xfb,0xff,0x7f,0x01,0x7f,
0x01,0x01,0xff,0x01,0x09,0xfe,0x12,0x8d,0xff,0x02,
0xfe,0x01,0xfd,0x00,0xfe,0x7f,0xff,0x7f,0xff,0x7d,
0x00,0x7d,0x01,0x7e,0x02,0x7f,0x03,0x00,0x02,0x01,
0x01,0x02,0xfb,0x88,0xfe,0x7e,0xff,0x7d,0x00,0x7d,
0x01,0x7e,0x01,0x7f,0x07,0x8b,0xff,0x78,0x00,0x7e,
0x02,0x7f,0x02,0x00,0x02,0x02,0x01,0x03,0x00,0x02,
0xff,0x03,0xff,0x02,0xfe,0x02,0xfe,0x01,0xfd,0x01,
0xfd,0x00,0xfd,0x7f,0xfe,0x7f,0xfe,0x7e,0xff,0x7e,
0xff,0x7d,0x00,0x7d,0x01,0x7d,0x01,0x7e,0x02,0x7e,
0x02,0x7f,0x03,0x7f,0x03,0x00,0x03,0x01,0x02,0x01,
0x01,0x01,0xfe,0x8d,0xff,0x78,0x00,0x7e,0x01,0x7f,
0x08,0xfb,0x09,0x95,0xf8,0x6b,0x08,0x95,0x08,0x6b,
0xf3,0x87,0x0a,0x00,0x04,0xf9,0x04,0x95,0x00,0x6b,
0x00,0x95,0x09,0x00,0x03,0x7f,0x01,0x7f,0x01,0x7e,
0x00,0x7e,0xff,0x7e,0xff,0x7f,0xfd,0x7f,0xf7,0x80,
0x09,0x00,0x03,0x7f,0x01,0x7f,0x01,0x7e,0x00,0x7d,
0xff,0x7e,0xff,0x7f,0xfd,0x7f,0xf7,0x00,0x11,0x80,
0x12,0x90,0xff,0x02,0xfe,0x02,0xfe,0x01,0xfc,0x00,
0xfe,0x7f,0xfe,0x7e,0xff,0x7e,0xff,0x7d,0x00,0x7b,
0x01,0x7d,0x01,0x7e,0x02,0x7e,0x02,0x7f,0x04,0x00,
0x02,0x01,0x02,0x02,0x01,0x02,0x03,0xfb,0x04,0x95,
0x00,0x6b,0x00,0x95,0x07,0x00,0x03,0x7f,0x02,0x7e,
0x01,0x7e,0x01,0x7d,0x00,0x7b,0xff,0x7d,0xff,0x7e,
0xfe,0x7e,0xfd,0x7f,0xf9,0x00,0x11,0x80,0x04,0x95,
0x00,0x6b,0x00,0x95,0x0d,0x00,0xf3,0xf6,0x08,0x00,
0xf8,0xf5,0x0d,0x00,0x02,0x80,0x04,0x95,0x00,0x6b,
0x00,0x95,0x0d,0x00,0xf3,0xf6,0x08,0x00,0x06,0xf5,
0x12,0x90,0xff,0x02,0xfe,0x02,0xfe,0x01,0xfc,0x00,
0xfe,0x7f,0xfe,0x7e,0xff,0x7e,0xff,0x7d,0x00,0x7b,
0x01,0x7d,0x01,0x7e,0x02,0x7e,0x02,0x7f,0x04,0x00,
0x02,0x01,0x02,0x02,0x01,0x02,0x00,0x03,0xfb,0x80,
0x05,0x00,0x03,0xf8,0x04,0x95,0x00,0x6b,0x0e,0x95,
0x00,0x6b,0xf2,0x8b,0x0e,0x00,0x04,0xf5,0x04,0x95,
0x00,0x6b,0x04,0x80,0x0c,0x95,0x00,0x70,0xff,0x7d,
0xff,0x7f,0xfe,0x7f,0xfe,0x00,0xfe,0x01,0xff,0x01,
0xff,0x03,0x00,0x02,0x0e,0xf9,0x04,0x95,0x00,0x6b,
0x0e,0x95,0xf2,0x72,0x05,0x85,0x09,0x74,0x03,0x80,
0x04,0x95,0x00,0x6b,0x00,0x80,0x0c,0x00,0x01,0x80,
0x04,0x95,0x00,0x6b,0x00,0x95,0x08,0x6b,0x08,0x95,
0xf8,0x6b,0x08,0x95,0x00,0x6b,0x04,0x80,0x04,0x95,
0x00,0x6b,0x00,0x95,0x0e,0x6b,0x00,0x95,0x00,0x6b,
0x04,0x80,0x09,0x95,0xfe,0x7f,0xfe,0x7e,0xff,0x7e,
0xff,0x7d,0x00,0x7b,0x01,0x7d,0x01,0x7e,0x02,0x7e,
0x02,0x7f,0x04,0x00,0x02,0x01,0x02,0x02,0x01,0x02,
0x01,0x03,0x00,0x05,0xff,0x03,0xff,0x02,0xfe,0x02,
0xfe,0x01,0xfc,0x00,0x0d,0xeb,0x04,0x95,0x00,0x6b,
0x00,0x95,0x09,0x00,0x03,0x7f,0x01,0x7f,0x01,0x7e,
0x00,0x7d,0xff,0x7e,0xff,0x7f,0xfd,0x7f,0xf7,0x00,
0x11,0xf6,0x09,0x95,0xfe,0x7f,0xfe,0x7e,0xff,0x7e,
0xff,0x7d,0x00,0x7b,0x01,0x7d,0x01,0x7e,0x02,0x7e,
0x02,0x7f,0x04,0x00,0x02,0x01,0x02,0x02,0x01,0x02,
0x01,0x03,0x00,0x05,0xff,0x03,0xff,0x02,0xfe,0x02,
0xfe,0x01,0xfc,0x00,0x03,0xef,0x06,0x7a,0x04,0x82,
0x04,0x95,0x00,0x6b,0x00,0x95,0x09,0x00,0x03,0x7f,
0x01,0x7f,0x01,0x7e,0x00,0x7e,0xff,0x7e,0xff,0x7f,
0xfd,0x7f,0xf7,0x00,0x07,0x80,0x07,0x75,0x03,0x80,
0x11,0x92,0xfe,0x02,0xfd,0x01,0xfc,0x00,0xfd,0x7f,
0xfe,0x7e,0x00,0x7e,0x01,0x7e,0x01,0x7f,0x02,0x7f,
0x06,0x7e,0x02,0x7f,0x01,0x7f,0x01,0x7e,0x00,0x7d,
0xfe,0x7e,0xfd,0x7f,0xfc,0x00,0xfd,0x01,0xfe,0x02,
0x11,0xfd,0x08,0x95,0x00,0x6b,0xf9,0x95,0x0e,0x00,
0x01,0xeb,0x04,0x95,0x00,0x71,0x01,0x7d,0x02,0x7e,
0x03,0x7f,0x02,0x00,0x03,0x01,0x02,0x02,0x01,0x03,
0x00,0x0f,0x04,0xeb,0x01,0x95,0x08,0x6b,0x08,0x95,
0xf8,0x6b,0x09,0x80,0x02,0x95,0x05,0x6b,0x05,0x95,
0xfb,0x6b,0x05,0x95,0x05,0x6b,0x05,0x95,0xfb,0x6b,
0x07,0x80,0x03,0x95,0x0e,0x6b,0x00,0x95,0xf2,0x6b,
0x11,0x80,0x01,0x95,0x08,0x76,0x00,0x75,0x08,0x95,
0xf8,0x76,0x09,0xf5,0x11,0x95,0xf2,0x6b,0x00,0x95,
0x0e,0x00,0xf2,0xeb,0x0e,0x00,0x03,0x80,0x03,0x93,
0x00,0x6c,0x01,0x94,0x00,0x6c,0xff,0x94,0x05,0x00,
0xfb,0xec,0x05,0x00,0x02,0x81,0x00,0x95,0x0e,0x68,
0x00,0x83,0x06,0x93,0x00,0x6c,0x01,0x94,0x00,0x6c,
0xfb,0x94,0x05,0x00,0xfb,0xec,0x05,0x00,0x03,0x81,
0x03,0x87,0x08,0x05,0x08,0x7b,0xf0,0x80,0x08,0x04,
0x08,0x7c,0x03,0xf9,0x01,0x80,0x10,0x00,0x01,0x80,
0x06,0x95,0xff,0x7f,0xff,0x7e,0x00,0x7e,0x01,0x7f,
0x01,0x01,0xff,0x01,0x05,0xef,0x0f,0x8e,0x00,0x72,
0x00,0x8b,0xfe,0x02,0xfe,0x01,0xfd,0x00,0xfe,0x7f,
0xfe,0x7e,0xff,0x7d,0x00,0x7e,0x01,0x7d,0x02,0x7e,
0x02,0x7f,0x03,0x00,0x02,0x01,0x02,0x02,0x04,0xfd,
0x04,0x95,0x00,0x6b,0x00,0x8b,0x02,0x02,0x02,0x01,
0x03,0x00,0x02,0x7f,0x02,0x7e,0x01,0x7d,0x00,0x7e,
0xff,0x7d,0xfe,0x7e,0xfe,0x7f,0xfd,0x00,0xfe,0x01,
0xfe,0x02,0x0f,0xfd,0x0f,0x8b,0xfe,0x02,0xfe,0x01,
0xfd,0x00,0xfe,0x7f,0xfe,0x7e,0xff,0x7d,0x00,0x7e,
0x01,0x7d,0x02,0x7e,0x02,0x7f,0x03,0x00,0x02,0x01,
0x02,0x02,0x03,0xfd,0x0f,0x95,0x00,0x6b,0x00,0x8b,
0xfe,0x02,0xfe,0x01,0xfd,0x00,0xfe,0x7f,0xfe,0x7e,
0xff,0x7d,0x00,0x7e,0x01,0x7d,0x02,0x7e,0x02,0x7f,
0x03,0x00,0x02,0x01,0x02,0x02,0x04,0xfd,0x03,0x88,
0x0c,0x00,0x00,0x02,0xff,0x02,0xff,0x01,0xfe,0x01,
0xfd,0x00,0xfe,0x7f,0xfe,0x7e,0xff,0x7d,0x00,0x7e,
0x01,0x7d,0x02,0x7e,0x02,0x7f,0x03,0x00,0x02,0x01,
0x02,0x02,0x03,0xfd,0x0a,0x95,0xfe,0x00,0xfe,0x7f,
0xff,0x7d,0x00,0x6f,0xfd,0x8e,0x07,0x00,0x03,0xf2,
0x0f,0x8e,0x00,0x70,0xff,0x7d,0xff,0x7f,0xfe,0x7f,
0xfd,0x00,0xfe,0x01,0x09,0x91,0xfe,0x02,0xfe,0x01,
0xfd,0x00,0xfe,0x7f,0xfe,0x7e,0xff,0x7d,0x00,0x7e,
0x01,0x7d,0x02,0x7e,0x02,0x7f,0x03,0x00,0x02,0x01,
0x02,0x02,0x04,0xfd,0x04,0x95,0x00,0x6b,0x00,0x8a,
0x03,0x03,0x02,0x01,0x03,0x00,0x02,0x7f,0x01,0x7d,
0x00,0x76,0x04,0x80,0x03,0x95,0x01,0x7f,0x01,0x01,
0xff,0x01,0xff,0x7f,0x01,0xf9,0x00,0x72,0x04,0x80,
0x05,0x95,0x01,0x7f,0x01,0x01,0xff,0x01,0xff,0x7f,
0x01,0xf9,0x00,0x6f,0xff,0x7d,0xfe,0x7f,0xfe,0x00,
0x09,0x87,0x04,0x95,0x00,0x6b,0x0a,0x8e,0xf6,0x76,
0x04,0x84,0x07,0x78,0x02,0x80,0x04,0x95,0x00,0x6b,
0x04,0x80,0x04,0x8e,0x00,0x72,0x00,0x8a,0x03,0x03,
0x02,0x01,0x03,0x00,0x02,0x7f,0x01,0x7d,0x00,0x76,
0x00,0x8a,0x03,0x03,0x02,0x01,0x03,0x00,0x02,0x7f,
0x01,0x7d,0x00,0x76,0x04,0x80,0x04,0x8e,0x00,0x72,
0x00,0x8a,0x03,0x03,0x02,0x01,0x03,0x00,0x02,0x7f,
0x01,0x7d,0x00,0x76,0x04,0x80,0x08,0x8e,0xfe,0x7f,
0xfe,0x7e,0xff,0x7d,0x00,0x7e,0x01,0x7d,0x02,0x7e,
0x02,0x7f,0x03,0x00,0x02,0x01,0x02,0x02,0x01,0x03,
0x00,0x02,0xff,0x03,0xfe,0x02,0xfe,0x01,0xfd,0x00,
0x0b,0xf2,0x04,0x8e,0x00,0x6b,0x00,0x92,0x02,0x02,
0x02,0x01,0x03,0x00,0x02,0x7f,0x02,0x7e,0x01,0x7d,
0x00,0x7e,0xff,0x7d,0xfe,0x7e,0xfe,0x7f,0xfd,0x00,
0xfe,0x01,0xfe,0x02,0x0f,0xfd,0x0f,0x8e,0x00,0x6b,
0x00,0x92,0xfe,0x02,0xfe,0x01,0xfd,0x00,0xfe,0x7f,
0xfe,0x7e,0xff,0x7d,0x00,0x7e,0x01,0x7d,0x02,0x7e,
0x02,0x7f,0x03,0x00,0x02,0x01,0x02,0x02,0x04,0xfd,
0x04,0x8e,0x00,0x72,0x00,0x88,0x01,0x03,0x02,0x02,
0x02,0x01,0x03,0x00,0x01,0xf2,0x0e,0x8b,0xff,0x02,
0xfd,0x01,0xfd,0x00,0xfd,0x7f,0xff,0x7e,0x01,0x7e,
0x02,0x7f,0x05,0x7f,0x02,0x7f,0x01,0x7e,0x00,0x7f,
0xff,0x7e,0xfd,0x7f,0xfd,0x00,0xfd,0x01,0xff,0x02,
0x0e,0xfd,0x05,0x95,0x00,0x6f,0x01,0x7d,0x02,0x7f,
0x02,0x00,0xf8,0x8e,0x07,0x00,0x03,0xf2,0x04,0x8e,
0x00,0x76,0x01,0x7d,0x02,0x7f,0x03,0x00,0x02,0x01,
0x03,0x03,0x00,0x8a,0x00,0x72,0x04,0x80,0x02,0x8e,
0x06,0x72,0x06,0x8e,0xfa,0x72,0x08,0x80,0x03,0x8e,
0x04,0x72,0x04,0x8e,0xfc,0x72,0x04,0x8e,0x04,0x72,
0x04,0x8e,0xfc,0x72,0x07,0x80,0x03,0x8e,0x0b,0x72,
0x00,0x8e,0xf5,0x72,0x0e,0x80,0x02,0x8e,0x06,0x72,
0x06,0x8e,0xfa,0x72,0xfe,0x7c,0xfe,0x7e,0xfe,0x7f,
0xff,0x00,0x0f,0x87,0x0e,0x8e,0xf5,0x72,0x00,0x8e,
0x0b,0x00,0xf5,0xf2,0x0b,0x00,0x03,0x80,0x09,0x99,
0xfe,0x7f,0xff,0x7f,0xff,0x7e,0x00,0x7e,0x01,0x7e,
0x01,0x7f,0x01,0x7e,0x00,0x7e,0xfe,0x7e,0x01,0x8e,
0xff,0x7e,0x00,0x7e,0x01,0x7e,0x01,0x7f,0x01,0x7e,
0x00,0x7e,0xff,0x7e,0xfc,0x7e,0x04,0x7e,0x01,0x7e,
0x00,0x7e,0xff,0x7e,0xff,0x7f,0xff,0x7e,0x00,0x7e,
0x01,0x7e,0xff,0x8e,0x02,0x7e,0x00,0x7e,0xff,0x7e,
0xff,0x7f,0xff,0x7e,0x00,0x7e,0x01,0x7e,0x01,0x7f,
0x02,0x7f,0x05,0x87,0x04,0x95,0x00,0x77,0x00,0xfd,
0x00,0x77,0x04,0x80,0x05,0x99,0x02,0x7f,0x01,0x7f,
0x01,0x7e,0x00,0x7e,0xff,0x7e,0xff,0x7f,0xff,0x7e,
0x00,0x7e,0x02,0x7e,0xff,0x8e,0x01,0x7e,0x00,0x7e,
0xff,0x7e,0xff,0x7f,0xff,0x7e,0x00,0x7e,0x01,0x7e,
0x04,0x7e,0xfc,0x7e,0xff,0x7e,0x00,0x7e,0x01,0x7e,
0x01,0x7f,0x01,0x7e,0x00,0x7e,0xff,0x7e,0x01,0x8e,
0xfe,0x7e,0x00,0x7e,0x01,0x7e,0x01,0x7f,0x01,0x7e,
0x00,0x7e,0xff,0x7e,0xff,0x7f,0xfe,0x7f,0x09,0x87,
0x03,0x86,0x00,0x02,0x01,0x03,0x02,0x01,0x02,0x00,
0x02,0x7f,0x04,0x7d,0x02,0x7f,0x02,0x00,0x02,0x01,
0x01,0x02,0xee,0xfe,0x01,0x02,0x02,0x01,0x02,0x00,
0x02,0x7f,0x04,0x7d,0x02,0x7f,0x02,0x00,0x02,0x01,
0x01,0x03,0x00,0x02,0x03,0xf4,0x10,0x80,0x03,0x80,
0x07,0x15,0x08,0x6b,0xfe,0x85,0xf5,0x00,0x10,0xfb,
0x0d,0x95,0xf6,0x00,0x00,0x6b,0x0a,0x00,0x02,0x02,
0x00,0x08,0xfe,0x02,0xf6,0x00,0x0e,0xf4,0x03,0x80,
0x00,0x15,0x0a,0x00,0x02,0x7e,0x00,0x7e,0x00,0x7d,
0x00,0x7e,0xfe,0x7f,0xf6,0x00,0x0a,0x80,0x02,0x7e,
0x01,0x7e,0x00,0x7d,0xff,0x7d,0xfe,0x7f,0xf6,0x00,
0x10,0x80,0x03,0x80,0x00,0x15,0x0c,0x00,0xff,0x7e,
0x03,0xed,0x03,0xfd,0x00,0x03,0x02,0x00,0x00,0x12,
0x02,0x03,0x0a,0x00,0x00,0x6b,0x02,0x00,0x00,0x7d,
0xfe,0x83,0xf4,0x00,0x11,0x80,0x0f,0x80,0xf4,0x00,
0x00,0x15,0x0c,0x00,0xff,0xf6,0xf5,0x00,0x0f,0xf5,
0x04,0x95,0x07,0x76,0x00,0x0a,0x07,0x80,0xf9,0x76,
0x00,0x75,0xf8,0x80,0x07,0x0c,0x09,0xf4,0xf9,0x0c,
0x09,0xf4,0x03,0x92,0x02,0x03,0x07,0x00,0x03,0x7d,
0x00,0x7b,0xfc,0x7e,0x04,0x7d,0x00,0x7a,0xfd,0x7e,
0xf9,0x00,0xfe,0x02,0x06,0x89,0x02,0x00,0x06,0xf5,
0x03,0x95,0x00,0x6b,0x0c,0x15,0x00,0x6b,0x02,0x80,
0x03,0x95,0x00,0x6b,0x0c,0x15,0x00,0x6b,0xf8,0x96,
0x03,0x00,0x07,0xea,0x03,0x80,0x00,0x15,0x0c,0x80,
0xf7,0x76,0xfd,0x00,0x03,0x80,0x0a,0x75,0x03,0x80,
0x03,0x80,0x07,0x13,0x02,0x02,0x03,0x00,0x00,0x6b,
0x02,0x80,0x03,0x80,0x00,0x15,0x09,0x6b,0x09,0x15,
0x00,0x6b,0x03,0x80,0x03,0x80,0x00,0x15,0x00,0xf6,
0x0d,0x00,0x00,0x8a,0x00,0x6b,0x03,0x80,0x07,0x80,
0xfd,0x00,0xff,0x03,0x00,0x04,0x00,0x07,0x00,0x04,
0x01,0x02,0x03,0x01,0x06,0x00,0x03,0x7f,0x01,0x7e,
0x01,0x7c,0x00,0x79,0xff,0x7c,0xff,0x7d,0xfd,0x00,
0xfa,0x00,0x0e,0x80,0x03,0x80,0x00,0x15,0x0c,0x00,
0x00,0x6b,0x02,0x80,0x03,0x80,0x00,0x15,0x0a,0x00,
0x02,0x7f,0x01,0x7d,0x00,0x7b,0xff,0x7e,0xfe,0x7f,
0xf6,0x00,0x10,0xf7,0x11,0x8f,0xff,0x03,0xff,0x02,
0xfe,0x01,0xfa,0x00,0xfd,0x7f,0xff,0x7e,0x00,0x7c,
0x00,0x79,0x00,0x7b,0x01,0x7e,0x03,0x00,0x06,0x00,
0x02,0x00,0x01,0x03,0x01,0x02,0x03,0xfb,0x03,0x95,
0x0c,0x00,0xfa,0x80,0x00,0x6b,0x09,0x80,0x03,0x95,
0x00,0x77,0x06,0x7a,0x06,0x06,0x00,0x09,0xfa,0xf1,
0xfa,0x7a,0x0e,0x80,0x03,0x87,0x00,0x0b,0x02,0x02,
0x03,0x00,0x02,0x7e,0x01,0x02,0x04,0x00,0x02,0x7e,
0x00,0x75,0xfe,0x7e,0xfc,0x00,0xff,0x01,0xfe,0x7f,
0xfd,0x00,0xfe,0x02,0x07,0x8e,0x00,0x6b,0x09,0x80,
0x03,0x80,0x0e,0x15,0xf2,0x80,0x0e,0x6b,0x03,0x80,
0x03,0x95,0x00,0x6b,0x0e,0x00,0x00,0x7d,0xfe,0x98,
0x00,0x6b,0x05,0x80,0x03,0x95,0x00,0x75,0x02,0x7d,
0x0a,0x00,0x00,0x8e,0x00,0x6b,0x02,0x80,0x03,0x95,
0x00,0x6b,0x10,0x00,0x00,0x15,0xf8,0x80,0x00,0x6b,
0x0a,0x80,0x03,0x95,0x00,0x6b,0x10,0x00,0x00,0x15,
0xf8,0x80,0x00,0x6b,0x0a,0x00,0x00,0x7d,0x02,0x83,
0x10,0x80,0x03,0x95,0x00,0x6b,0x09,0x00,0x03,0x02,
0x00,0x08,0xfd,0x02,0xf7,0x00,0x0e,0x89,0x00,0x6b,
0x03,0x80,0x03,0x95,0x00,0x6b,0x09,0x00,0x03,0x02,
0x00,0x08,0xfd,0x02,0xf7,0x00,0x0e,0xf4,0x03,0x92,
0x02,0x03,0x07,0x00,0x03,0x7d,0x00,0x70,0xfd,0x7e,
0xf9,0x00,0xfe,0x02,0x03,0x89,0x09,0x00,0x02,0xf5,
0x03,0x80,0x00,0x15,0x00,0xf5,0x07,0x00,0x00,0x08,
0x02,0x03,0x06,0x00,0x02,0x7d,0x00,0x70,0xfe,0x7e,
0xfa,0x00,0xfe,0x02,0x00,0x08,0x0c,0xf6,0x0f,0x80,
0x00,0x15,0xf6,0x00,0xfe,0x7d,0x00,0x79,0x02,0x7e,
0x0a,0x00,0xf4,0xf7,0x07,0x09,0x07,0xf7,0x03,0x8c,
0x01,0x02,0x01,0x01,0x05,0x00,0x02,0x7f,0x01,0x7e,
0x00,0x74,0x00,0x86,0xff,0x01,0xfe,0x01,0xfb,0x00,
0xff,0x7f,0xff,0x7f,0x00,0x7c,0x01,0x7e,0x01,0x00,
0x05,0x00,0x02,0x00,0x01,0x02,0x03,0xfe,0x04,0x8e,
0x02,0x01,0x04,0x00,0x02,0x7f,0x01,0x7e,0x00,0x77,
0xff,0x7e,0xfe,0x7f,0xfc,0x00,0xfe,0x01,0xff,0x02,
0x00,0x09,0x01,0x02,0x02,0x02,0x03,0x01,0x02,0x01,
0x01,0x01,0x01,0x02,0x02,0xeb,0x03,0x80,0x00,0x15,
0x03,0x00,0x02,0x7e,0x00,0x7b,0xfe,0x7e,0xfd,0x00,
0x03,0x80,0x04,0x00,0x03,0x7e,0x00,0x78,0xfd,0x7e,
0xf9,0x00,0x0c,0x80,0x03,0x8c,0x02,0x02,0x02,0x01,
0x03,0x00,0x02,0x7f,0x01,0x7d,0xfe,0x7e,0xf9,0x7d,
0xff,0x7e,0x00,0x7d,0x03,0x7f,0x02,0x00,0x03,0x01,
0x02,0x01,0x02,0xfe,0x0d,0x8c,0xff,0x02,0xfe,0x01,
0xfc,0x00,0xfe,0x7f,0xff,0x7e,0x00,0x77,0x01,0x7e,
0x02,0x7f,0x04,0x00,0x02,0x01,0x01,0x02,0x00,0x0f,
0xff,0x02,0xfe,0x01,0xf9,0x00,0x0c,0xeb,0x03,0x88,
0x0a,0x00,0x00,0x02,0x00,0x03,0xfe,0x02,0xfa,0x00,
0xff,0x7e,0xff,0x7d,0x00,0x7b,0x01,0x7c,0x01,0x7f,
0x06,0x00,0x02,0x02,0x03,0xfe,0x03,0x8f,0x06,0x77,
0x06,0x09,0xfa,0x80,0x00,0x71,0xff,0x87,0xfb,0x79,
0x07,0x87,0x05,0x79,0x02,0x80,0x03,0x8d,0x02,0x02,
0x06,0x00,0x02,0x7e,0x00,0x7d,0xfc,0x7d,0x04,0x7e,
0x00,0x7d,0xfe,0x7e,0xfa,0x00,0xfe,0x02,0x04,0x85,
0x02,0x00,0x06,0xf9,0x03,0x8f,0x00,0x73,0x01,0x7e,
0x07,0x00,0x02,0x02,0x00,0x0d,0x00,0xf3,0x01,0x7e,
0x03,0x80,0x03,0x8f,0x00,0x73,0x01,0x7e,0x07,0x00,
0x02,0x02,0x00,0x0d,0x00,0xf3,0x01,0x7e,0xf8,0x90,
0x03,0x00,0x08,0xf0,0x03,0x80,0x00,0x15,0x00,0xf3,
0x02,0x00,0x06,0x07,0xfa,0xf9,0x07,0x78,0x03,0x80,
0x03,0x80,0x04,0x0c,0x02,0x03,0x04,0x00,0x00,0x71,
0x02,0x80,0x03,0x80,0x00,0x0f,0x06,0x77,0x06,0x09,
0x00,0x71,0x02,0x80,0x03,0x80,0x00,0x0f,0x0a,0xf1,
0x00,0x0f,0xf6,0xf8,0x0a,0x00,0x02,0xf9,0x05,0x80,
0xff,0x01,0xff,0x04,0x00,0x05,0x01,0x03,0x01,0x02,
0x06,0x00,0x02,0x7e,0x00,0x7d,0x00,0x7b,0x00,0x7c,
0xfe,0x7f,0xfa,0x00,0x0b,0x80,0x03,0x80,0x00,0x0f,
0x00,0xfb,0x01,0x03,0x01,0x02,0x05,0x00,0x02,0x7e,
0x01,0x7d,0x00,0x76,0x03,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,0x10,0x80,
0x10,0x80,0x0a,0x8f,0x02,0x7f,0x01,0x7e,0x00,0x76,
0xff,0x7f,0xfe,0x7f,0xfb,0x00,0xff,0x01,0xff,0x01,
0x00,0x0a,0x01,0x02,0x01,0x01,0x05,0x00,0xf9,0x80,
0x00,0x6b,0x0c,0x86,0x0d,0x8a,0xff,0x03,0xfe,0x02,
0xfb,0x00,0xff,0x7e,0xff,0x7d,0x00,0x7b,0x01,0x7c,
0x01,0x7f,0x05,0x00,0x02,0x01,0x01,0x03,0x03,0xfc,
0x03,0x80,0x00,0x0f,0x00,0xfb,0x01,0x03,0x01,0x02,
0x04,0x00,0x01,0x7e,0x01,0x7d,0x00,0x76,0x00,0x8a,
0x01,0x03,0x02,0x02,0x03,0x00,0x02,0x7e,0x01,0x7d,
0x00,0x76,0x03,0x80,0x03,0x8f,0x00,0x74,0x01,0x7e,
0x02,0x7f,0x04,0x00,0x02,0x01,0x01,0x01,0x00,0x8d,
0x00,0x6e,0xff,0x7e,0xfe,0x7f,0xfb,0x00,0xfe,0x01,
0x0c,0x85,0x03,0x8d,0x01,0x02,0x03,0x00,0x02,0x7e,
0x01,0x02,0x03,0x00,0x02,0x7e,0x00,0x74,0xfe,0x7f,
0xfd,0x00,0xff,0x01,0xfe,0x7f,0xfd,0x00,0xff,0x01,
0x00,0x0c,0x06,0x82,0x00,0x6b,0x08,0x86,0x03,0x80,
0x0a,0x0f,0xf6,0x80,0x0a,0x71,0x03,0x80,0x03,0x8f,
0x00,0x73,0x01,0x7e,0x07,0x00,0x02,0x02,0x00,0x0d,
0x00,0xf3,0x01,0x7e,0x00,0x7e,0x03,0x82,0x03,0x8f,
0x00,0x79,0x02,0x7e,0x08,0x00,0x00,0x89,0x00,0x71,
0x02,0x80,0x03,0x8f,0x00,0x73,0x01,0x7e,0x03,0x00,
0x02,0x02,0x00,0x0d,0x00,0xf3,0x01,0x7e,0x03,0x00,
0x02,0x02,0x00,0x0d,0x00,0xf3,0x01,0x7e,0x03,0x80,
0x03,0x8f,0x00,0x73,0x01,0x7e,0x03,0x00,0x02,0x02,
0x00,0x0d,0x00,0xf3,0x01,0x7e,0x03,0x00,0x02,0x02,
0x00,0x0d,0x00,0xf3,0x01,0x7e,0x00,0x7e,0x03,0x82,
0x03,0x8d,0x00,0x02,0x02,0x00,0x00,0x71,0x08,0x00,
0x02,0x02,0x00,0x06,0xfe,0x02,0xf8,0x00,0x0c,0xf6,
0x03,0x8f,0x00,0x71,0x07,0x00,0x02,0x02,0x00,0x06,
0xfe,0x02,0xf9,0x00,0x0c,0x85,0x00,0x71,0x02,0x80,
0x03,0x8f,0x00,0x71,0x07,0x00,0x03,0x02,0x00,0x06,
0xfd,0x02,0xf9,0x00,0x0c,0xf6,0x03,0x8d,0x02,0x02,
0x06,0x00,0x02,0x7e,0x00,0x75,0xfe,0x7e,0xfa,0x00,
0xfe,0x02,0x04,0x85,0x06,0x00,0x02,0xf9,0x03,0x80,
0x00,0x0f,0x00,0xf8,0x04,0x00,0x00,0x06,0x02,0x02,
0x04,0x00,0x02,0x7e,0x00,0x75,0xfe,0x7e,0xfc,0x00,
0xfe,0x02,0x00,0x05,0x0a,0xf9,0x0d,0x80,0x00,0x0f,
0xf7,0x00,0xff,0x7e,0x00,0x7b,0x01,0x7e,0x09,0x00,
0xf6,0xfa,0x04,0x06,0x08,0xfa
};
//-------------------------------------------------------------------------
gsv_text::gsv_text() :
m_x(0.0),
m_y(0.0),
m_start_x(0.0),
m_width(10.0),
m_height(0.0),
m_space(0.0),
m_line_space(0.0),
m_text(m_chr),
m_text_buf(),
m_cur_chr(m_chr),
m_font(gsv_default_font),
m_loaded_font(),
m_status(initial),
m_big_endian(false),
m_flip(false)
{
m_chr[0] = m_chr[1] = 0;
int t = 1;
if(*(char*)&t == 0) m_big_endian = true;
}
//-------------------------------------------------------------------------
void gsv_text::font(const void* font)
{
m_font = font;
if(m_font == 0) m_font = &m_loaded_font[0];
}
//-------------------------------------------------------------------------
void gsv_text::size(double height, double width)
{
m_height = height;
m_width = width;
}
//-------------------------------------------------------------------------
void gsv_text::space(double space)
{
m_space = space;
}
//-------------------------------------------------------------------------
void gsv_text::line_space(double line_space)
{
m_line_space = line_space;
}
//-------------------------------------------------------------------------
void gsv_text::start_point(double x, double y)
{
m_x = m_start_x = x;
m_y = y;
//if(m_flip) m_y += m_height;
}
//-------------------------------------------------------------------------
void gsv_text::load_font(const char* file)
{
m_loaded_font.resize(0);
FILE* fd = std::fopen(file, "rb");
if(fd)
{
unsigned len;
std::fseek(fd, 0l, SEEK_END);
len = std::ftell(fd);
std::fseek(fd, 0l, SEEK_SET);
if(len > 0)
{
m_loaded_font.resize(len);
if (std::fread(&m_loaded_font[0], 1, len, fd) == len)
m_font = &m_loaded_font[0];
else
m_font = 0;
}
std::fclose(fd);
}
}
//-------------------------------------------------------------------------
void gsv_text::text(const char* text)
{
if(text == 0)
{
m_chr[0] = 0;
m_text = m_chr;
return;
}
unsigned new_size = std::strlen(text) + 1;
if(new_size > m_text_buf.size())
{
m_text_buf.resize(new_size);
}
std::memcpy(&m_text_buf[0], text, new_size);
m_text = &m_text_buf[0];
}
//-------------------------------------------------------------------------
void gsv_text::rewind(unsigned)
{
m_status = initial;
if(m_font == 0) return;
m_indices = (int8u*)m_font;
double base_height = value(m_indices + 4);
m_indices += value(m_indices);
m_glyphs = (int8*)(m_indices + 257*2);
m_h = m_height / base_height;
m_w = (m_width == 0.0) ? m_h : m_width / base_height;
if(m_flip) m_h = -m_h;
m_cur_chr = m_text;
}
//-------------------------------------------------------------------------
unsigned gsv_text::vertex(double* x, double* y)
{
unsigned idx;
int8 yc, yf;
int dx, dy;
bool quit = false;
while(!quit)
{
switch(m_status)
{
case initial:
if(m_font == 0)
{
quit = true;
break;
}
m_status = next_char;
case next_char:
if(*m_cur_chr == 0)
{
quit = true;
break;
}
idx = (*m_cur_chr++) & 0xFF;
if(idx == '\n')
{
m_x = m_start_x;
m_y -= m_flip ? -m_height - m_line_space : m_height + m_line_space;
break;
}
idx <<= 1;
m_bglyph = m_glyphs + value(m_indices + idx);
m_eglyph = m_glyphs + value(m_indices + idx + 2);
m_status = start_glyph;
case start_glyph:
*x = m_x;
*y = m_y;
m_status = glyph;
return path_cmd_move_to;
case glyph:
if(m_bglyph >= m_eglyph)
{
m_status = next_char;
m_x += m_space;
break;
}
dx = int(*m_bglyph++);
yf = (yc = *m_bglyph++) & 0x80;
yc <<= 1;
yc >>= 1;
dy = int(yc);
m_x += double(dx) * m_w;
m_y += double(dy) * m_h;
*x = m_x;
*y = m_y;
return yf ? path_cmd_move_to : path_cmd_line_to;
}
}
return path_cmd_stop;
}
//-------------------------------------------------------------------------
double gsv_text::text_width()
{
double x1, y1, x2, y2;
bounding_rect_single(*this, 0, &x1, &y1, &x2, &y2);
return x2 - x1;
}
}
| mit |
SkyIsTheLimit/vacation-planner | src/pages/origin-picker/origin-picker.module.ts | 347 | import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { OriginPickerPage } from './origin-picker';
@NgModule({
declarations: [
OriginPickerPage,
],
imports: [
IonicPageModule.forChild(OriginPickerPage),
],
exports: [
OriginPickerPage
]
})
export class OriginPickerPageModule {}
| mit |
irmen/Pyro5 | examples/resourcetracking/client.py | 662 | import random
from Pyro5.api import Proxy
uri = input("Enter the URI of the server object: ")
with Proxy(uri) as proxy:
print("currently allocated resources:", proxy.list())
name1 = hex(random.randint(0, 999999))[-4:]
name2 = hex(random.randint(0, 999999))[-4:]
print("allocating resource...", name1)
proxy.allocate(name1)
print("allocating resource...", name2)
proxy.allocate(name2)
input("\nhit Enter now to continue normally or ^C/break to abort the connection forcefully:")
print("free resources normally...")
proxy.free(name1)
proxy.free(name2)
print("allocated resources:", proxy.list())
print("done.")
| mit |
clooca/clooca | lib/client/components/editor/header.js | 5473 | 'use strict';
var React = require('react');
var Link = require('react-router').Link;
var Menu = require('../menu');
var MenuItem = require('../menu/item');
var Resources = require('./resources');
var AddTabModal = require('../modal/addTab');
var AddObjectModal = require('../modal/addObject');
var AddContainmentModal = require('../modal/addContainment');
var ImportJSONModal = require('../modal/importJSON');
var ExportJSONModal = require('../modal/exportJSON');
var TabAction = require('../../actions/tab');
var ModalAction = require('../../actions/modal');
var querystring = require('querystring');
var repository = require('../../../common/core/repository');
var Header = React.createClass({
displayName: 'Header',
getInitialState: function getInitialState() {
return {
isOpenAddTabModal: false,
isOpenImportJSONModal: false,
isOpenExportJSONModal: false,
isOpenAddObjectModal: this.props.editorSettings.isOpenAddObjectModal,
isOpenAddContainmentModal: this.props.editorSettings.isOpenAddContainmentModal
};
},
componentWillMount: function componentWillMount() {
var setState = this.setState.bind(this);
},
componentDidMount: function componentDidMount() {},
componentDidUpdate: function componentDidUpdate() {},
componentWillUnmount: function componentWillUnmount() {},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.setState({
isOpenAddContainmentModal: nextProps.editorSettings.isOpenAddContainmentModal
});
},
addTab: function addTab(newTab) {
TabAction.add(newTab);
},
onAddTabMenuSelected: function onAddTabMenuSelected() {
this.setState({
isOpenAddTabModal: true
});
},
onAddObjectMenuSelected: function onAddObjectMenuSelected() {
clooca.getPlugin('clooca').request('modal', {
isOpenAddObjectModal: true
}).then(function () {});
},
onSaveMenuSelected: function onSaveMenuSelected() {
var modelJson = clooca.getModelInterface().getModelJSON();
repository.save(clooca, modelJson.uri, modelJson.data).then(function () {});
},
onImportMenuSelected: function onImportMenuSelected() {
this.setState({
isOpenImportJSONModal: true
});
},
onExportMenuSelected: function onExportMenuSelected() {
this.setState({
isOpenExportJSONModal: true
});
},
onCloseImportJSONModal: function onCloseImportJSONModal() {
this.setState({
isOpenImportJSONModal: false
});
},
onCloseAddTabModal: function onCloseAddTabModal() {
this.setState({
isOpenAddTabModal: false
});
},
onCloseAddObjectModal: function onCloseAddObjectModal() {
ModalAction.close();
},
onCloseAddContainmentModal: function onCloseAddContainmentModal() {
ModalAction.close();
},
onCloseExportJSONModal: function onCloseExportJSONModal() {
this.setState({
isOpenExportJSONModal: false
});
},
onDatasourceSelected: function onDatasourceSelected(uri) {
clooca.getModelInterface().setCurrentModel(uri);
},
render: function render() {
return React.createElement(
'div',
{ className: 'core-header', style: { height: "32px", borderBottom: "solid 1px #333" } },
React.createElement(
'div',
{ style: { float: "left", "marginLeft": "12px" } },
React.createElement(
'div',
null,
React.createElement(
Link,
{ to: '/projects' },
'\u2190Return'
)
)
),
React.createElement(
'div',
{ style: { float: "left", "marginLeft": "30px" } },
React.createElement(
Menu,
null,
React.createElement(
MenuItem,
{ onSelect: this.onAddTabMenuSelected },
'Add New Tab'
),
React.createElement(
MenuItem,
{ onSelect: this.onSaveMenuSelected },
'Save Model'
),
React.createElement(
MenuItem,
{ onSelect: this.onImportMenuSelected },
'Import Model'
),
React.createElement(
MenuItem,
{ onSelect: this.onExportMenuSelected },
'Export Model'
),
React.createElement(
MenuItem,
null,
React.createElement(Resources, { onSelect: this.onDatasourceSelected })
)
)
),
React.createElement('div', { style: { overflow: 'hidden', clear: 'both' } }),
React.createElement(AddTabModal, { isOpen: this.state.isOpenAddTabModal, onOk: this.addTab, onClose: this.onCloseAddTabModal, pluginNames: this.props.pluginNames }),
React.createElement(AddObjectModal, { isOpen: this.props.editorSettings.isOpenAddObjectModal, onClose: this.onCloseAddObjectModal, uri: this.props.editorSettings.uri }),
React.createElement(AddContainmentModal, { isOpen: this.props.editorSettings.isOpenAddContainmentModal, onClose: this.onCloseAddContainmentModal, model: this.props.editorSettings.target, resourceSet: this.props.editorSettings.resourceSet }),
React.createElement(ImportJSONModal, { isOpen: this.state.isOpenImportJSONModal, onClose: this.onCloseImportJSONModal }),
React.createElement(ExportJSONModal, { isOpen: this.state.isOpenExportJSONModal, onClose: this.onCloseExportJSONModal })
);
}
});
module.exports = Header;
//# sourceMappingURL=header.js.map
| mit |
smialy/ssrp | demo/app.py | 2697 | import sys
import traceback
import ssrp
import model
from flask import Flask, render_template, request, redirect, jsonify, session
from flask.ext.login import LoginManager, login_required, login_user, logout_user, current_user
app = Flask(__name__)
app.debug = True
app.secret_key = 'test :P'
login_manager = LoginManager(app)
login_manager.session_protection = "strong"
@login_manager.user_loader
def load_user(userid):
user = model.find_user(userid)
if user:
return user
@login_manager.unauthorized_handler
def unauthorized():
# do stuff
return redirect('/login')
@app.route("/")
@login_required
def hello():
return render_template('index.html')
@app.route('/login')
def login():
return render_template('login.html')
@app.route('/authenticate', methods=['POST'])
def authenticate():
user = model.get_user(request.form['login'])
if user:
_M = request.form['m']
srp = session.pop('srp', None)
if srp:
K, M = srp
if _M == str(M):
user.authenticated = True
login_user(user)
return jsonify(error=False);
return jsonify(error=True, message="Incorect session");
@app.route("/handshake", methods=['GET','POST'])
def handshake():
try:
user = model.get_user(request.form['login'])
if user:
A = request.form['a']
svr = ssrp.Server(user.login, user.salt, int(user.v), int(A));
salt, B = svr.challenge()
session['srp'] = (svr.K, svr.M)
if salt is None or B is None:
return jsonify(error=True, message="Authentication failed");
return jsonify(error=False, salt=salt, b=str(B));
return jsonify(error=True, message="Not found user");
except:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
print(exceptionType, exceptionValue)
traceback.print_tb(exceptionTraceback)
return jsonify(error=True, message="Internal error");
@app.route("/registration", methods=['POST', 'GET'])
def registration():
if request.method == 'POST':
login = request.form['login']
salt = request.form['salt']
v = request.form['v']
if model.has_user(login):
return jsonify(dict(error=True, message="User exits"))
model.add_user(login, salt, v)
return jsonify(dict(error=False))
else:
return render_template('registration.html')
@app.route("/logout")
@login_required
def logout():
current_user.authenticated = False
logout_user()
return redirect('/')
if __name__ == "__main__":
app.run(port=8000)
| mit |
espace/redmine_estimate_change_history | app/controllers/estimates_controller.rb | 330 | class EstimatesController < ApplicationController
include EstimatesHelper
def index
@issue = Issue.find(params[:issue_id])
@estimates = EstimateUpdate.find(:all,
:conditions=>{:issue_id=>params[:issue_id]},
:order=>:created_at)
end
end
| mit |
alimasri/movies_organizer | movies_organizer/app.py | 2876 | import argparse
import logging
import os
import sys
from movies_organizer import utils, __version__
__author__ = "Ali Masri"
__copyright__ = "Ali Masri"
__license__ = "MIT"
_logger = logging.getLogger(__name__)
def parse_args(args):
parser = argparse.ArgumentParser(
description="Movie library organizer")
parser.add_argument(
'--version',
action='version',
version='movies_organizer {ver}'.format(ver=__version__))
parser.add_argument(
'-v',
'--verbose',
dest="loglevel",
help="set loglevel to INFO",
action='store_const',
const=logging.INFO)
parser.add_argument(
'-vv',
'--very-verbose',
dest="loglevel",
help="set loglevel to DEBUG",
action='store_const',
const=logging.DEBUG)
parser.add_argument(
'--src',
help="the source directory",
type=str,
metavar="TEXT")
parser.add_argument(
'--dst',
help="the destination folder",
type=str,
metavar="TEXT")
parser.add_argument(
'--auto',
const=True,
default=False,
nargs='?',
help="automatically select a movie from the search results",
)
return parser.parse_args(args)
def setup_logging(loglevel):
logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
logging.basicConfig(level=loglevel, stream=sys.stdout,
format=logformat, datefmt="%Y-%m-%d %H:%M:%S")
def main(args):
num_stars = 40
args = parse_args(args)
setup_logging(args.loglevel)
_logger.debug("Program started...")
src = args.src if args.src is not None else "."
auto_select = args.auto
dst = args.dst if args.dst is not None else src
movies = os.listdir(src)
if movies is None:
print('No movies found in: ' + src)
exit(0)
missing_movies = []
for file_name in movies:
movie_title = os.path.splitext(file_name)[0]
try:
print(num_stars * "*")
print("Searching for " + str(movie_title.encode("utf8")) + "...")
movie = utils.search(movie_title, auto_select)
if movie is None:
print('Movie not found...')
missing_movies.append(movie_title)
continue
utils.move_files(os.path.join(src, file_name), dst, movie)
except Exception as error:
print('Error: ' + str(error))
continue
if len(missing_movies) != 0:
print(num_stars * "*")
print('Sorry we could not find the following movies:')
for movie_title in missing_movies:
print(str(movie_title.encode("utf8")))
print(num_stars * "*")
_logger.info("Process finished")
def run():
main(sys.argv[1:])
if __name__ == '__main__':
run()
| mit |
openbibleinfo/Bible-Passage-Reference-Parser | test/js/ar.spec.js | 100598 | (function() {
var bcv_parser;
bcv_parser = require("../../js/ar_bcv_parser.js").bcv_parser;
describe("Parsing", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.options.osis_compaction_strategy = "b";
return p.options.sequence_combination_strategy = "combine";
});
it("should round-trip OSIS references", function() {
var bc, bcv, bcv_range, book, books, i, len, results;
p.set_options({
osis_compaction_strategy: "bc"
});
books = ["Gen", "Exod", "Lev", "Num", "Deut", "Josh", "Judg", "Ruth", "1Sam", "2Sam", "1Kgs", "2Kgs", "1Chr", "2Chr", "Ezra", "Neh", "Esth", "Job", "Ps", "Prov", "Eccl", "Song", "Isa", "Jer", "Lam", "Ezek", "Dan", "Hos", "Joel", "Amos", "Obad", "Jonah", "Mic", "Nah", "Hab", "Zeph", "Hag", "Zech", "Mal", "Matt", "Mark", "Luke", "John", "Acts", "Rom", "1Cor", "2Cor", "Gal", "Eph", "Phil", "Col", "1Thess", "2Thess", "1Tim", "2Tim", "Titus", "Phlm", "Heb", "Jas", "1Pet", "2Pet", "1John", "2John", "3John", "Jude", "Rev"];
results = [];
for (i = 0, len = books.length; i < len; i++) {
book = books[i];
bc = book + ".1";
bcv = bc + ".1";
bcv_range = bcv + "-" + bc + ".2";
expect(p.parse(bc).osis()).toEqual(bc);
expect(p.parse(bcv).osis()).toEqual(bcv);
results.push(expect(p.parse(bcv_range).osis()).toEqual(bcv_range));
}
return results;
});
it("should round-trip OSIS Apocrypha references", function() {
var bc, bcv, bcv_range, book, books, i, j, len, len1, results;
p.set_options({
osis_compaction_strategy: "bc",
ps151_strategy: "b"
});
p.include_apocrypha(true);
books = ["Tob", "Jdt", "GkEsth", "Wis", "Sir", "Bar", "PrAzar", "Sus", "Bel", "SgThree", "EpJer", "1Macc", "2Macc", "3Macc", "4Macc", "1Esd", "2Esd", "PrMan", "Ps151"];
for (i = 0, len = books.length; i < len; i++) {
book = books[i];
bc = book + ".1";
bcv = bc + ".1";
bcv_range = bcv + "-" + bc + ".2";
expect(p.parse(bc).osis()).toEqual(bc);
expect(p.parse(bcv).osis()).toEqual(bcv);
expect(p.parse(bcv_range).osis()).toEqual(bcv_range);
}
p.set_options({
ps151_strategy: "bc"
});
expect(p.parse("Ps151.1").osis()).toEqual("Ps.151");
expect(p.parse("Ps151.1.1").osis()).toEqual("Ps.151.1");
expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual("Ps.151.1-Ps.151.2");
p.include_apocrypha(false);
results = [];
for (j = 0, len1 = books.length; j < len1; j++) {
book = books[j];
bc = book + ".1";
results.push(expect(p.parse(bc).osis()).toEqual(""));
}
return results;
});
return it("should handle a preceding character", function() {
expect(p.parse(" Gen 1").osis()).toEqual("Gen.1");
expect(p.parse("Matt5John3").osis()).toEqual("Matt.5,John.3");
expect(p.parse("1Ps 1").osis()).toEqual("");
return expect(p.parse("11Sam 1").osis()).toEqual("");
});
});
describe("Localized book Gen (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Gen (ar)", function() {
expect(p.parse("سفر التكوين 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("التكوين 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("ﺗﻜﻮﻳﻦ 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("تك 1:1").osis()).toEqual("Gen.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر التكوين 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("التكوين 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("ﺗﻜﻮﻳﻦ 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("تك 1:1").osis()).toEqual("Gen.1.1")
;
return true;
});
});
describe("Localized book Exod (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Exod (ar)", function() {
expect(p.parse("سفر الخروج 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("الخروج 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("خر 1:1").osis()).toEqual("Exod.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر الخروج 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("الخروج 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("خر 1:1").osis()).toEqual("Exod.1.1")
;
return true;
});
});
describe("Localized book Bel (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Bel (ar)", function() {
expect(p.parse("بل والتنين 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1")
;
return true;
});
});
describe("Localized book Lev (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Lev (ar)", function() {
expect(p.parse("سفر اللاويين 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("اللاويين 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("الأحبار 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("ﺍﻟﻼﻭﻳﻲ 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("أح 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("لا 1:1").osis()).toEqual("Lev.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر اللاويين 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("اللاويين 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("الأحبار 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("ﺍﻟﻼﻭﻳﻲ 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("أح 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("لا 1:1").osis()).toEqual("Lev.1.1")
;
return true;
});
});
describe("Localized book Num (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Num (ar)", function() {
expect(p.parse("سفر العدد 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("العدد 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("عد 1:1").osis()).toEqual("Num.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر العدد 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("العدد 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("عد 1:1").osis()).toEqual("Num.1.1")
;
return true;
});
});
describe("Localized book Sir (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Sir (ar)", function() {
expect(p.parse("سفر ابن سيراخ 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("يشوع بن سيراخ 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("سيراخ 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("سي 1:1").osis()).toEqual("Sir.1.1")
;
return true;
});
});
describe("Localized book Wis (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Wis (ar)", function() {
expect(p.parse("حكمة سليمان 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("سفر الحكمة 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("الحكمة 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("حك 1:1").osis()).toEqual("Wis.1.1")
;
return true;
});
});
describe("Localized book Lam (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Lam (ar)", function() {
expect(p.parse("سفر مراثي إرميا 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("مراثي إرميا 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("المراثي 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("مرا 1:1").osis()).toEqual("Lam.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر مراثي إرميا 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("مراثي إرميا 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("المراثي 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("مرا 1:1").osis()).toEqual("Lam.1.1")
;
return true;
});
});
describe("Localized book EpJer (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: EpJer (ar)", function() {
expect(p.parse("رسالة إرميا 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1")
;
return true;
});
});
describe("Localized book PrMan (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: PrMan (ar)", function() {
expect(p.parse("صلاة منسى 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1")
;
return true;
});
});
describe("Localized book Deut (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Deut (ar)", function() {
expect(p.parse("تثنية الإشتراع 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("سفر التثنية 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("تَثنِيَة 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("التثنية 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("تث 1:1").osis()).toEqual("Deut.1.1")
p.include_apocrypha(false)
expect(p.parse("تثنية الإشتراع 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("سفر التثنية 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("تَثنِيَة 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("التثنية 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("تث 1:1").osis()).toEqual("Deut.1.1")
;
return true;
});
});
describe("Localized book Josh (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Josh (ar)", function() {
expect(p.parse("سفر يشوع 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("يشوع 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("يش 1:1").osis()).toEqual("Josh.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر يشوع 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("يشوع 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("يش 1:1").osis()).toEqual("Josh.1.1")
;
return true;
});
});
describe("Localized book Judg (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Judg (ar)", function() {
expect(p.parse("سفر القضاة 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("القضاة 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("قض 1:1").osis()).toEqual("Judg.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر القضاة 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("القضاة 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("قض 1:1").osis()).toEqual("Judg.1.1")
;
return true;
});
});
describe("Localized book Ruth (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Ruth (ar)", function() {
expect(p.parse("سفر راعوث 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("راعوث 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("را 1:1").osis()).toEqual("Ruth.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر راعوث 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("راعوث 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("را 1:1").osis()).toEqual("Ruth.1.1")
;
return true;
});
});
describe("Localized book 1Esd (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1Esd (ar)", function() {
expect(p.parse("إسدراس الأول 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1")
;
return true;
});
});
describe("Localized book 2Esd (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2Esd (ar)", function() {
expect(p.parse("إسدراس الثاني 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1")
;
return true;
});
});
describe("Localized book Isa (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Isa (ar)", function() {
expect(p.parse("سفر إشعياء 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("إشَعْياء 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ﺃﺷﻌﻴﺎء 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("إشعيا 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("اش 1:1").osis()).toEqual("Isa.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر إشعياء 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("إشَعْياء 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ﺃﺷﻌﻴﺎء 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("إشعيا 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("اش 1:1").osis()).toEqual("Isa.1.1")
;
return true;
});
});
describe("Localized book 2Sam (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2Sam (ar)", function() {
expect(p.parse("سفر صموئيل الثاني 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("الممالك الثاني 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("صموئيل الثّاني 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("صموئيل الثاني 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 صموئيل 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 صم 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر صموئيل الثاني 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("الممالك الثاني 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("صموئيل الثّاني 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("صموئيل الثاني 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 صموئيل 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 صم 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1")
;
return true;
});
});
describe("Localized book 1Sam (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1Sam (ar)", function() {
expect(p.parse("سفر صموئيل الأول 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("الممالك الأول 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("صموئيل الأول 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("ﺻﻤﻮﺋﻴﻞ ﺍﻷﻭﻝ 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 صموئيل 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 صم 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر صموئيل الأول 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("الممالك الأول 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("صموئيل الأول 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("ﺻﻤﻮﺋﻴﻞ ﺍﻷﻭﻝ 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 صموئيل 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 صم 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1")
;
return true;
});
});
describe("Localized book 2Kgs (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2Kgs (ar)", function() {
expect(p.parse("سفر الملوك الثاني 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("الممالك الرابع 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("ﺍﻟﻤﻠﻮﻙ ﺍﻟﺜﺎﻧﻲ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 الملوك 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 مل 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر الملوك الثاني 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("الممالك الرابع 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("ﺍﻟﻤﻠﻮﻙ ﺍﻟﺜﺎﻧﻲ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 الملوك 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 مل 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1")
;
return true;
});
});
describe("Localized book 1Kgs (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1Kgs (ar)", function() {
expect(p.parse("سفر الملوك الأول 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("الممالك الثالث 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("الملوك الأول 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("ﺍﻟﻤﻠﻮﻙ ﺍﻷﻭ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 الملوك 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 مل 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر الملوك الأول 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("الممالك الثالث 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("الملوك الأول 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("ﺍﻟﻤﻠﻮﻙ ﺍﻷﻭ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 الملوك 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 مل 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1")
;
return true;
});
});
describe("Localized book 2Chr (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2Chr (ar)", function() {
expect(p.parse("سفر أخبار الأيام الثاني 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("أخبار الأيام الثاني 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("ﺃﺧﺒﺎﺭ ﺍﻷﻳﺎﻡ ﺍﻟﺜﺎﻥ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("الأخبار 2 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 أخ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر أخبار الأيام الثاني 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("أخبار الأيام الثاني 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("ﺃﺧﺒﺎﺭ ﺍﻷﻳﺎﻡ ﺍﻟﺜﺎﻥ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("الأخبار 2 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 أخ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1")
;
return true;
});
});
describe("Localized book 1Chr (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1Chr (ar)", function() {
expect(p.parse("سفر أخبار الأيام الأول 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("أخبار الأيام الأول 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("ﺃﺧﺒﺎﺭ ﺍﻷﻳﺎﻡ ﺍﻷ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("الأخبار 1 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 أخ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر أخبار الأيام الأول 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("أخبار الأيام الأول 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("ﺃﺧﺒﺎﺭ ﺍﻷﻳﺎﻡ ﺍﻷ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("الأخبار 1 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 أخ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1")
;
return true;
});
});
describe("Localized book Ezra (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Ezra (ar)", function() {
expect(p.parse("سفر عزرا 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("عزرا 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("عـز 1:1").osis()).toEqual("Ezra.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر عزرا 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("عزرا 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("عـز 1:1").osis()).toEqual("Ezra.1.1")
;
return true;
});
});
describe("Localized book Neh (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Neh (ar)", function() {
expect(p.parse("سفر نحميا 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("نحميا 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("نح 1:1").osis()).toEqual("Neh.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر نحميا 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("نحميا 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("نح 1:1").osis()).toEqual("Neh.1.1")
;
return true;
});
});
describe("Localized book GkEsth (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: GkEsth (ar)", function() {
expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1")
;
return true;
});
});
describe("Localized book Esth (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Esth (ar)", function() {
expect(p.parse("سفر أستير 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("أستير 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("أس 1:1").osis()).toEqual("Esth.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر أستير 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("أستير 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("أس 1:1").osis()).toEqual("Esth.1.1")
;
return true;
});
});
describe("Localized book Job (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Job (ar)", function() {
expect(p.parse("سفر أيوب 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("أيوب 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("أي 1:1").osis()).toEqual("Job.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر أيوب 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("أيوب 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("أي 1:1").osis()).toEqual("Job.1.1")
;
return true;
});
});
describe("Localized book Ps (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Ps (ar)", function() {
expect(p.parse("سفر المزامير 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("المَزمُور 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("المزامير 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("المزمور 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("مزمور 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("مز 1:1").osis()).toEqual("Ps.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر المزامير 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("المَزمُور 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("المزامير 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("المزمور 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("مزمور 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("مز 1:1").osis()).toEqual("Ps.1.1")
;
return true;
});
});
describe("Localized book PrAzar (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: PrAzar (ar)", function() {
expect(p.parse("صلاة عزريا 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1")
;
return true;
});
});
describe("Localized book Prov (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Prov (ar)", function() {
expect(p.parse("سفر الأمثال 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("الأمثال 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("أمثال 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("ﺃﻣﺜﺎﻝ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("مثل 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("ام 1:1").osis()).toEqual("Prov.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر الأمثال 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("الأمثال 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("أمثال 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("ﺃﻣﺜﺎﻝ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("مثل 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("ام 1:1").osis()).toEqual("Prov.1.1")
;
return true;
});
});
describe("Localized book Eccl (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Eccl (ar)", function() {
expect(p.parse("سفر الجامعة 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("الجامعة 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("جا 1:1").osis()).toEqual("Eccl.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر الجامعة 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("الجامعة 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("جا 1:1").osis()).toEqual("Eccl.1.1")
;
return true;
});
});
describe("Localized book SgThree (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: SgThree (ar)", function() {
expect(p.parse("أنشودة الأطفال الثلاثة 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1")
;
return true;
});
});
describe("Localized book Song (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Song (ar)", function() {
expect(p.parse("سفر نشيد الأنشاد 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("نشيد الأناشيد 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("ﻧﺸﻴﺪ ﺍﻷﻧﺸﺎ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("نش 1:1").osis()).toEqual("Song.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر نشيد الأنشاد 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("نشيد الأناشيد 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("ﻧﺸﻴﺪ ﺍﻷﻧﺸﺎ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("نش 1:1").osis()).toEqual("Song.1.1")
;
return true;
});
});
describe("Localized book Jer (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Jer (ar)", function() {
expect(p.parse("سفر إرميا 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("ﺃﺭﻣﻴﺎء 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("أرميا 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("إرميا 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("ار 1:1").osis()).toEqual("Jer.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر إرميا 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("ﺃﺭﻣﻴﺎء 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("أرميا 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("إرميا 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("ار 1:1").osis()).toEqual("Jer.1.1")
;
return true;
});
});
describe("Localized book Ezek (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Ezek (ar)", function() {
expect(p.parse("سفر حزقيال 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("حزقيال 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("حز 1:1").osis()).toEqual("Ezek.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر حزقيال 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("حزقيال 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("حز 1:1").osis()).toEqual("Ezek.1.1")
;
return true;
});
});
describe("Localized book Dan (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Dan (ar)", function() {
expect(p.parse("سفر دانيال 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("دانيال 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("دا 1:1").osis()).toEqual("Dan.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر دانيال 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("دانيال 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("دا 1:1").osis()).toEqual("Dan.1.1")
;
return true;
});
});
describe("Localized book Hos (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Hos (ar)", function() {
expect(p.parse("سفر هوشع 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("هوشع 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("هو 1:1").osis()).toEqual("Hos.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر هوشع 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("هوشع 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("هو 1:1").osis()).toEqual("Hos.1.1")
;
return true;
});
});
describe("Localized book Joel (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Joel (ar)", function() {
expect(p.parse("سفر يوئيل 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("يوئيل 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("يوء 1:1").osis()).toEqual("Joel.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر يوئيل 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("يوئيل 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("يوء 1:1").osis()).toEqual("Joel.1.1")
;
return true;
});
});
describe("Localized book Amos (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Amos (ar)", function() {
expect(p.parse("سفر عاموس 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("عاموس 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("عا 1:1").osis()).toEqual("Amos.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر عاموس 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("عاموس 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("عا 1:1").osis()).toEqual("Amos.1.1")
;
return true;
});
});
describe("Localized book Obad (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Obad (ar)", function() {
expect(p.parse("سفر عوبديا 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("عوبديا 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("عو 1:1").osis()).toEqual("Obad.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر عوبديا 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("عوبديا 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("عو 1:1").osis()).toEqual("Obad.1.1")
;
return true;
});
});
describe("Localized book Jonah (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Jonah (ar)", function() {
expect(p.parse("سفر يونان 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("يونان 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("يون 1:1").osis()).toEqual("Jonah.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر يونان 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("يونان 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("يون 1:1").osis()).toEqual("Jonah.1.1")
;
return true;
});
});
describe("Localized book Mic (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Mic (ar)", function() {
expect(p.parse("سفر ميخا 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("ميخا 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("مي 1:1").osis()).toEqual("Mic.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر ميخا 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("ميخا 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("مي 1:1").osis()).toEqual("Mic.1.1")
;
return true;
});
});
describe("Localized book Nah (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Nah (ar)", function() {
expect(p.parse("سفر ناحوم 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("ناحوم 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("نحوم 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("نحو 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("نا 1:1").osis()).toEqual("Nah.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر ناحوم 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("ناحوم 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("نحوم 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("نحو 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("نا 1:1").osis()).toEqual("Nah.1.1")
;
return true;
});
});
describe("Localized book Hab (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Hab (ar)", function() {
expect(p.parse("سفر حبقوق 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("حبقوق 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("حب 1:1").osis()).toEqual("Hab.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر حبقوق 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("حبقوق 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("حب 1:1").osis()).toEqual("Hab.1.1")
;
return true;
});
});
describe("Localized book Zeph (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Zeph (ar)", function() {
expect(p.parse("سفر صفنيا 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("صفنيا 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("صف 1:1").osis()).toEqual("Zeph.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر صفنيا 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("صفنيا 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("صف 1:1").osis()).toEqual("Zeph.1.1")
;
return true;
});
});
describe("Localized book Hag (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Hag (ar)", function() {
expect(p.parse("سفر حجي 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("حجَّي 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("حجاي 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("حجي 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("حج 1:1").osis()).toEqual("Hag.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر حجي 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("حجَّي 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("حجاي 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("حجي 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("حج 1:1").osis()).toEqual("Hag.1.1")
;
return true;
});
});
describe("Localized book Zech (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Zech (ar)", function() {
expect(p.parse("زَكَرِيّا 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("سفر زكريا 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("زكريا 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("زك 1:1").osis()).toEqual("Zech.1.1")
p.include_apocrypha(false)
expect(p.parse("زَكَرِيّا 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("سفر زكريا 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("زكريا 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("زك 1:1").osis()).toEqual("Zech.1.1")
;
return true;
});
});
describe("Localized book Mal (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Mal (ar)", function() {
expect(p.parse("سفر ملاخي 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("ملاخي 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("ملا 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("ﻣﻼﺥ 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("مل 1:1").osis()).toEqual("Mal.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر ملاخي 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("ملاخي 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("ملا 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("ﻣﻼﺥ 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("مل 1:1").osis()).toEqual("Mal.1.1")
;
return true;
});
});
describe("Localized book Matt (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Matt (ar)", function() {
expect(p.parse("إنجيل متى 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("متى 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("مت 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("إنجيل متى 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("متى 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("مت 1:1").osis()).toEqual("Matt.1.1")
;
return true;
});
});
describe("Localized book Mark (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Mark (ar)", function() {
expect(p.parse("إنجيل مرقس 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("مرقس 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("مر 1:1").osis()).toEqual("Mark.1.1")
p.include_apocrypha(false)
expect(p.parse("إنجيل مرقس 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("مرقس 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("مر 1:1").osis()).toEqual("Mark.1.1")
;
return true;
});
});
describe("Localized book Luke (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Luke (ar)", function() {
expect(p.parse("إنجيل لوقا 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("لوقا 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("لو 1:1").osis()).toEqual("Luke.1.1")
p.include_apocrypha(false)
expect(p.parse("إنجيل لوقا 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("لوقا 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("لو 1:1").osis()).toEqual("Luke.1.1")
;
return true;
});
});
describe("Localized book 1John (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1John (ar)", function() {
expect(p.parse("رسالة القديس يوحنا الأولى 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("رسالة يوحنا الأولى 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("رسالة يوحنا 1 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("يوحنا الأولى 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("ﻳﻮﺣﻨﺎ ﺍﻻﻭﻝ 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 يو 1:1").osis()).toEqual("1John.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة القديس يوحنا الأولى 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("رسالة يوحنا الأولى 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("رسالة يوحنا 1 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("يوحنا الأولى 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("ﻳﻮﺣﻨﺎ ﺍﻻﻭﻝ 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 يو 1:1").osis()).toEqual("1John.1.1")
;
return true;
});
});
describe("Localized book 2John (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2John (ar)", function() {
expect(p.parse("رسالة القديس يوحنا الثانية 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("رسالة يوحنا الثانية 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("رسالة يوحنا 2 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("يوحنا الثانية 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 يو 1:1").osis()).toEqual("2John.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة القديس يوحنا الثانية 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("رسالة يوحنا الثانية 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("رسالة يوحنا 2 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("يوحنا الثانية 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 يو 1:1").osis()).toEqual("2John.1.1")
;
return true;
});
});
describe("Localized book 3John (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 3John (ar)", function() {
expect(p.parse("رسالة القديس يوحنا الثالثة 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("رسالة يوحنا الثالثة 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("رسالة يوحنا 3 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("يوحنا الثالثة 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 يو 1:1").osis()).toEqual("3John.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة القديس يوحنا الثالثة 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("رسالة يوحنا الثالثة 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("رسالة يوحنا 3 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("يوحنا الثالثة 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 يو 1:1").osis()).toEqual("3John.1.1")
;
return true;
});
});
describe("Localized book Rev (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Rev (ar)", function() {
expect(p.parse("رؤيا يوحنا 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ﻳﻮﺣﻨﺎ ﺭﺅﻳﺎ 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("الرؤيــا 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("رؤ 1:1").osis()).toEqual("Rev.1.1")
p.include_apocrypha(false)
expect(p.parse("رؤيا يوحنا 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ﻳﻮﺣﻨﺎ ﺭﺅﻳﺎ 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("الرؤيــا 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("رؤ 1:1").osis()).toEqual("Rev.1.1")
;
return true;
});
});
describe("Localized book John (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: John (ar)", function() {
expect(p.parse("إنجيل يوحنا 1:1").osis()).toEqual("John.1.1")
expect(p.parse("يوحنا 1:1").osis()).toEqual("John.1.1")
expect(p.parse("John 1:1").osis()).toEqual("John.1.1")
expect(p.parse("يو 1:1").osis()).toEqual("John.1.1")
p.include_apocrypha(false)
expect(p.parse("إنجيل يوحنا 1:1").osis()).toEqual("John.1.1")
expect(p.parse("يوحنا 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("يو 1:1").osis()).toEqual("John.1.1")
;
return true;
});
});
describe("Localized book Acts (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Acts (ar)", function() {
expect(p.parse("سفر أعمال الرسل 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("أعمال الرسل 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("ﺍﻋﻤﺎﻝ ﺍﻟﺮﺳﻞ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("اع 1:1").osis()).toEqual("Acts.1.1")
p.include_apocrypha(false)
expect(p.parse("سفر أعمال الرسل 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("أعمال الرسل 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("ﺍﻋﻤﺎﻝ ﺍﻟﺮﺳﻞ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("اع 1:1").osis()).toEqual("Acts.1.1")
;
return true;
});
});
describe("Localized book Rom (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Rom (ar)", function() {
expect(p.parse("رسالة بولس الرسول إلى أهل رومية 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("الرسالة إلى أهل رومية 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("رسالة روما 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ﺭﻭﻣﻴﺔ 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("روم 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("رو 1:1").osis()).toEqual("Rom.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول إلى أهل رومية 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("الرسالة إلى أهل رومية 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("رسالة روما 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ﺭﻭﻣﻴﺔ 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("روم 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("رو 1:1").osis()).toEqual("Rom.1.1")
;
return true;
});
});
describe("Localized book 2Cor (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2Cor (ar)", function() {
expect(p.parse("رسالة بولس الرسول الثانية إلى أهل كورنثوس 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("الرسالة الثانية إلى أهل كورنثوس 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("كورنثوس الثانية 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 قور 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2كو 1:1").osis()).toEqual("2Cor.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول الثانية إلى أهل كورنثوس 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("الرسالة الثانية إلى أهل كورنثوس 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("كورنثوس الثانية 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 قور 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2كو 1:1").osis()).toEqual("2Cor.1.1")
;
return true;
});
});
describe("Localized book 1Cor (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1Cor (ar)", function() {
expect(p.parse("رسالة بولس الرسول الأولى إلى أهل كورنثوس 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("الرسالة الأولى إلى أهل كورنثوس 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("كورنثوس الأولى 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("ﻛﻮﺭﻧﺜﻮﺱ ﺍﻻﻭﻝ 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 قور 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1كو 1:1").osis()).toEqual("1Cor.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول الأولى إلى أهل كورنثوس 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("الرسالة الأولى إلى أهل كورنثوس 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("كورنثوس الأولى 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("ﻛﻮﺭﻧﺜﻮﺱ ﺍﻻﻭﻝ 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 قور 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1كو 1:1").osis()).toEqual("1Cor.1.1")
;
return true;
});
});
describe("Localized book Gal (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Gal (ar)", function() {
expect(p.parse("رسالة بولس الرسول إلى أهل غلاطية 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("الرسالة إلى أهل غلاطية 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("رسالة غلاطية 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("ﻏﻼﻃﻲ 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("غل 1:1").osis()).toEqual("Gal.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول إلى أهل غلاطية 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("الرسالة إلى أهل غلاطية 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("رسالة غلاطية 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("ﻏﻼﻃﻲ 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("غل 1:1").osis()).toEqual("Gal.1.1")
;
return true;
});
});
describe("Localized book Eph (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Eph (ar)", function() {
expect(p.parse("رسالة بولس الرسول إلى أهل أفسس 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("الرسالة إلى أهل أفسس 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("رسالة أفسس 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("ﺃﻓﺴﺲ 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("أف 1:1").osis()).toEqual("Eph.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول إلى أهل أفسس 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("الرسالة إلى أهل أفسس 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("رسالة أفسس 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("ﺃﻓﺴﺲ 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("أف 1:1").osis()).toEqual("Eph.1.1")
;
return true;
});
});
describe("Localized book Phil (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Phil (ar)", function() {
expect(p.parse("رسالة بولس الرسول إلى أهل فيلبي 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("الرسالة إلى أهل فيلبي 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("رسالة فيلبي 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("ﻓﻴﻠﻴﺒﻲ 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("فل 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("في 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول إلى أهل فيلبي 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("الرسالة إلى أهل فيلبي 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("رسالة فيلبي 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("ﻓﻴﻠﻴﺒﻲ 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("فل 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("في 1:1").osis()).toEqual("Phil.1.1")
;
return true;
});
});
describe("Localized book Col (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Col (ar)", function() {
expect(p.parse("رسالة بولس الرسول إلى أهل كولوسي 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("الرسالة إلى أهل كولوسي 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("رسالة كولوسي 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("ﻛﻮﻟﻮﺳﻲ 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("قول 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("كو 1:1").osis()).toEqual("Col.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول إلى أهل كولوسي 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("الرسالة إلى أهل كولوسي 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("رسالة كولوسي 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("ﻛﻮﻟﻮﺳﻲ 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("قول 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("كو 1:1").osis()).toEqual("Col.1.1")
;
return true;
});
});
describe("Localized book 2Thess (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2Thess (ar)", function() {
expect(p.parse("رسالة بولس الرسول الثانية إلى أهل تسالونيكي 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("الرسالة الثانية إلى أهل تسالونيكي 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("رسالة تسالونيكي الثانية 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("ﺍﻟﺜﺎﻧﻴﺔ ﺗﺴﺎﻟﻮﻧﻴﻜﻲ 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 تس 1:1").osis()).toEqual("2Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول الثانية إلى أهل تسالونيكي 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("الرسالة الثانية إلى أهل تسالونيكي 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("رسالة تسالونيكي الثانية 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("ﺍﻟﺜﺎﻧﻴﺔ ﺗﺴﺎﻟﻮﻧﻴﻜﻲ 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 تس 1:1").osis()).toEqual("2Thess.1.1")
;
return true;
});
});
describe("Localized book 1Thess (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1Thess (ar)", function() {
expect(p.parse("رسالة بولس الرسول الأولى إلى أهل تسالونيكي 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("الرسالة الأولى إلى أهل تسالونيكي 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("رسالة تسالونيكي الأولى 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("ﺍﻻﻭﻝ ﺗﺴﺎﻟﻮﻧﻴﻜﻲ 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 تس 1:1").osis()).toEqual("1Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول الأولى إلى أهل تسالونيكي 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("الرسالة الأولى إلى أهل تسالونيكي 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("رسالة تسالونيكي الأولى 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("ﺍﻻﻭﻝ ﺗﺴﺎﻟﻮﻧﻴﻜﻲ 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 تس 1:1").osis()).toEqual("1Thess.1.1")
;
return true;
});
});
describe("Localized book 2Tim (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2Tim (ar)", function() {
expect(p.parse("رسالة بولس الرسول الثانية إلى تيموثاوس 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("الرسالة الثانية إلى تيموثاوس 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("تيموثاوس الثانية 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("ﺍﻟﺜﺎﻧﻴﺔ ﺗﻴﻤﻮﺛﺎﻭﺱ 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 طيم 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول الثانية إلى تيموثاوس 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("الرسالة الثانية إلى تيموثاوس 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("تيموثاوس الثانية 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("ﺍﻟﺜﺎﻧﻴﺔ ﺗﻴﻤﻮﺛﺎﻭﺱ 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 طيم 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1")
;
return true;
});
});
describe("Localized book 1Tim (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1Tim (ar)", function() {
expect(p.parse("رسالة بولس الرسول الأولى إلى تيموثاوس 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("الرسالة الأولى إلى تيموثاوس 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("تيموثاوس الأولى 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("ﺍﻻﻭﻝ ﺗﻴﻤﻮﺛﺎﻭﺱ 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 طيم 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول الأولى إلى تيموثاوس 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("الرسالة الأولى إلى تيموثاوس 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("تيموثاوس الأولى 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("ﺍﻻﻭﻝ ﺗﻴﻤﻮﺛﺎﻭﺱ 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 طيم 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1")
;
return true;
});
});
describe("Localized book Titus (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Titus (ar)", function() {
expect(p.parse("رسالة بولس الرسول إلى تيطس 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("الرسالة إلى تيطس 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("طيطس 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("ﺗﻴﻄﺲ 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("تي 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("طي 1:1").osis()).toEqual("Titus.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول إلى تيطس 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("الرسالة إلى تيطس 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("طيطس 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("ﺗﻴﻄﺲ 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("تي 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("طي 1:1").osis()).toEqual("Titus.1.1")
;
return true;
});
});
describe("Localized book Phlm (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Phlm (ar)", function() {
expect(p.parse("رسالة بولس الرسول إلى فليمون 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("الرسالة إلى فليمون 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("فليمون 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("فيل 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("ف 1:1").osis()).toEqual("Phlm.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة بولس الرسول إلى فليمون 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("الرسالة إلى فليمون 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("فليمون 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("فيل 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("ف 1:1").osis()).toEqual("Phlm.1.1")
;
return true;
});
});
describe("Localized book Heb (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Heb (ar)", function() {
expect(p.parse("الرسالة إلى العبرانيين 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("العبرانيين 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("عب 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("الرسالة إلى العبرانيين 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("العبرانيين 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("عب 1:1").osis()).toEqual("Heb.1.1")
;
return true;
});
});
describe("Localized book Jas (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Jas (ar)", function() {
expect(p.parse("رسالة القديس يعقوب 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("رسالة يعقوب 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("يعقوب 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("يع 1:1").osis()).toEqual("Jas.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة القديس يعقوب 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("رسالة يعقوب 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("يعقوب 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("يع 1:1").osis()).toEqual("Jas.1.1")
;
return true;
});
});
describe("Localized book 2Pet (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2Pet (ar)", function() {
expect(p.parse("رسالة القديس بطرس الثانية 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("رسالة بطرس الثانية 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("بطرس الثانية 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("رسالة بطرس 2 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 بط 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2بط 1:1").osis()).toEqual("2Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة القديس بطرس الثانية 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("رسالة بطرس الثانية 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("بطرس الثانية 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("رسالة بطرس 2 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 بط 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2بط 1:1").osis()).toEqual("2Pet.1.1")
;
return true;
});
});
describe("Localized book 1Pet (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1Pet (ar)", function() {
expect(p.parse("رسالة القديس بطرس الأولى 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("رسالة بطرس الأولى 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("رسالة بطرس 1 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("بطرس الأولى 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 بط 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1بط 1:1").osis()).toEqual("1Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالة القديس بطرس الأولى 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("رسالة بطرس الأولى 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("رسالة بطرس 1 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("بطرس الأولى 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 بط 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1بط 1:1").osis()).toEqual("1Pet.1.1")
;
return true;
});
});
describe("Localized book Jude (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Jude (ar)", function() {
expect(p.parse("رسالى القديس يهوذا 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("رسالة يهوذا 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("يهوذا 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("يهو 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("يه 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("رسالى القديس يهوذا 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("رسالة يهوذا 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("يهوذا 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("يهو 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("يه 1:1").osis()).toEqual("Jude.1.1")
;
return true;
});
});
describe("Localized book Tob (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Tob (ar)", function() {
expect(p.parse("سفر طوبيا 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("طوبيا 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("طو 1:1").osis()).toEqual("Tob.1.1")
;
return true;
});
});
describe("Localized book Jdt (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Jdt (ar)", function() {
expect(p.parse("سفر يهوديت 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("يهوديت 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("يـه 1:1").osis()).toEqual("Jdt.1.1")
;
return true;
});
});
describe("Localized book Bar (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Bar (ar)", function() {
expect(p.parse("سفر باروخ 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("باروك 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("با 1:1").osis()).toEqual("Bar.1.1")
;
return true;
});
});
describe("Localized book Sus (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: Sus (ar)", function() {
expect(p.parse("كتاب سوزانا 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("سوزانا 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1")
;
return true;
});
});
describe("Localized book 2Macc (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 2Macc (ar)", function() {
expect(p.parse("سفر المكابين الثاني 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("المكابين الثاني 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 المكابيين 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 مك 1:1").osis()).toEqual("2Macc.1.1")
;
return true;
});
});
describe("Localized book 3Macc (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 3Macc (ar)", function() {
expect(p.parse("المكابين الثالث 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1")
;
return true;
});
});
describe("Localized book 4Macc (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 4Macc (ar)", function() {
expect(p.parse("المكابين الرابع 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1")
;
return true;
});
});
describe("Localized book 1Macc (ar)", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
return it("should handle book: 1Macc (ar)", function() {
expect(p.parse("سفر المكابين الأول 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("المكابين الأول 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 المكابيين 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 مك 1:1").osis()).toEqual("1Macc.1.1")
;
return true;
});
});
describe("Miscellaneous tests", function() {
var p;
p = {};
beforeEach(function() {
p = new bcv_parser;
p.set_options({
book_alone_strategy: "ignore",
book_sequence_strategy: "ignore",
osis_compaction_strategy: "bc",
captive_end_digits_strategy: "delete"
});
return p.include_apocrypha(true);
});
it("should return the expected language", function() {
return expect(p.languages).toEqual(["ar"]);
});
it("should handle ranges (ar)", function() {
expect(p.parse("Titus 1:1 to 2").osis()).toEqual("Titus.1.1-Titus.1.2");
expect(p.parse("Matt 1to2").osis()).toEqual("Matt.1-Matt.2");
return expect(p.parse("Phlm 2 TO 3").osis()).toEqual("Phlm.1.2-Phlm.1.3");
});
it("should handle chapters (ar)", function() {
expect(p.parse("Titus 1:1, فصل 2").osis()).toEqual("Titus.1.1,Titus.2");
return expect(p.parse("Matt 3:4 فصل 6").osis()).toEqual("Matt.3.4,Matt.6");
});
it("should handle verses (ar)", function() {
expect(p.parse("Exod 1:1 آية 3").osis()).toEqual("Exod.1.1,Exod.1.3");
return expect(p.parse("Phlm آية 6").osis()).toEqual("Phlm.1.6");
});
it("should handle 'and' (ar)", function() {
expect(p.parse("Exod 1:1 ، 3").osis()).toEqual("Exod.1.1,Exod.1.3");
return expect(p.parse("Phlm 2 ، 6").osis()).toEqual("Phlm.1.2,Phlm.1.6");
});
it("should handle titles (ar)", function() {
expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual("Ps.3.1,Ps.4.2,Ps.5.1");
return expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual("Ps.3.1,Ps.4.2,Ps.5.1");
});
it("should handle 'ff' (ar)", function() {
expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual("Rev.3-Rev.22,Rev.4.2-Rev.4.11");
return expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual("Rev.3-Rev.22,Rev.4.2-Rev.4.11");
});
it("should handle translations (ar)", function() {
expect(p.parse("Lev 1 (ALAB)").osis_and_translations()).toEqual([["Lev.1", "ALAB"]]);
expect(p.parse("lev 1 alab").osis_and_translations()).toEqual([["Lev.1", "ALAB"]]);
expect(p.parse("Lev 1 (VD)").osis_and_translations()).toEqual([["Lev.1", "VD"]]);
return expect(p.parse("lev 1 vd").osis_and_translations()).toEqual([["Lev.1", "VD"]]);
});
return it("should handle boundaries (ar)", function() {
p.set_options({
book_alone_strategy: "full"
});
expect(p.parse("\u2014Matt\u2014").osis()).toEqual("Matt.1-Matt.28");
return expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual("Matt.1.1");
});
});
}).call(this);
| mit |
PenoaksDev/HolyWorlds | fw/views/messages/chat.blade.php | 294 | @if (Auth::check())
<div id="chat_header">
<span id="chat_header_title">Chat</span>
<span id="chat_header_icon" class="fa fa-comments fa-3x"></span>
</div>
<div id="chat_box">
<div id="chat_box_content"></div>
<input type="text" id="chat_input" placeholder="chat" />
</div>
@endif | mit |
doijunior/muter | src/br/edu/ifpr/tcc/gamification/Leaderboard.java | 479 | package br.edu.ifpr.tcc.gamification;
import java.util.ArrayList;
import java.util.Collections;
public class Leaderboard {
private ArrayList <Wallet> walletList;
public Leaderboard (){
walletList=new ArrayList<Wallet>();
}
public void addWallet (Wallet wallet){
this.walletList.add(wallet);
}
public ArrayList<Wallet> organizeWallet (){
Collections.sort(this.walletList);
return walletList;
}
public ArrayList<Wallet> getWalletList(){
return walletList;
}
}
| mit |
ArthurMialon/StarterApiNodejs | api/models/user.js | 1085 | import Waterline from 'Waterline';
import bcrypt from 'bcrypt-nodejs';
/*---------------------------------------------/
| User Model
|
| Export simple Waterline Collection
|----------------------------------------------*/
export default Waterline.Collection.extend({
identity: 'user',
connection: 'myMongo',
attributes: {
username: {
type: 'string',
required: true,
},
password: {
type: 'string',
required: true,
},
first_name: {
type: 'string',
required: true,
maxLength: 20
},
last_name: {
type: 'string',
required: true,
maxLength: 20
},
/**
* Get fullname
*/
fullName() {
return `${this.first_name} ${this.last_name}`;
},
/**
* Compare password and validate
*/
validPassword(password) {
return bcrypt.compareSync(password, this.password);
}
},
/**
* Before create the user
*/
beforeCreate(user, next) {
user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(8), null);
next();
},
});
| mit |
nelsonperez/osha-web-app | app/tests/car-model.server.model.test.js | 1135 | 'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
CarModel = mongoose.model('CarModel');
/**
* Globals
*/
var user, carModel;
/**
* Unit tests
*/
describe('Car model Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
carModel = new CarModel({
name: 'Car model Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return carModel.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
carModel.name = '';
return carModel.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
CarModel.remove().exec();
User.remove().exec();
done();
});
}); | mit |
dfslima/portalCliente | src/main/webapp/app/src/module/customer/controllers/customer.edit.js | 3219 | app.controller('editCustomerController', function ($scope, $location, $rootScope, $timeout, $window, userFactory,
maskFactory, validationFactory, toast, customer, customerService) {
userFactory
angular.extend($scope, validationFactory);
$scope.showType = true;
$rootScope.isBusy = false;
$scope.calDays = days();
$scope.calMonth = month();
$scope.calYear = year();
$scope.address = customer.address;
$scope.customer = customer;
$scope.marital = maritalStatusForSelected();
$scope.genreCustomer = genreForSelected();
$scope.states = states();
var pf = 'app/src/module/customer/template/customer.pf.html';
var pj = 'app/src/module/customer/template/customer.pj.html';
$scope.formAddress = 'app/src/module/address/address.form.html';
$scope.type = customer.type;
$scope.selectedCustomer = function (type) {
$scope.type = parseInt(type);
if ($scope.type == 1) {
$scope.formType = pf;
} else if ($scope.type == 2) {
$scope.formType = pj;
}
};
$scope.selectedCustomer($scope.type);
if (customer.birthDate != undefined) {
var dataCustomer = customer.birthDate;
var str = dataCustomer.split("/");
$scope.day = str[0];
$scope.month = str[1];
$scope.year = str[2];
}
$scope.save = function (customerForm) {
$scope.validate = false;
$scope.invalidValueCpf = false;
$scope.invalidValueCnpj = false;
if (customerForm.$valid) {
if ($scope.address !== undefined && $scope.address !== null && $scope.address !== '') {
$scope.customer.address = $scope.address;
}
if ($scope.customer.type == 1) {
// Concatena os campos vindos dos selects para formar a data
$scope.customer.birthDate = $scope.day + "/" + $scope.month + "/" + $scope.year;
}
// Retira os caractes especiais do cpf/cnpj
$scope.customer.cpfCnpj = $scope.customer.cpfCnpj.replace(/\./g, "").replace("/", "").replace("-", "");
$rootScope.isBusy = true;
$scope.customer.user = userFactory.getUser();
customerService.edit($scope.customer).then(function (response) {
$rootScope.isBusy = false;
if (response != undefined) {
if (response.erro) {
toast.open('warning', response.message);
return;
}
}
toast.open('success', 'Cliente alterado com sucesso');
$location.path('/customers');
});
}
else {
$rootScope.isBusy = false;
$scope.validate = true;
if ($scope.customer.type == 1) {
$scope.addressForm = $scope.pfForm = $scope.customerForm;
}
else if ($scope.customer.type == 2) {
$scope.addressForm = $scope.pjForm = $scope.customerForm;
}
}
};
$scope.goBack = function () {
$location.path('/customers');
};
}); | mit |
tilemapjp/OSGeo.GDAL.Xamarin | gdal-1.11.0/frmts/hfa/hfaopen.cpp | 154658 | /******************************************************************************
* $Id: hfaopen.cpp 27044 2014-03-16 23:41:27Z rouault $
*
* Project: Erdas Imagine (.img) Translator
* Purpose: Supporting functions for HFA (.img) ... main (C callable) API
* that is not dependent on GDAL (just CPL).
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 1999, Intergraph Corporation
* Copyright (c) 2007-2011, Even Rouault <even dot rouault at mines-paris dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************
*
* hfaopen.cpp
*
* Supporting routines for reading Erdas Imagine (.imf) Heirarchical
* File Architecture files. This is intended to be a library independent
* of the GDAL core, but dependent on the Common Portability Library.
*
*/
#include "hfa_p.h"
#include "cpl_conv.h"
#include <limits.h>
#include <vector>
CPL_CVSID("$Id: hfaopen.cpp 27044 2014-03-16 23:41:27Z rouault $");
static const char *apszAuxMetadataItems[] = {
// node/entry field_name metadata_key type
"Statistics", "dminimum", "STATISTICS_MINIMUM", "Esta_Statistics",
"Statistics", "dmaximum", "STATISTICS_MAXIMUM", "Esta_Statistics",
"Statistics", "dmean", "STATISTICS_MEAN", "Esta_Statistics",
"Statistics", "dmedian", "STATISTICS_MEDIAN", "Esta_Statistics",
"Statistics", "dmode", "STATISTICS_MODE", "Esta_Statistics",
"Statistics", "dstddev", "STATISTICS_STDDEV", "Esta_Statistics",
"HistogramParameters", "lBinFunction.numBins", "STATISTICS_HISTONUMBINS","Eimg_StatisticsParameters830",
"HistogramParameters", "dBinFunction.minLimit", "STATISTICS_HISTOMIN", "Eimg_StatisticsParameters830",
"HistogramParameters", "dBinFunction.maxLimit", "STATISTICS_HISTOMAX", "Eimg_StatisticsParameters830",
"StatisticsParameters", "lSkipFactorX", "STATISTICS_SKIPFACTORX", "",
"StatisticsParameters", "lSkipFactorY", "STATISTICS_SKIPFACTORY", "",
"StatisticsParameters", "dExcludedValues", "STATISTICS_EXCLUDEDVALUES","",
"", "elayerType", "LAYER_TYPE", "",
NULL
};
const char ** GetHFAAuxMetaDataList()
{
return apszAuxMetadataItems;
}
/************************************************************************/
/* HFAGetDictionary() */
/************************************************************************/
static char * HFAGetDictionary( HFAHandle hHFA )
{
int nDictMax = 100;
char *pszDictionary = (char *) CPLMalloc(nDictMax);
int nDictSize = 0;
VSIFSeekL( hHFA->fp, hHFA->nDictionaryPos, SEEK_SET );
while( TRUE )
{
if( nDictSize >= nDictMax-1 )
{
nDictMax = nDictSize * 2 + 100;
pszDictionary = (char *) CPLRealloc(pszDictionary, nDictMax );
}
if( VSIFReadL( pszDictionary + nDictSize, 1, 1, hHFA->fp ) < 1
|| pszDictionary[nDictSize] == '\0'
|| (nDictSize > 2 && pszDictionary[nDictSize-2] == ','
&& pszDictionary[nDictSize-1] == '.') )
break;
nDictSize++;
}
pszDictionary[nDictSize] = '\0';
return( pszDictionary );
}
/************************************************************************/
/* HFAOpen() */
/************************************************************************/
HFAHandle HFAOpen( const char * pszFilename, const char * pszAccess )
{
VSILFILE *fp;
char szHeader[16];
HFAInfo_t *psInfo;
GUInt32 nHeaderPos;
/* -------------------------------------------------------------------- */
/* Open the file. */
/* -------------------------------------------------------------------- */
if( EQUAL(pszAccess,"r") || EQUAL(pszAccess,"rb" ) )
fp = VSIFOpenL( pszFilename, "rb" );
else
fp = VSIFOpenL( pszFilename, "r+b" );
/* should this be changed to use some sort of CPLFOpen() which will
set the error? */
if( fp == NULL )
{
CPLError( CE_Failure, CPLE_OpenFailed,
"File open of %s failed.",
pszFilename );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Read and verify the header. */
/* -------------------------------------------------------------------- */
if( VSIFReadL( szHeader, 16, 1, fp ) < 1 )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Attempt to read 16 byte header failed for\n%s.",
pszFilename );
return NULL;
}
if( !EQUALN(szHeader,"EHFA_HEADER_TAG",15) )
{
CPLError( CE_Failure, CPLE_AppDefined,
"File %s is not an Imagine HFA file ... header wrong.",
pszFilename );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Create the HFAInfo_t */
/* -------------------------------------------------------------------- */
psInfo = (HFAInfo_t *) CPLCalloc(sizeof(HFAInfo_t),1);
psInfo->pszFilename = CPLStrdup(CPLGetFilename(pszFilename));
psInfo->pszPath = CPLStrdup(CPLGetPath(pszFilename));
psInfo->fp = fp;
if( EQUAL(pszAccess,"r") || EQUAL(pszAccess,"rb" ) )
psInfo->eAccess = HFA_ReadOnly;
else
psInfo->eAccess = HFA_Update;
psInfo->bTreeDirty = FALSE;
/* -------------------------------------------------------------------- */
/* Where is the header? */
/* -------------------------------------------------------------------- */
VSIFReadL( &nHeaderPos, sizeof(GInt32), 1, fp );
HFAStandard( 4, &nHeaderPos );
/* -------------------------------------------------------------------- */
/* Read the header. */
/* -------------------------------------------------------------------- */
VSIFSeekL( fp, nHeaderPos, SEEK_SET );
VSIFReadL( &(psInfo->nVersion), sizeof(GInt32), 1, fp );
HFAStandard( 4, &(psInfo->nVersion) );
VSIFReadL( szHeader, 4, 1, fp ); /* skip freeList */
VSIFReadL( &(psInfo->nRootPos), sizeof(GInt32), 1, fp );
HFAStandard( 4, &(psInfo->nRootPos) );
VSIFReadL( &(psInfo->nEntryHeaderLength), sizeof(GInt16), 1, fp );
HFAStandard( 2, &(psInfo->nEntryHeaderLength) );
VSIFReadL( &(psInfo->nDictionaryPos), sizeof(GInt32), 1, fp );
HFAStandard( 4, &(psInfo->nDictionaryPos) );
/* -------------------------------------------------------------------- */
/* Collect file size. */
/* -------------------------------------------------------------------- */
VSIFSeekL( fp, 0, SEEK_END );
psInfo->nEndOfFile = (GUInt32) VSIFTellL( fp );
/* -------------------------------------------------------------------- */
/* Instantiate the root entry. */
/* -------------------------------------------------------------------- */
psInfo->poRoot = new HFAEntry( psInfo, psInfo->nRootPos, NULL, NULL );
/* -------------------------------------------------------------------- */
/* Read the dictionary */
/* -------------------------------------------------------------------- */
psInfo->pszDictionary = HFAGetDictionary( psInfo );
psInfo->poDictionary = new HFADictionary( psInfo->pszDictionary );
/* -------------------------------------------------------------------- */
/* Collect band definitions. */
/* -------------------------------------------------------------------- */
HFAParseBandInfo( psInfo );
return psInfo;
}
/************************************************************************/
/* HFACreateDependent() */
/* */
/* Create a .rrd file for the named file if it does not exist, */
/* or return the existing dependent if it already exists. */
/************************************************************************/
HFAInfo_t *HFACreateDependent( HFAInfo_t *psBase )
{
if( psBase->psDependent != NULL )
return psBase->psDependent;
/* -------------------------------------------------------------------- */
/* Create desired RRD filename. */
/* -------------------------------------------------------------------- */
CPLString oBasename = CPLGetBasename( psBase->pszFilename );
CPLString oRRDFilename =
CPLFormFilename( psBase->pszPath, oBasename, "rrd" );
/* -------------------------------------------------------------------- */
/* Does this file already exist? If so, re-use it. */
/* -------------------------------------------------------------------- */
VSILFILE *fp = VSIFOpenL( oRRDFilename, "rb" );
if( fp != NULL )
{
VSIFCloseL( fp );
psBase->psDependent = HFAOpen( oRRDFilename, "rb" );
}
/* -------------------------------------------------------------------- */
/* Otherwise create it now. */
/* -------------------------------------------------------------------- */
HFAInfo_t *psDep;
psDep = psBase->psDependent = HFACreateLL( oRRDFilename );
/* -------------------------------------------------------------------- */
/* Add the DependentFile node with the pointer back to the */
/* parent. When working from an .aux file we really want the */
/* .rrd to point back to the original file, not the .aux file. */
/* -------------------------------------------------------------------- */
HFAEntry *poEntry = psBase->poRoot->GetNamedChild("DependentFile");
const char *pszDependentFile = NULL;
if( poEntry != NULL )
pszDependentFile = poEntry->GetStringField( "dependent.string" );
if( pszDependentFile == NULL )
pszDependentFile = psBase->pszFilename;
HFAEntry *poDF = new HFAEntry( psDep, "DependentFile",
"Eimg_DependentFile", psDep->poRoot );
poDF->MakeData( strlen(pszDependentFile) + 50 );
poDF->SetPosition();
poDF->SetStringField( "dependent.string", pszDependentFile );
return psDep;
}
/************************************************************************/
/* HFAGetDependent() */
/************************************************************************/
HFAInfo_t *HFAGetDependent( HFAInfo_t *psBase, const char *pszFilename )
{
if( EQUAL(pszFilename,psBase->pszFilename) )
return psBase;
if( psBase->psDependent != NULL )
{
if( EQUAL(pszFilename,psBase->psDependent->pszFilename) )
return psBase->psDependent;
else
return NULL;
}
/* -------------------------------------------------------------------- */
/* Try to open the dependent file. */
/* -------------------------------------------------------------------- */
char *pszDependent;
VSILFILE *fp;
const char* pszMode = psBase->eAccess == HFA_Update ? "r+b" : "rb";
pszDependent = CPLStrdup(
CPLFormFilename( psBase->pszPath, pszFilename, NULL ) );
fp = VSIFOpenL( pszDependent, pszMode );
if( fp != NULL )
{
VSIFCloseL( fp );
psBase->psDependent = HFAOpen( pszDependent, pszMode );
}
CPLFree( pszDependent );
return psBase->psDependent;
}
/************************************************************************/
/* HFAParseBandInfo() */
/* */
/* This is used by HFAOpen() and HFACreate() to initialize the */
/* band structures. */
/************************************************************************/
CPLErr HFAParseBandInfo( HFAInfo_t *psInfo )
{
HFAEntry *poNode;
/* -------------------------------------------------------------------- */
/* Find the first band node. */
/* -------------------------------------------------------------------- */
psInfo->nBands = 0;
poNode = psInfo->poRoot->GetChild();
while( poNode != NULL )
{
if( EQUAL(poNode->GetType(),"Eimg_Layer")
&& poNode->GetIntField("width") > 0
&& poNode->GetIntField("height") > 0 )
{
if( psInfo->nBands == 0 )
{
psInfo->nXSize = poNode->GetIntField("width");
psInfo->nYSize = poNode->GetIntField("height");
}
else if( poNode->GetIntField("width") != psInfo->nXSize
|| poNode->GetIntField("height") != psInfo->nYSize )
{
return CE_Failure;
}
psInfo->papoBand = (HFABand **)
CPLRealloc(psInfo->papoBand,
sizeof(HFABand *) * (psInfo->nBands+1));
psInfo->papoBand[psInfo->nBands] = new HFABand( psInfo, poNode );
if (psInfo->papoBand[psInfo->nBands]->nWidth == 0)
{
delete psInfo->papoBand[psInfo->nBands];
return CE_Failure;
}
psInfo->nBands++;
}
poNode = poNode->GetNext();
}
return CE_None;
}
/************************************************************************/
/* HFAClose() */
/************************************************************************/
void HFAClose( HFAHandle hHFA )
{
int i;
if( hHFA->eAccess == HFA_Update && (hHFA->bTreeDirty || hHFA->poDictionary->bDictionaryTextDirty) )
HFAFlush( hHFA );
if( hHFA->psDependent != NULL )
HFAClose( hHFA->psDependent );
delete hHFA->poRoot;
VSIFCloseL( hHFA->fp );
if( hHFA->poDictionary != NULL )
delete hHFA->poDictionary;
CPLFree( hHFA->pszDictionary );
CPLFree( hHFA->pszFilename );
CPLFree( hHFA->pszIGEFilename );
CPLFree( hHFA->pszPath );
for( i = 0; i < hHFA->nBands; i++ )
{
delete hHFA->papoBand[i];
}
CPLFree( hHFA->papoBand );
if( hHFA->pProParameters != NULL )
{
Eprj_ProParameters *psProParms = (Eprj_ProParameters *)
hHFA->pProParameters;
CPLFree( psProParms->proExeName );
CPLFree( psProParms->proName );
CPLFree( psProParms->proSpheroid.sphereName );
CPLFree( psProParms );
}
if( hHFA->pDatum != NULL )
{
CPLFree( ((Eprj_Datum *) hHFA->pDatum)->datumname );
CPLFree( ((Eprj_Datum *) hHFA->pDatum)->gridname );
CPLFree( hHFA->pDatum );
}
if( hHFA->pMapInfo != NULL )
{
CPLFree( ((Eprj_MapInfo *) hHFA->pMapInfo)->proName );
CPLFree( ((Eprj_MapInfo *) hHFA->pMapInfo)->units );
CPLFree( hHFA->pMapInfo );
}
CPLFree( hHFA );
}
/************************************************************************/
/* HFARemove() */
/* Used from HFADelete() function. */
/************************************************************************/
CPLErr HFARemove( const char *pszFilename )
{
VSIStatBufL sStat;
if( VSIStatL( pszFilename, &sStat ) == 0 && VSI_ISREG( sStat.st_mode ) )
{
if( VSIUnlink( pszFilename ) == 0 )
return CE_None;
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"Attempt to unlink %s failed.\n", pszFilename );
return CE_Failure;
}
}
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"Unable to delete %s, not a file.\n", pszFilename );
return CE_Failure;
}
}
/************************************************************************/
/* HFADelete() */
/************************************************************************/
CPLErr HFADelete( const char *pszFilename )
{
HFAInfo_t *psInfo = HFAOpen( pszFilename, "rb" );
HFAEntry *poDMS = NULL;
HFAEntry *poLayer = NULL;
HFAEntry *poNode = NULL;
if( psInfo != NULL )
{
poNode = psInfo->poRoot->GetChild();
while( ( poNode != NULL ) && ( poLayer == NULL ) )
{
if( EQUAL(poNode->GetType(),"Eimg_Layer") )
{
poLayer = poNode;
}
poNode = poNode->GetNext();
}
if( poLayer != NULL )
poDMS = poLayer->GetNamedChild( "ExternalRasterDMS" );
if ( poDMS )
{
const char *pszRawFilename =
poDMS->GetStringField( "fileName.string" );
if( pszRawFilename != NULL )
HFARemove( CPLFormFilename( psInfo->pszPath,
pszRawFilename, NULL ) );
}
HFAClose( psInfo );
}
return HFARemove( pszFilename );
}
/************************************************************************/
/* HFAGetRasterInfo() */
/************************************************************************/
CPLErr HFAGetRasterInfo( HFAHandle hHFA, int * pnXSize, int * pnYSize,
int * pnBands )
{
if( pnXSize != NULL )
*pnXSize = hHFA->nXSize;
if( pnYSize != NULL )
*pnYSize = hHFA->nYSize;
if( pnBands != NULL )
*pnBands = hHFA->nBands;
return CE_None;
}
/************************************************************************/
/* HFAGetBandInfo() */
/************************************************************************/
CPLErr HFAGetBandInfo( HFAHandle hHFA, int nBand, int * pnDataType,
int * pnBlockXSize, int * pnBlockYSize,
int *pnCompressionType )
{
if( nBand < 0 || nBand > hHFA->nBands )
{
CPLAssert( FALSE );
return CE_Failure;
}
HFABand *poBand = hHFA->papoBand[nBand-1];
if( pnDataType != NULL )
*pnDataType = poBand->nDataType;
if( pnBlockXSize != NULL )
*pnBlockXSize = poBand->nBlockXSize;
if( pnBlockYSize != NULL )
*pnBlockYSize = poBand->nBlockYSize;
/* -------------------------------------------------------------------- */
/* Get compression code from RasterDMS. */
/* -------------------------------------------------------------------- */
if( pnCompressionType != NULL )
{
HFAEntry *poDMS;
*pnCompressionType = 0;
poDMS = poBand->poNode->GetNamedChild( "RasterDMS" );
if( poDMS != NULL )
*pnCompressionType = poDMS->GetIntField( "compressionType" );
}
return( CE_None );
}
/************************************************************************/
/* HFAGetBandNoData() */
/* */
/* returns TRUE if value is set, otherwise FALSE. */
/************************************************************************/
int HFAGetBandNoData( HFAHandle hHFA, int nBand, double *pdfNoData )
{
if( nBand < 0 || nBand > hHFA->nBands )
{
CPLAssert( FALSE );
return CE_Failure;
}
HFABand *poBand = hHFA->papoBand[nBand-1];
if( !poBand->bNoDataSet && poBand->nOverviews > 0 )
{
poBand = poBand->papoOverviews[0];
if( poBand == NULL )
return FALSE;
}
*pdfNoData = poBand->dfNoData;
return poBand->bNoDataSet;
}
/************************************************************************/
/* HFASetBandNoData() */
/* */
/* attempts to set a no-data value on the given band */
/************************************************************************/
CPLErr HFASetBandNoData( HFAHandle hHFA, int nBand, double dfValue )
{
if ( nBand < 0 || nBand > hHFA->nBands )
{
CPLAssert( FALSE );
return CE_Failure;
}
HFABand *poBand = hHFA->papoBand[nBand - 1];
return poBand->SetNoDataValue( dfValue );
}
/************************************************************************/
/* HFAGetOverviewCount() */
/************************************************************************/
int HFAGetOverviewCount( HFAHandle hHFA, int nBand )
{
HFABand *poBand;
if( nBand < 0 || nBand > hHFA->nBands )
{
CPLAssert( FALSE );
return CE_Failure;
}
poBand = hHFA->papoBand[nBand-1];
poBand->LoadOverviews();
return poBand->nOverviews;
}
/************************************************************************/
/* HFAGetOverviewInfo() */
/************************************************************************/
CPLErr HFAGetOverviewInfo( HFAHandle hHFA, int nBand, int iOverview,
int * pnXSize, int * pnYSize,
int * pnBlockXSize, int * pnBlockYSize,
int * pnHFADataType )
{
HFABand *poBand;
if( nBand < 0 || nBand > hHFA->nBands )
{
CPLAssert( FALSE );
return CE_Failure;
}
poBand = hHFA->papoBand[nBand-1];
poBand->LoadOverviews();
if( iOverview < 0 || iOverview >= poBand->nOverviews )
{
CPLAssert( FALSE );
return CE_Failure;
}
poBand = poBand->papoOverviews[iOverview];
if( poBand == NULL )
{
return CE_Failure;
}
if( pnXSize != NULL )
*pnXSize = poBand->nWidth;
if( pnYSize != NULL )
*pnYSize = poBand->nHeight;
if( pnBlockXSize != NULL )
*pnBlockXSize = poBand->nBlockXSize;
if( pnBlockYSize != NULL )
*pnBlockYSize = poBand->nBlockYSize;
if( pnHFADataType != NULL )
*pnHFADataType = poBand->nDataType;
return( CE_None );
}
/************************************************************************/
/* HFAGetRasterBlock() */
/************************************************************************/
CPLErr HFAGetRasterBlock( HFAHandle hHFA, int nBand,
int nXBlock, int nYBlock, void * pData )
{
return HFAGetRasterBlockEx(hHFA, nBand, nXBlock, nYBlock, pData, -1);
}
/************************************************************************/
/* HFAGetRasterBlockEx() */
/************************************************************************/
CPLErr HFAGetRasterBlockEx( HFAHandle hHFA, int nBand,
int nXBlock, int nYBlock, void * pData, int nDataSize )
{
if( nBand < 1 || nBand > hHFA->nBands )
return CE_Failure;
return( hHFA->papoBand[nBand-1]->GetRasterBlock(nXBlock,nYBlock,pData,nDataSize) );
}
/************************************************************************/
/* HFAGetOverviewRasterBlock() */
/************************************************************************/
CPLErr HFAGetOverviewRasterBlock( HFAHandle hHFA, int nBand, int iOverview,
int nXBlock, int nYBlock, void * pData )
{
return HFAGetOverviewRasterBlockEx(hHFA, nBand, iOverview, nXBlock, nYBlock, pData, -1);
}
/************************************************************************/
/* HFAGetOverviewRasterBlockEx() */
/************************************************************************/
CPLErr HFAGetOverviewRasterBlockEx( HFAHandle hHFA, int nBand, int iOverview,
int nXBlock, int nYBlock, void * pData, int nDataSize )
{
if( nBand < 1 || nBand > hHFA->nBands )
return CE_Failure;
if( iOverview < 0 || iOverview >= hHFA->papoBand[nBand-1]->nOverviews )
return CE_Failure;
return( hHFA->papoBand[nBand-1]->papoOverviews[iOverview]->
GetRasterBlock(nXBlock,nYBlock,pData, nDataSize) );
}
/************************************************************************/
/* HFASetRasterBlock() */
/************************************************************************/
CPLErr HFASetRasterBlock( HFAHandle hHFA, int nBand,
int nXBlock, int nYBlock, void * pData )
{
if( nBand < 1 || nBand > hHFA->nBands )
return CE_Failure;
return( hHFA->papoBand[nBand-1]->SetRasterBlock(nXBlock,nYBlock,pData) );
}
/************************************************************************/
/* HFASetRasterBlock() */
/************************************************************************/
CPLErr HFASetOverviewRasterBlock( HFAHandle hHFA, int nBand, int iOverview,
int nXBlock, int nYBlock, void * pData )
{
if( nBand < 1 || nBand > hHFA->nBands )
return CE_Failure;
if( iOverview < 0 || iOverview >= hHFA->papoBand[nBand-1]->nOverviews )
return CE_Failure;
return( hHFA->papoBand[nBand-1]->papoOverviews[iOverview]->
SetRasterBlock(nXBlock,nYBlock,pData) );
}
/************************************************************************/
/* HFAGetBandName() */
/************************************************************************/
const char * HFAGetBandName( HFAHandle hHFA, int nBand )
{
if( nBand < 1 || nBand > hHFA->nBands )
return "";
return( hHFA->papoBand[nBand-1]->GetBandName() );
}
/************************************************************************/
/* HFASetBandName() */
/************************************************************************/
void HFASetBandName( HFAHandle hHFA, int nBand, const char *pszName )
{
if( nBand < 1 || nBand > hHFA->nBands )
return;
hHFA->papoBand[nBand-1]->SetBandName( pszName );
}
/************************************************************************/
/* HFAGetDataTypeBits() */
/************************************************************************/
int HFAGetDataTypeBits( int nDataType )
{
switch( nDataType )
{
case EPT_u1:
return 1;
case EPT_u2:
return 2;
case EPT_u4:
return 4;
case EPT_u8:
case EPT_s8:
return 8;
case EPT_u16:
case EPT_s16:
return 16;
case EPT_u32:
case EPT_s32:
case EPT_f32:
return 32;
case EPT_f64:
case EPT_c64:
return 64;
case EPT_c128:
return 128;
}
return 0;
}
/************************************************************************/
/* HFAGetDataTypeName() */
/************************************************************************/
const char *HFAGetDataTypeName( int nDataType )
{
switch( nDataType )
{
case EPT_u1:
return "u1";
case EPT_u2:
return "u2";
case EPT_u4:
return "u4";
case EPT_u8:
return "u8";
case EPT_s8:
return "s8";
case EPT_u16:
return "u16";
case EPT_s16:
return "s16";
case EPT_u32:
return "u32";
case EPT_s32:
return "s32";
case EPT_f32:
return "f32";
case EPT_f64:
return "f64";
case EPT_c64:
return "c64";
case EPT_c128:
return "c128";
default:
return "unknown";
}
}
/************************************************************************/
/* HFAGetMapInfo() */
/************************************************************************/
const Eprj_MapInfo *HFAGetMapInfo( HFAHandle hHFA )
{
HFAEntry *poMIEntry;
Eprj_MapInfo *psMapInfo;
if( hHFA->nBands < 1 )
return NULL;
/* -------------------------------------------------------------------- */
/* Do we already have it? */
/* -------------------------------------------------------------------- */
if( hHFA->pMapInfo != NULL )
return( (Eprj_MapInfo *) hHFA->pMapInfo );
/* -------------------------------------------------------------------- */
/* Get the HFA node. If we don't find it under the usual name */
/* we search for any node of the right type (#3338). */
/* -------------------------------------------------------------------- */
poMIEntry = hHFA->papoBand[0]->poNode->GetNamedChild( "Map_Info" );
if( poMIEntry == NULL )
{
HFAEntry *poChild;
for( poChild = hHFA->papoBand[0]->poNode->GetChild();
poChild != NULL && poMIEntry == NULL;
poChild = poChild->GetNext() )
{
if( EQUAL(poChild->GetType(),"Eprj_MapInfo") )
poMIEntry = poChild;
}
}
if( poMIEntry == NULL )
{
return NULL;
}
/* -------------------------------------------------------------------- */
/* Allocate the structure. */
/* -------------------------------------------------------------------- */
psMapInfo = (Eprj_MapInfo *) CPLCalloc(sizeof(Eprj_MapInfo),1);
/* -------------------------------------------------------------------- */
/* Fetch the fields. */
/* -------------------------------------------------------------------- */
CPLErr eErr;
psMapInfo->proName = CPLStrdup(poMIEntry->GetStringField("proName"));
psMapInfo->upperLeftCenter.x =
poMIEntry->GetDoubleField("upperLeftCenter.x");
psMapInfo->upperLeftCenter.y =
poMIEntry->GetDoubleField("upperLeftCenter.y");
psMapInfo->lowerRightCenter.x =
poMIEntry->GetDoubleField("lowerRightCenter.x");
psMapInfo->lowerRightCenter.y =
poMIEntry->GetDoubleField("lowerRightCenter.y");
psMapInfo->pixelSize.width =
poMIEntry->GetDoubleField("pixelSize.width",&eErr);
psMapInfo->pixelSize.height =
poMIEntry->GetDoubleField("pixelSize.height",&eErr);
// The following is basically a hack to get files with
// non-standard MapInfo's that misname the pixelSize fields. (#3338)
if( eErr != CE_None )
{
psMapInfo->pixelSize.width =
poMIEntry->GetDoubleField("pixelSize.x");
psMapInfo->pixelSize.height =
poMIEntry->GetDoubleField("pixelSize.y");
}
psMapInfo->units = CPLStrdup(poMIEntry->GetStringField("units"));
hHFA->pMapInfo = (void *) psMapInfo;
return psMapInfo;
}
/************************************************************************/
/* HFAInvGeoTransform() */
/************************************************************************/
static int HFAInvGeoTransform( double *gt_in, double *gt_out )
{
double det, inv_det;
/* we assume a 3rd row that is [1 0 0] */
/* Compute determinate */
det = gt_in[1] * gt_in[5] - gt_in[2] * gt_in[4];
if( fabs(det) < 0.000000000000001 )
return 0;
inv_det = 1.0 / det;
/* compute adjoint, and devide by determinate */
gt_out[1] = gt_in[5] * inv_det;
gt_out[4] = -gt_in[4] * inv_det;
gt_out[2] = -gt_in[2] * inv_det;
gt_out[5] = gt_in[1] * inv_det;
gt_out[0] = ( gt_in[2] * gt_in[3] - gt_in[0] * gt_in[5]) * inv_det;
gt_out[3] = (-gt_in[1] * gt_in[3] + gt_in[0] * gt_in[4]) * inv_det;
return 1;
}
/************************************************************************/
/* HFAGetGeoTransform() */
/************************************************************************/
int HFAGetGeoTransform( HFAHandle hHFA, double *padfGeoTransform )
{
const Eprj_MapInfo *psMapInfo = HFAGetMapInfo( hHFA );
padfGeoTransform[0] = 0.0;
padfGeoTransform[1] = 1.0;
padfGeoTransform[2] = 0.0;
padfGeoTransform[3] = 0.0;
padfGeoTransform[4] = 0.0;
padfGeoTransform[5] = 1.0;
/* -------------------------------------------------------------------- */
/* Simple (north up) MapInfo approach. */
/* -------------------------------------------------------------------- */
if( psMapInfo != NULL )
{
padfGeoTransform[0] = psMapInfo->upperLeftCenter.x
- psMapInfo->pixelSize.width*0.5;
padfGeoTransform[1] = psMapInfo->pixelSize.width;
if(padfGeoTransform[1] == 0.0)
padfGeoTransform[1] = 1.0;
padfGeoTransform[2] = 0.0;
if( psMapInfo->upperLeftCenter.y >= psMapInfo->lowerRightCenter.y )
padfGeoTransform[5] = - psMapInfo->pixelSize.height;
else
padfGeoTransform[5] = psMapInfo->pixelSize.height;
if(padfGeoTransform[5] == 0.0)
padfGeoTransform[5] = 1.0;
padfGeoTransform[3] = psMapInfo->upperLeftCenter.y
- padfGeoTransform[5]*0.5;
padfGeoTransform[4] = 0.0;
// special logic to fixup odd angular units.
if( EQUAL(psMapInfo->units,"ds") )
{
padfGeoTransform[0] /= 3600.0;
padfGeoTransform[1] /= 3600.0;
padfGeoTransform[2] /= 3600.0;
padfGeoTransform[3] /= 3600.0;
padfGeoTransform[4] /= 3600.0;
padfGeoTransform[5] /= 3600.0;
}
return TRUE;
}
/* -------------------------------------------------------------------- */
/* Try for a MapToPixelXForm affine polynomial supporting */
/* rotated and sheared affine transformations. */
/* -------------------------------------------------------------------- */
if( hHFA->nBands == 0 )
return FALSE;
HFAEntry *poXForm0 =
hHFA->papoBand[0]->poNode->GetNamedChild( "MapToPixelXForm.XForm0" );
if( poXForm0 == NULL )
return FALSE;
if( poXForm0->GetIntField( "order" ) != 1
|| poXForm0->GetIntField( "numdimtransform" ) != 2
|| poXForm0->GetIntField( "numdimpolynomial" ) != 2
|| poXForm0->GetIntField( "termcount" ) != 3 )
return FALSE;
// Verify that there aren't any further xform steps.
if( hHFA->papoBand[0]->poNode->GetNamedChild( "MapToPixelXForm.XForm1" )
!= NULL )
return FALSE;
// we should check that the exponent list is 0 0 1 0 0 1 but
// we don't because we are lazy
// fetch geotransform values.
double adfXForm[6];
adfXForm[0] = poXForm0->GetDoubleField( "polycoefvector[0]" );
adfXForm[1] = poXForm0->GetDoubleField( "polycoefmtx[0]" );
adfXForm[4] = poXForm0->GetDoubleField( "polycoefmtx[1]" );
adfXForm[3] = poXForm0->GetDoubleField( "polycoefvector[1]" );
adfXForm[2] = poXForm0->GetDoubleField( "polycoefmtx[2]" );
adfXForm[5] = poXForm0->GetDoubleField( "polycoefmtx[3]" );
// invert
HFAInvGeoTransform( adfXForm, padfGeoTransform );
// Adjust origin from center of top left pixel to top left corner
// of top left pixel.
padfGeoTransform[0] -= padfGeoTransform[1] * 0.5;
padfGeoTransform[0] -= padfGeoTransform[2] * 0.5;
padfGeoTransform[3] -= padfGeoTransform[4] * 0.5;
padfGeoTransform[3] -= padfGeoTransform[5] * 0.5;
return TRUE;
}
/************************************************************************/
/* HFASetMapInfo() */
/************************************************************************/
CPLErr HFASetMapInfo( HFAHandle hHFA, const Eprj_MapInfo *poMapInfo )
{
/* -------------------------------------------------------------------- */
/* Loop over bands, setting information on each one. */
/* -------------------------------------------------------------------- */
for( int iBand = 0; iBand < hHFA->nBands; iBand++ )
{
HFAEntry *poMIEntry;
/* -------------------------------------------------------------------- */
/* Create a new Map_Info if there isn't one present already. */
/* -------------------------------------------------------------------- */
poMIEntry = hHFA->papoBand[iBand]->poNode->GetNamedChild( "Map_Info" );
if( poMIEntry == NULL )
{
poMIEntry = new HFAEntry( hHFA, "Map_Info", "Eprj_MapInfo",
hHFA->papoBand[iBand]->poNode );
}
poMIEntry->MarkDirty();
/* -------------------------------------------------------------------- */
/* Ensure we have enough space for all the data. */
/* -------------------------------------------------------------------- */
int nSize;
GByte *pabyData;
nSize = 48 + 40
+ strlen(poMapInfo->proName) + 1
+ strlen(poMapInfo->units) + 1;
pabyData = poMIEntry->MakeData( nSize );
memset( pabyData, 0, nSize );
poMIEntry->SetPosition();
/* -------------------------------------------------------------------- */
/* Write the various fields. */
/* -------------------------------------------------------------------- */
poMIEntry->SetStringField( "proName", poMapInfo->proName );
poMIEntry->SetDoubleField( "upperLeftCenter.x",
poMapInfo->upperLeftCenter.x );
poMIEntry->SetDoubleField( "upperLeftCenter.y",
poMapInfo->upperLeftCenter.y );
poMIEntry->SetDoubleField( "lowerRightCenter.x",
poMapInfo->lowerRightCenter.x );
poMIEntry->SetDoubleField( "lowerRightCenter.y",
poMapInfo->lowerRightCenter.y );
poMIEntry->SetDoubleField( "pixelSize.width",
poMapInfo->pixelSize.width );
poMIEntry->SetDoubleField( "pixelSize.height",
poMapInfo->pixelSize.height );
poMIEntry->SetStringField( "units", poMapInfo->units );
}
return CE_None;
}
/************************************************************************/
/* HFAGetPEString() */
/* */
/* Some files have a ProjectionX node contining the ESRI style */
/* PE_STRING. This function allows fetching from it. */
/************************************************************************/
char *HFAGetPEString( HFAHandle hHFA )
{
if( hHFA->nBands == 0 )
return NULL;
/* -------------------------------------------------------------------- */
/* Get the HFA node. */
/* -------------------------------------------------------------------- */
HFAEntry *poProX;
poProX = hHFA->papoBand[0]->poNode->GetNamedChild( "ProjectionX" );
if( poProX == NULL )
return NULL;
const char *pszType = poProX->GetStringField( "projection.type.string" );
if( pszType == NULL || !EQUAL(pszType,"PE_COORDSYS") )
return NULL;
/* -------------------------------------------------------------------- */
/* Use a gross hack to scan ahead to the actual projection */
/* string. We do it this way because we don't have general */
/* handling for MIFObjects. */
/* -------------------------------------------------------------------- */
GByte *pabyData = poProX->GetData();
int nDataSize = poProX->GetDataSize();
while( nDataSize > 10
&& !EQUALN((const char *) pabyData,"PE_COORDSYS,.",13) ) {
pabyData++;
nDataSize--;
}
if( nDataSize < 31 )
return NULL;
/* -------------------------------------------------------------------- */
/* Skip ahead to the actual string. */
/* -------------------------------------------------------------------- */
pabyData += 30;
nDataSize -= 30;
return CPLStrdup( (const char *) pabyData );
}
/************************************************************************/
/* HFASetPEString() */
/************************************************************************/
CPLErr HFASetPEString( HFAHandle hHFA, const char *pszPEString )
{
/* -------------------------------------------------------------------- */
/* Loop over bands, setting information on each one. */
/* -------------------------------------------------------------------- */
int iBand;
for( iBand = 0; iBand < hHFA->nBands; iBand++ )
{
HFAEntry *poProX;
/* -------------------------------------------------------------------- */
/* Verify we don't already have the node, since update-in-place */
/* is likely to be more complicated. */
/* -------------------------------------------------------------------- */
poProX = hHFA->papoBand[iBand]->poNode->GetNamedChild( "ProjectionX" );
/* -------------------------------------------------------------------- */
/* If we are setting an empty string then a missing entry is */
/* equivelent. */
/* -------------------------------------------------------------------- */
if( strlen(pszPEString) == 0 && poProX == NULL )
continue;
/* -------------------------------------------------------------------- */
/* Create the node. */
/* -------------------------------------------------------------------- */
if( poProX == NULL )
{
poProX = new HFAEntry( hHFA, "ProjectionX","Eprj_MapProjection842",
hHFA->papoBand[iBand]->poNode );
if( poProX == NULL || poProX->GetTypeObject() == NULL )
return CE_Failure;
}
/* -------------------------------------------------------------------- */
/* Prepare the data area with some extra space just in case. */
/* -------------------------------------------------------------------- */
GByte *pabyData = poProX->MakeData( 700 + strlen(pszPEString) );
if( !pabyData )
return CE_Failure;
memset( pabyData, 0, 250+strlen(pszPEString) );
poProX->SetPosition();
poProX->SetStringField( "projection.type.string", "PE_COORDSYS" );
poProX->SetStringField( "projection.MIFDictionary.string",
"{0:pcstring,}Emif_String,{1:x{0:pcstring,}Emif_String,coordSys,}PE_COORDSYS,." );
/* -------------------------------------------------------------------- */
/* Use a gross hack to scan ahead to the actual projection */
/* string. We do it this way because we don't have general */
/* handling for MIFObjects. */
/* -------------------------------------------------------------------- */
pabyData = poProX->GetData();
int nDataSize = poProX->GetDataSize();
GUInt32 iOffset = poProX->GetDataPos();
GUInt32 nSize;
while( nDataSize > 10
&& !EQUALN((const char *) pabyData,"PE_COORDSYS,.",13) ) {
pabyData++;
nDataSize--;
iOffset++;
}
CPLAssert( nDataSize > (int) strlen(pszPEString) + 10 );
pabyData += 14;
iOffset += 14;
/* -------------------------------------------------------------------- */
/* Set the size and offset of the mifobject. */
/* -------------------------------------------------------------------- */
iOffset += 8;
nSize = strlen(pszPEString) + 9;
HFAStandard( 4, &nSize );
memcpy( pabyData, &nSize, 4 );
pabyData += 4;
HFAStandard( 4, &iOffset );
memcpy( pabyData, &iOffset, 4 );
pabyData += 4;
/* -------------------------------------------------------------------- */
/* Set the size and offset of the string value. */
/* -------------------------------------------------------------------- */
nSize = strlen(pszPEString) + 1;
HFAStandard( 4, &nSize );
memcpy( pabyData, &nSize, 4 );
pabyData += 4;
iOffset = 8;
HFAStandard( 4, &iOffset );
memcpy( pabyData, &iOffset, 4 );
pabyData += 4;
/* -------------------------------------------------------------------- */
/* Place the string itself. */
/* -------------------------------------------------------------------- */
memcpy( pabyData, pszPEString, strlen(pszPEString)+1 );
poProX->SetStringField( "title.string", "PE" );
}
return CE_None;
}
/************************************************************************/
/* HFAGetProParameters() */
/************************************************************************/
const Eprj_ProParameters *HFAGetProParameters( HFAHandle hHFA )
{
HFAEntry *poMIEntry;
Eprj_ProParameters *psProParms;
int i;
if( hHFA->nBands < 1 )
return NULL;
/* -------------------------------------------------------------------- */
/* Do we already have it? */
/* -------------------------------------------------------------------- */
if( hHFA->pProParameters != NULL )
return( (Eprj_ProParameters *) hHFA->pProParameters );
/* -------------------------------------------------------------------- */
/* Get the HFA node. */
/* -------------------------------------------------------------------- */
poMIEntry = hHFA->papoBand[0]->poNode->GetNamedChild( "Projection" );
if( poMIEntry == NULL )
return NULL;
/* -------------------------------------------------------------------- */
/* Allocate the structure. */
/* -------------------------------------------------------------------- */
psProParms = (Eprj_ProParameters *)CPLCalloc(sizeof(Eprj_ProParameters),1);
/* -------------------------------------------------------------------- */
/* Fetch the fields. */
/* -------------------------------------------------------------------- */
psProParms->proType = (Eprj_ProType) poMIEntry->GetIntField("proType");
psProParms->proNumber = poMIEntry->GetIntField("proNumber");
psProParms->proExeName =CPLStrdup(poMIEntry->GetStringField("proExeName"));
psProParms->proName = CPLStrdup(poMIEntry->GetStringField("proName"));
psProParms->proZone = poMIEntry->GetIntField("proZone");
for( i = 0; i < 15; i++ )
{
char szFieldName[40];
sprintf( szFieldName, "proParams[%d]", i );
psProParms->proParams[i] = poMIEntry->GetDoubleField(szFieldName);
}
psProParms->proSpheroid.sphereName =
CPLStrdup(poMIEntry->GetStringField("proSpheroid.sphereName"));
psProParms->proSpheroid.a = poMIEntry->GetDoubleField("proSpheroid.a");
psProParms->proSpheroid.b = poMIEntry->GetDoubleField("proSpheroid.b");
psProParms->proSpheroid.eSquared =
poMIEntry->GetDoubleField("proSpheroid.eSquared");
psProParms->proSpheroid.radius =
poMIEntry->GetDoubleField("proSpheroid.radius");
hHFA->pProParameters = (void *) psProParms;
return psProParms;
}
/************************************************************************/
/* HFASetProParameters() */
/************************************************************************/
CPLErr HFASetProParameters( HFAHandle hHFA, const Eprj_ProParameters *poPro )
{
/* -------------------------------------------------------------------- */
/* Loop over bands, setting information on each one. */
/* -------------------------------------------------------------------- */
for( int iBand = 0; iBand < hHFA->nBands; iBand++ )
{
HFAEntry *poMIEntry;
/* -------------------------------------------------------------------- */
/* Create a new Projection if there isn't one present already. */
/* -------------------------------------------------------------------- */
poMIEntry = hHFA->papoBand[iBand]->poNode->GetNamedChild("Projection");
if( poMIEntry == NULL )
{
poMIEntry = new HFAEntry( hHFA, "Projection","Eprj_ProParameters",
hHFA->papoBand[iBand]->poNode );
}
poMIEntry->MarkDirty();
/* -------------------------------------------------------------------- */
/* Ensure we have enough space for all the data. */
/* -------------------------------------------------------------------- */
int nSize;
GByte *pabyData;
nSize = 34 + 15 * 8
+ 8 + strlen(poPro->proName) + 1
+ 32 + 8 + strlen(poPro->proSpheroid.sphereName) + 1;
if( poPro->proExeName != NULL )
nSize += strlen(poPro->proExeName) + 1;
pabyData = poMIEntry->MakeData( nSize );
if(!pabyData)
return CE_Failure;
poMIEntry->SetPosition();
// Initialize the whole thing to zeros for a clean start.
memset( poMIEntry->GetData(), 0, poMIEntry->GetDataSize() );
/* -------------------------------------------------------------------- */
/* Write the various fields. */
/* -------------------------------------------------------------------- */
poMIEntry->SetIntField( "proType", poPro->proType );
poMIEntry->SetIntField( "proNumber", poPro->proNumber );
poMIEntry->SetStringField( "proExeName", poPro->proExeName );
poMIEntry->SetStringField( "proName", poPro->proName );
poMIEntry->SetIntField( "proZone", poPro->proZone );
poMIEntry->SetDoubleField( "proParams[0]", poPro->proParams[0] );
poMIEntry->SetDoubleField( "proParams[1]", poPro->proParams[1] );
poMIEntry->SetDoubleField( "proParams[2]", poPro->proParams[2] );
poMIEntry->SetDoubleField( "proParams[3]", poPro->proParams[3] );
poMIEntry->SetDoubleField( "proParams[4]", poPro->proParams[4] );
poMIEntry->SetDoubleField( "proParams[5]", poPro->proParams[5] );
poMIEntry->SetDoubleField( "proParams[6]", poPro->proParams[6] );
poMIEntry->SetDoubleField( "proParams[7]", poPro->proParams[7] );
poMIEntry->SetDoubleField( "proParams[8]", poPro->proParams[8] );
poMIEntry->SetDoubleField( "proParams[9]", poPro->proParams[9] );
poMIEntry->SetDoubleField( "proParams[10]", poPro->proParams[10] );
poMIEntry->SetDoubleField( "proParams[11]", poPro->proParams[11] );
poMIEntry->SetDoubleField( "proParams[12]", poPro->proParams[12] );
poMIEntry->SetDoubleField( "proParams[13]", poPro->proParams[13] );
poMIEntry->SetDoubleField( "proParams[14]", poPro->proParams[14] );
poMIEntry->SetStringField( "proSpheroid.sphereName",
poPro->proSpheroid.sphereName );
poMIEntry->SetDoubleField( "proSpheroid.a",
poPro->proSpheroid.a );
poMIEntry->SetDoubleField( "proSpheroid.b",
poPro->proSpheroid.b );
poMIEntry->SetDoubleField( "proSpheroid.eSquared",
poPro->proSpheroid.eSquared );
poMIEntry->SetDoubleField( "proSpheroid.radius",
poPro->proSpheroid.radius );
}
return CE_None;
}
/************************************************************************/
/* HFAGetDatum() */
/************************************************************************/
const Eprj_Datum *HFAGetDatum( HFAHandle hHFA )
{
HFAEntry *poMIEntry;
Eprj_Datum *psDatum;
int i;
if( hHFA->nBands < 1 )
return NULL;
/* -------------------------------------------------------------------- */
/* Do we already have it? */
/* -------------------------------------------------------------------- */
if( hHFA->pDatum != NULL )
return( (Eprj_Datum *) hHFA->pDatum );
/* -------------------------------------------------------------------- */
/* Get the HFA node. */
/* -------------------------------------------------------------------- */
poMIEntry = hHFA->papoBand[0]->poNode->GetNamedChild( "Projection.Datum" );
if( poMIEntry == NULL )
return NULL;
/* -------------------------------------------------------------------- */
/* Allocate the structure. */
/* -------------------------------------------------------------------- */
psDatum = (Eprj_Datum *) CPLCalloc(sizeof(Eprj_Datum),1);
/* -------------------------------------------------------------------- */
/* Fetch the fields. */
/* -------------------------------------------------------------------- */
psDatum->datumname = CPLStrdup(poMIEntry->GetStringField("datumname"));
psDatum->type = (Eprj_DatumType) poMIEntry->GetIntField("type");
for( i = 0; i < 7; i++ )
{
char szFieldName[30];
sprintf( szFieldName, "params[%d]", i );
psDatum->params[i] = poMIEntry->GetDoubleField(szFieldName);
}
psDatum->gridname = CPLStrdup(poMIEntry->GetStringField("gridname"));
hHFA->pDatum = (void *) psDatum;
return psDatum;
}
/************************************************************************/
/* HFASetDatum() */
/************************************************************************/
CPLErr HFASetDatum( HFAHandle hHFA, const Eprj_Datum *poDatum )
{
/* -------------------------------------------------------------------- */
/* Loop over bands, setting information on each one. */
/* -------------------------------------------------------------------- */
for( int iBand = 0; iBand < hHFA->nBands; iBand++ )
{
HFAEntry *poDatumEntry=NULL, *poProParms;
/* -------------------------------------------------------------------- */
/* Create a new Projection if there isn't one present already. */
/* -------------------------------------------------------------------- */
poProParms =
hHFA->papoBand[iBand]->poNode->GetNamedChild("Projection");
if( poProParms == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Can't add Eprj_Datum with no Eprj_ProjParameters." );
return CE_Failure;
}
poDatumEntry = poProParms->GetNamedChild("Datum");
if( poDatumEntry == NULL )
{
poDatumEntry = new HFAEntry( hHFA, "Datum","Eprj_Datum",
poProParms );
}
poDatumEntry->MarkDirty();
/* -------------------------------------------------------------------- */
/* Ensure we have enough space for all the data. */
/* -------------------------------------------------------------------- */
int nSize;
GByte *pabyData;
nSize = 26 + strlen(poDatum->datumname) + 1 + 7*8;
if( poDatum->gridname != NULL )
nSize += strlen(poDatum->gridname) + 1;
pabyData = poDatumEntry->MakeData( nSize );
if(!pabyData)
return CE_Failure;
poDatumEntry->SetPosition();
// Initialize the whole thing to zeros for a clean start.
memset( poDatumEntry->GetData(), 0, poDatumEntry->GetDataSize() );
/* -------------------------------------------------------------------- */
/* Write the various fields. */
/* -------------------------------------------------------------------- */
poDatumEntry->SetStringField( "datumname", poDatum->datumname );
poDatumEntry->SetIntField( "type", poDatum->type );
poDatumEntry->SetDoubleField( "params[0]", poDatum->params[0] );
poDatumEntry->SetDoubleField( "params[1]", poDatum->params[1] );
poDatumEntry->SetDoubleField( "params[2]", poDatum->params[2] );
poDatumEntry->SetDoubleField( "params[3]", poDatum->params[3] );
poDatumEntry->SetDoubleField( "params[4]", poDatum->params[4] );
poDatumEntry->SetDoubleField( "params[5]", poDatum->params[5] );
poDatumEntry->SetDoubleField( "params[6]", poDatum->params[6] );
poDatumEntry->SetStringField( "gridname", poDatum->gridname );
}
return CE_None;
}
/************************************************************************/
/* HFAGetPCT() */
/* */
/* Read the PCT from a band, if it has one. */
/************************************************************************/
CPLErr HFAGetPCT( HFAHandle hHFA, int nBand, int *pnColors,
double **ppadfRed, double **ppadfGreen,
double **ppadfBlue , double **ppadfAlpha,
double **ppadfBins )
{
if( nBand < 1 || nBand > hHFA->nBands )
return CE_Failure;
return( hHFA->papoBand[nBand-1]->GetPCT( pnColors, ppadfRed,
ppadfGreen, ppadfBlue,
ppadfAlpha, ppadfBins ) );
}
/************************************************************************/
/* HFASetPCT() */
/* */
/* Set the PCT on a band. */
/************************************************************************/
CPLErr HFASetPCT( HFAHandle hHFA, int nBand, int nColors,
double *padfRed, double *padfGreen, double *padfBlue,
double *padfAlpha )
{
if( nBand < 1 || nBand > hHFA->nBands )
return CE_Failure;
return( hHFA->papoBand[nBand-1]->SetPCT( nColors, padfRed,
padfGreen, padfBlue, padfAlpha ) );
}
/************************************************************************/
/* HFAGetDataRange() */
/************************************************************************/
CPLErr HFAGetDataRange( HFAHandle hHFA, int nBand,
double * pdfMin, double *pdfMax )
{
HFAEntry *poBinInfo;
if( nBand < 1 || nBand > hHFA->nBands )
return CE_Failure;
poBinInfo = hHFA->papoBand[nBand-1]->poNode->GetNamedChild("Statistics" );
if( poBinInfo == NULL )
return( CE_Failure );
*pdfMin = poBinInfo->GetDoubleField( "minimum" );
*pdfMax = poBinInfo->GetDoubleField( "maximum" );
if( *pdfMax > *pdfMin )
return CE_None;
else
return CE_Failure;
}
/************************************************************************/
/* HFADumpNode() */
/************************************************************************/
static void HFADumpNode( HFAEntry *poEntry, int nIndent, int bVerbose,
FILE * fp )
{
static char szSpaces[256];
int i;
for( i = 0; i < nIndent*2; i++ )
szSpaces[i] = ' ';
szSpaces[nIndent*2] = '\0';
fprintf( fp, "%s%s(%s) @ %d + %d @ %d\n", szSpaces,
poEntry->GetName(), poEntry->GetType(),
poEntry->GetFilePos(),
poEntry->GetDataSize(), poEntry->GetDataPos() );
if( bVerbose )
{
strcat( szSpaces, "+ " );
poEntry->DumpFieldValues( fp, szSpaces );
fprintf( fp, "\n" );
}
if( poEntry->GetChild() != NULL )
HFADumpNode( poEntry->GetChild(), nIndent+1, bVerbose, fp );
if( poEntry->GetNext() != NULL )
HFADumpNode( poEntry->GetNext(), nIndent, bVerbose, fp );
}
/************************************************************************/
/* HFADumpTree() */
/* */
/* Dump the tree of information in a HFA file. */
/************************************************************************/
void HFADumpTree( HFAHandle hHFA, FILE * fpOut )
{
HFADumpNode( hHFA->poRoot, 0, TRUE, fpOut );
}
/************************************************************************/
/* HFADumpDictionary() */
/* */
/* Dump the dictionary (in raw, and parsed form) to the named */
/* device. */
/************************************************************************/
void HFADumpDictionary( HFAHandle hHFA, FILE * fpOut )
{
fprintf( fpOut, "%s\n", hHFA->pszDictionary );
hHFA->poDictionary->Dump( fpOut );
}
/************************************************************************/
/* HFAStandard() */
/* */
/* Swap byte order on MSB systems. */
/************************************************************************/
#ifdef CPL_MSB
void HFAStandard( int nBytes, void * pData )
{
int i;
GByte *pabyData = (GByte *) pData;
for( i = nBytes/2-1; i >= 0; i-- )
{
GByte byTemp;
byTemp = pabyData[i];
pabyData[i] = pabyData[nBytes-i-1];
pabyData[nBytes-i-1] = byTemp;
}
}
#endif
/* ==================================================================== */
/* Default data dictionary. Emitted verbatim into the imagine */
/* file. */
/* ==================================================================== */
static const char *aszDefaultDD[] = {
"{1:lversion,1:LfreeList,1:LrootEntryPtr,1:sentryHeaderLength,1:LdictionaryPtr,}Ehfa_File,{1:Lnext,1:Lprev,1:Lparent,1:Lchild,1:Ldata,1:ldataSize,64:cname,32:ctype,1:tmodTime,}Ehfa_Entry,{16:clabel,1:LheaderPtr,}Ehfa_HeaderTag,{1:LfreeList,1:lfreeSize,}Ehfa_FreeListNode,{1:lsize,1:Lptr,}Ehfa_Data,{1:lwidth,1:lheight,1:e3:thematic,athematic,fft of real-valued data,layerType,",
"1:e13:u1,u2,u4,u8,s8,u16,s16,u32,s32,f32,f64,c64,c128,pixelType,1:lblockWidth,1:lblockHeight,}Eimg_Layer,{1:lwidth,1:lheight,1:e3:thematic,athematic,fft of real-valued data,layerType,1:e13:u1,u2,u4,u8,s8,u16,s16,u32,s32,f32,f64,c64,c128,pixelType,1:lblockWidth,1:lblockHeight,}Eimg_Layer_SubSample,{1:e2:raster,vector,type,1:LdictionaryPtr,}Ehfa_Layer,{1:LspaceUsedForRasterData,}ImgFormatInfo831,{1:sfileCode,1:Loffset,1:lsize,1:e2:false,true,logvalid,",
"1:e2:no compression,ESRI GRID compression,compressionType,}Edms_VirtualBlockInfo,{1:lmin,1:lmax,}Edms_FreeIDList,{1:lnumvirtualblocks,1:lnumobjectsperblock,1:lnextobjectnum,1:e2:no compression,RLC compression,compressionType,0:poEdms_VirtualBlockInfo,blockinfo,0:poEdms_FreeIDList,freelist,1:tmodTime,}Edms_State,{0:pcstring,}Emif_String,{1:oEmif_String,fileName,2:LlayerStackValidFlagsOffset,2:LlayerStackDataOffset,1:LlayerStackCount,1:LlayerStackIndex,}ImgExternalRaster,{1:oEmif_String,algorithm,0:poEmif_String,nameList,}Eimg_RRDNamesList,{1:oEmif_String,projection,1:oEmif_String,units,}Eimg_MapInformation,",
"{1:oEmif_String,dependent,}Eimg_DependentFile,{1:oEmif_String,ImageLayerName,}Eimg_DependentLayerName,{1:lnumrows,1:lnumcolumns,1:e13:EGDA_TYPE_U1,EGDA_TYPE_U2,EGDA_TYPE_U4,EGDA_TYPE_U8,EGDA_TYPE_S8,EGDA_TYPE_U16,EGDA_TYPE_S16,EGDA_TYPE_U32,EGDA_TYPE_S32,EGDA_TYPE_F32,EGDA_TYPE_F64,EGDA_TYPE_C64,EGDA_TYPE_C128,datatype,1:e4:EGDA_SCALAR_OBJECT,EGDA_TABLE_OBJECT,EGDA_MATRIX_OBJECT,EGDA_RASTER_OBJECT,objecttype,}Egda_BaseData,{1:*bvalueBD,}Eimg_NonInitializedValue,{1:dx,1:dy,}Eprj_Coordinate,{1:dwidth,1:dheight,}Eprj_Size,{0:pcproName,1:*oEprj_Coordinate,upperLeftCenter,",
"1:*oEprj_Coordinate,lowerRightCenter,1:*oEprj_Size,pixelSize,0:pcunits,}Eprj_MapInfo,{0:pcdatumname,1:e3:EPRJ_DATUM_PARAMETRIC,EPRJ_DATUM_GRID,EPRJ_DATUM_REGRESSION,type,0:pdparams,0:pcgridname,}Eprj_Datum,{0:pcsphereName,1:da,1:db,1:deSquared,1:dradius,}Eprj_Spheroid,{1:e2:EPRJ_INTERNAL,EPRJ_EXTERNAL,proType,1:lproNumber,0:pcproExeName,0:pcproName,1:lproZone,0:pdproParams,1:*oEprj_Spheroid,proSpheroid,}Eprj_ProParameters,{1:dminimum,1:dmaximum,1:dmean,1:dmedian,1:dmode,1:dstddev,}Esta_Statistics,{1:lnumBins,1:e4:direct,linear,logarithmic,explicit,binFunctionType,1:dminLimit,1:dmaxLimit,1:*bbinLimits,}Edsc_BinFunction,{0:poEmif_String,LayerNames,1:*bExcludedValues,1:oEmif_String,AOIname,",
"1:lSkipFactorX,1:lSkipFactorY,1:*oEdsc_BinFunction,BinFunction,}Eimg_StatisticsParameters830,{1:lnumrows,}Edsc_Table,{1:lnumRows,1:LcolumnDataPtr,1:e4:integer,real,complex,string,dataType,1:lmaxNumChars,}Edsc_Column,{1:lposition,0:pcname,1:e2:EMSC_FALSE,EMSC_TRUE,editable,1:e3:LEFT,CENTER,RIGHT,alignment,0:pcformat,1:e3:DEFAULT,APPLY,AUTO-APPLY,formulamode,0:pcformula,1:dcolumnwidth,0:pcunits,1:e5:NO_COLOR,RED,GREEN,BLUE,COLOR,colorflag,0:pcgreenname,0:pcbluename,}Eded_ColumnAttributes_1,{1:lversion,1:lnumobjects,1:e2:EAOI_UNION,EAOI_INTERSECTION,operation,}Eaoi_AreaOfInterest,",
"{1:x{0:pcstring,}Emif_String,type,1:x{0:pcstring,}Emif_String,MIFDictionary,0:pCMIFObject,}Emif_MIFObject,",
"{1:x{1:x{0:pcstring,}Emif_String,type,1:x{0:pcstring,}Emif_String,MIFDictionary,0:pCMIFObject,}Emif_MIFObject,projection,1:x{0:pcstring,}Emif_String,title,}Eprj_MapProjection842,",
"{0:poEmif_String,titleList,}Exfr_GenericXFormHeader,{1:lorder,1:lnumdimtransform,1:lnumdimpolynomial,1:ltermcount,0:plexponentlist,1:*bpolycoefmtx,1:*bpolycoefvector,}Efga_Polynomial,",
".",
NULL
};
/************************************************************************/
/* HFACreateLL() */
/* */
/* Low level creation of an Imagine file. Writes out the */
/* Ehfa_HeaderTag, dictionary and Ehfa_File. */
/************************************************************************/
HFAHandle HFACreateLL( const char * pszFilename )
{
VSILFILE *fp;
HFAInfo_t *psInfo;
/* -------------------------------------------------------------------- */
/* Create the file in the file system. */
/* -------------------------------------------------------------------- */
fp = VSIFOpenL( pszFilename, "w+b" );
if( fp == NULL )
{
CPLError( CE_Failure, CPLE_OpenFailed,
"Creation of file %s failed.",
pszFilename );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Create the HFAInfo_t */
/* -------------------------------------------------------------------- */
psInfo = (HFAInfo_t *) CPLCalloc(sizeof(HFAInfo_t),1);
psInfo->fp = fp;
psInfo->eAccess = HFA_Update;
psInfo->nXSize = 0;
psInfo->nYSize = 0;
psInfo->nBands = 0;
psInfo->papoBand = NULL;
psInfo->pMapInfo = NULL;
psInfo->pDatum = NULL;
psInfo->pProParameters = NULL;
psInfo->bTreeDirty = FALSE;
psInfo->pszFilename = CPLStrdup(CPLGetFilename(pszFilename));
psInfo->pszPath = CPLStrdup(CPLGetPath(pszFilename));
/* -------------------------------------------------------------------- */
/* Write out the Ehfa_HeaderTag */
/* -------------------------------------------------------------------- */
GInt32 nHeaderPos;
VSIFWriteL( (void *) "EHFA_HEADER_TAG", 1, 16, fp );
nHeaderPos = 20;
HFAStandard( 4, &nHeaderPos );
VSIFWriteL( &nHeaderPos, 4, 1, fp );
/* -------------------------------------------------------------------- */
/* Write the Ehfa_File node, locked in at offset 20. */
/* -------------------------------------------------------------------- */
GInt32 nVersion = 1, nFreeList = 0, nRootEntry = 0;
GInt16 nEntryHeaderLength = 128;
GInt32 nDictionaryPtr = 38;
psInfo->nEntryHeaderLength = nEntryHeaderLength;
psInfo->nRootPos = 0;
psInfo->nDictionaryPos = nDictionaryPtr;
psInfo->nVersion = nVersion;
HFAStandard( 4, &nVersion );
HFAStandard( 4, &nFreeList );
HFAStandard( 4, &nRootEntry );
HFAStandard( 2, &nEntryHeaderLength );
HFAStandard( 4, &nDictionaryPtr );
VSIFWriteL( &nVersion, 4, 1, fp );
VSIFWriteL( &nFreeList, 4, 1, fp );
VSIFWriteL( &nRootEntry, 4, 1, fp );
VSIFWriteL( &nEntryHeaderLength, 2, 1, fp );
VSIFWriteL( &nDictionaryPtr, 4, 1, fp );
/* -------------------------------------------------------------------- */
/* Write the dictionary, locked in at location 38. Note that */
/* we jump through a bunch of hoops to operate on the */
/* dictionary in chunks because some compiles (such as VC++) */
/* don't allow particularly large static strings. */
/* -------------------------------------------------------------------- */
int nDictLen = 0, iChunk;
for( iChunk = 0; aszDefaultDD[iChunk] != NULL; iChunk++ )
nDictLen += strlen(aszDefaultDD[iChunk]);
psInfo->pszDictionary = (char *) CPLMalloc(nDictLen+1);
psInfo->pszDictionary[0] = '\0';
for( iChunk = 0; aszDefaultDD[iChunk] != NULL; iChunk++ )
strcat( psInfo->pszDictionary, aszDefaultDD[iChunk] );
VSIFWriteL( (void *) psInfo->pszDictionary, 1,
strlen(psInfo->pszDictionary)+1, fp );
psInfo->poDictionary = new HFADictionary( psInfo->pszDictionary );
psInfo->nEndOfFile = (GUInt32) VSIFTellL( fp );
/* -------------------------------------------------------------------- */
/* Create a root entry. */
/* -------------------------------------------------------------------- */
psInfo->poRoot = new HFAEntry( psInfo, "root", "root", NULL );
/* -------------------------------------------------------------------- */
/* If an .ige or .rrd file exists with the same base name, */
/* delete them. (#1784) */
/* -------------------------------------------------------------------- */
CPLString osExtension = CPLGetExtension(pszFilename);
if( !EQUAL(osExtension,"rrd") && !EQUAL(osExtension,"aux") )
{
CPLString osPath = CPLGetPath( pszFilename );
CPLString osBasename = CPLGetBasename( pszFilename );
VSIStatBufL sStatBuf;
CPLString osSupFile = CPLFormCIFilename( osPath, osBasename, "rrd" );
if( VSIStatL( osSupFile, &sStatBuf ) == 0 )
VSIUnlink( osSupFile );
osSupFile = CPLFormCIFilename( osPath, osBasename, "ige" );
if( VSIStatL( osSupFile, &sStatBuf ) == 0 )
VSIUnlink( osSupFile );
}
return psInfo;
}
/************************************************************************/
/* HFAAllocateSpace() */
/* */
/* Return an area in the file to the caller to write the */
/* requested number of bytes. Currently this is always at the */
/* end of the file, but eventually we might actually keep track */
/* of free space. The HFAInfo_t's concept of file size is */
/* updated, even if nothing ever gets written to this region. */
/* */
/* Returns the offset to the requested space, or zero one */
/* failure. */
/************************************************************************/
GUInt32 HFAAllocateSpace( HFAInfo_t *psInfo, GUInt32 nBytes )
{
/* should check if this will wrap over 2GB limit */
psInfo->nEndOfFile += nBytes;
return psInfo->nEndOfFile - nBytes;
}
/************************************************************************/
/* HFAFlush() */
/* */
/* Write out any dirty tree information to disk, putting the */
/* disk file in a consistent state. */
/************************************************************************/
CPLErr HFAFlush( HFAHandle hHFA )
{
CPLErr eErr;
if( !hHFA->bTreeDirty && !hHFA->poDictionary->bDictionaryTextDirty )
return CE_None;
CPLAssert( hHFA->poRoot != NULL );
/* -------------------------------------------------------------------- */
/* Flush HFAEntry tree to disk. */
/* -------------------------------------------------------------------- */
if( hHFA->bTreeDirty )
{
eErr = hHFA->poRoot->FlushToDisk();
if( eErr != CE_None )
return eErr;
hHFA->bTreeDirty = FALSE;
}
/* -------------------------------------------------------------------- */
/* Flush Dictionary to disk. */
/* -------------------------------------------------------------------- */
GUInt32 nNewDictionaryPos = hHFA->nDictionaryPos;
if( hHFA->poDictionary->bDictionaryTextDirty )
{
VSIFSeekL( hHFA->fp, 0, SEEK_END );
nNewDictionaryPos = (GUInt32) VSIFTellL( hHFA->fp );
VSIFWriteL( hHFA->poDictionary->osDictionaryText.c_str(),
strlen(hHFA->poDictionary->osDictionaryText.c_str()) + 1,
1, hHFA->fp );
hHFA->poDictionary->bDictionaryTextDirty = FALSE;
}
/* -------------------------------------------------------------------- */
/* do we need to update the Ehfa_File pointer to the root node? */
/* -------------------------------------------------------------------- */
if( hHFA->nRootPos != hHFA->poRoot->GetFilePos()
|| nNewDictionaryPos != hHFA->nDictionaryPos )
{
GUInt32 nOffset;
GUInt32 nHeaderPos;
VSIFSeekL( hHFA->fp, 16, SEEK_SET );
VSIFReadL( &nHeaderPos, sizeof(GInt32), 1, hHFA->fp );
HFAStandard( 4, &nHeaderPos );
nOffset = hHFA->nRootPos = hHFA->poRoot->GetFilePos();
HFAStandard( 4, &nOffset );
VSIFSeekL( hHFA->fp, nHeaderPos+8, SEEK_SET );
VSIFWriteL( &nOffset, 4, 1, hHFA->fp );
nOffset = hHFA->nDictionaryPos = nNewDictionaryPos;
HFAStandard( 4, &nOffset );
VSIFSeekL( hHFA->fp, nHeaderPos+14, SEEK_SET );
VSIFWriteL( &nOffset, 4, 1, hHFA->fp );
}
return CE_None;
}
/************************************************************************/
/* HFACreateLayer() */
/* */
/* Create a layer object, and corresponding RasterDMS. */
/* Suitable for use with primary layers, and overviews. */
/************************************************************************/
int
HFACreateLayer( HFAHandle psInfo, HFAEntry *poParent,
const char *pszLayerName,
int bOverview, int nBlockSize,
int bCreateCompressed, int bCreateLargeRaster,
int bDependentLayer,
int nXSize, int nYSize, int nDataType,
char **papszOptions,
// these are only related to external (large) files
GIntBig nStackValidFlagsOffset,
GIntBig nStackDataOffset,
int nStackCount, int nStackIndex )
{
HFAEntry *poEimg_Layer;
const char *pszLayerType;
if( bOverview )
pszLayerType = "Eimg_Layer_SubSample";
else
pszLayerType = "Eimg_Layer";
if (nBlockSize <= 0)
{
CPLError(CE_Failure, CPLE_IllegalArg, "HFACreateLayer : nBlockXSize < 0");
return FALSE;
}
/* -------------------------------------------------------------------- */
/* Work out some details about the tiling scheme. */
/* -------------------------------------------------------------------- */
int nBlocksPerRow, nBlocksPerColumn, nBlocks, nBytesPerBlock;
nBlocksPerRow = (nXSize + nBlockSize - 1) / nBlockSize;
nBlocksPerColumn = (nYSize + nBlockSize - 1) / nBlockSize;
nBlocks = nBlocksPerRow * nBlocksPerColumn;
nBytesPerBlock = (nBlockSize * nBlockSize
* HFAGetDataTypeBits(nDataType) + 7) / 8;
/* -------------------------------------------------------------------- */
/* Create the Eimg_Layer for the band. */
/* -------------------------------------------------------------------- */
poEimg_Layer =
new HFAEntry( psInfo, pszLayerName, pszLayerType, poParent );
poEimg_Layer->SetIntField( "width", nXSize );
poEimg_Layer->SetIntField( "height", nYSize );
poEimg_Layer->SetStringField( "layerType", "athematic" );
poEimg_Layer->SetIntField( "pixelType", nDataType );
poEimg_Layer->SetIntField( "blockWidth", nBlockSize );
poEimg_Layer->SetIntField( "blockHeight", nBlockSize );
/* -------------------------------------------------------------------- */
/* Create the RasterDMS (block list). This is a complex type */
/* with pointers, and variable size. We set the superstructure */
/* ourselves rather than trying to have the HFA type management */
/* system do it for us (since this would be hard to implement). */
/* -------------------------------------------------------------------- */
if ( !bCreateLargeRaster && !bDependentLayer )
{
int nDmsSize;
HFAEntry *poEdms_State;
GByte *pabyData;
poEdms_State =
new HFAEntry( psInfo, "RasterDMS", "Edms_State", poEimg_Layer );
nDmsSize = 14 * nBlocks + 38;
pabyData = poEdms_State->MakeData( nDmsSize );
/* set some simple values */
poEdms_State->SetIntField( "numvirtualblocks", nBlocks );
poEdms_State->SetIntField( "numobjectsperblock",
nBlockSize*nBlockSize );
poEdms_State->SetIntField( "nextobjectnum",
nBlockSize*nBlockSize*nBlocks );
/* Is file compressed or not? */
if( bCreateCompressed )
{
poEdms_State->SetStringField( "compressionType", "RLC compression" );
}
else
{
poEdms_State->SetStringField( "compressionType", "no compression" );
}
/* we need to hardcode file offset into the data, so locate it now */
poEdms_State->SetPosition();
/* Set block info headers */
GUInt32 nValue;
/* blockinfo count */
nValue = nBlocks;
HFAStandard( 4, &nValue );
memcpy( pabyData + 14, &nValue, 4 );
/* blockinfo position */
nValue = poEdms_State->GetDataPos() + 22;
HFAStandard( 4, &nValue );
memcpy( pabyData + 18, &nValue, 4 );
/* Set each blockinfo */
for( int iBlock = 0; iBlock < nBlocks; iBlock++ )
{
GInt16 nValue16;
int nOffset = 22 + 14 * iBlock;
/* fileCode */
nValue16 = 0;
HFAStandard( 2, &nValue16 );
memcpy( pabyData + nOffset, &nValue16, 2 );
/* offset */
if( bCreateCompressed )
{
/* flag it with zero offset - will allocate space when we compress it */
nValue = 0;
}
else
{
nValue = HFAAllocateSpace( psInfo, nBytesPerBlock );
}
HFAStandard( 4, &nValue );
memcpy( pabyData + nOffset + 2, &nValue, 4 );
/* size */
if( bCreateCompressed )
{
/* flag it with zero size - don't know until we compress it */
nValue = 0;
}
else
{
nValue = nBytesPerBlock;
}
HFAStandard( 4, &nValue );
memcpy( pabyData + nOffset + 6, &nValue, 4 );
/* logValid (false) */
nValue16 = 0;
HFAStandard( 2, &nValue16 );
memcpy( pabyData + nOffset + 10, &nValue16, 2 );
/* compressionType */
if( bCreateCompressed )
nValue16 = 1;
else
nValue16 = 0;
HFAStandard( 2, &nValue16 );
memcpy( pabyData + nOffset + 12, &nValue16, 2 );
}
}
/* -------------------------------------------------------------------- */
/* Create ExternalRasterDMS object. */
/* -------------------------------------------------------------------- */
else if( bCreateLargeRaster )
{
HFAEntry *poEdms_State;
poEdms_State =
new HFAEntry( psInfo, "ExternalRasterDMS",
"ImgExternalRaster", poEimg_Layer );
poEdms_State->MakeData( 8 + strlen(psInfo->pszIGEFilename) + 1 + 6 * 4 );
poEdms_State->SetStringField( "fileName.string",
psInfo->pszIGEFilename );
poEdms_State->SetIntField( "layerStackValidFlagsOffset[0]",
(int) (nStackValidFlagsOffset & 0xFFFFFFFF));
poEdms_State->SetIntField( "layerStackValidFlagsOffset[1]",
(int) (nStackValidFlagsOffset >> 32) );
poEdms_State->SetIntField( "layerStackDataOffset[0]",
(int) (nStackDataOffset & 0xFFFFFFFF) );
poEdms_State->SetIntField( "layerStackDataOffset[1]",
(int) (nStackDataOffset >> 32 ) );
poEdms_State->SetIntField( "layerStackCount", nStackCount );
poEdms_State->SetIntField( "layerStackIndex", nStackIndex );
}
/* -------------------------------------------------------------------- */
/* Dependent... */
/* -------------------------------------------------------------------- */
else if( bDependentLayer )
{
HFAEntry *poDepLayerName;
poDepLayerName =
new HFAEntry( psInfo, "DependentLayerName",
"Eimg_DependentLayerName", poEimg_Layer );
poDepLayerName->MakeData( 8 + strlen(pszLayerName) + 2 );
poDepLayerName->SetStringField( "ImageLayerName.string",
pszLayerName );
}
/* -------------------------------------------------------------------- */
/* Create the Ehfa_Layer. */
/* -------------------------------------------------------------------- */
HFAEntry *poEhfa_Layer;
GUInt32 nLDict;
char szLDict[128], chBandType;
if( nDataType == EPT_u1 )
chBandType = '1';
else if( nDataType == EPT_u2 )
chBandType = '2';
else if( nDataType == EPT_u4 )
chBandType = '4';
else if( nDataType == EPT_u8 )
chBandType = 'c';
else if( nDataType == EPT_s8 )
chBandType = 'C';
else if( nDataType == EPT_u16 )
chBandType = 's';
else if( nDataType == EPT_s16 )
chBandType = 'S';
else if( nDataType == EPT_u32 )
// for some reason erdas imagine expects an L for unsinged 32 bit ints
// otherwise it gives strange "out of memory errors"
chBandType = 'L';
else if( nDataType == EPT_s32 )
chBandType = 'L';
else if( nDataType == EPT_f32 )
chBandType = 'f';
else if( nDataType == EPT_f64 )
chBandType = 'd';
else if( nDataType == EPT_c64 )
chBandType = 'm';
else if( nDataType == EPT_c128 )
chBandType = 'M';
else
{
CPLAssert( FALSE );
chBandType = 'c';
}
// the first value in the entry below gives the number of pixels within a block
sprintf( szLDict, "{%d:%cdata,}RasterDMS,.", nBlockSize*nBlockSize, chBandType );
poEhfa_Layer = new HFAEntry( psInfo, "Ehfa_Layer", "Ehfa_Layer",
poEimg_Layer );
poEhfa_Layer->MakeData();
poEhfa_Layer->SetPosition();
nLDict = HFAAllocateSpace( psInfo, strlen(szLDict) + 1 );
poEhfa_Layer->SetStringField( "type", "raster" );
poEhfa_Layer->SetIntField( "dictionaryPtr", nLDict );
VSIFSeekL( psInfo->fp, nLDict, SEEK_SET );
VSIFWriteL( (void *) szLDict, strlen(szLDict) + 1, 1, psInfo->fp );
return TRUE;
}
/************************************************************************/
/* HFACreate() */
/************************************************************************/
HFAHandle HFACreate( const char * pszFilename,
int nXSize, int nYSize, int nBands,
int nDataType, char ** papszOptions )
{
HFAHandle psInfo;
int nBlockSize = 64;
const char * pszValue = CSLFetchNameValue( papszOptions, "BLOCKSIZE" );
if ( pszValue != NULL )
{
nBlockSize = atoi( pszValue );
// check for sane values
if ( ( nBlockSize < 32 ) || (nBlockSize > 2048) )
{
nBlockSize = 64;
}
}
int bCreateLargeRaster = CSLFetchBoolean(papszOptions,"USE_SPILL",
FALSE);
int bCreateCompressed =
CSLFetchBoolean(papszOptions,"COMPRESS", FALSE)
|| CSLFetchBoolean(papszOptions,"COMPRESSED", FALSE);
int bCreateAux = CSLFetchBoolean(papszOptions,"AUX", FALSE);
char *pszFullFilename = NULL, *pszRawFilename = NULL;
/* -------------------------------------------------------------------- */
/* Create the low level structure. */
/* -------------------------------------------------------------------- */
psInfo = HFACreateLL( pszFilename );
if( psInfo == NULL )
return NULL;
/* -------------------------------------------------------------------- */
/* Create the DependentFile node if requested. */
/* -------------------------------------------------------------------- */
const char *pszDependentFile =
CSLFetchNameValue( papszOptions, "DEPENDENT_FILE" );
if( pszDependentFile != NULL )
{
HFAEntry *poDF = new HFAEntry( psInfo, "DependentFile",
"Eimg_DependentFile", psInfo->poRoot );
poDF->MakeData( strlen(pszDependentFile) + 50 );
poDF->SetPosition();
poDF->SetStringField( "dependent.string", pszDependentFile );
}
/* -------------------------------------------------------------------- */
/* Work out some details about the tiling scheme. */
/* -------------------------------------------------------------------- */
int nBlocksPerRow, nBlocksPerColumn, nBlocks, nBytesPerBlock;
nBlocksPerRow = (nXSize + nBlockSize - 1) / nBlockSize;
nBlocksPerColumn = (nYSize + nBlockSize - 1) / nBlockSize;
nBlocks = nBlocksPerRow * nBlocksPerColumn;
nBytesPerBlock = (nBlockSize * nBlockSize
* HFAGetDataTypeBits(nDataType) + 7) / 8;
CPLDebug( "HFACreate", "Blocks per row %d, blocks per column %d, "
"total number of blocks %d, bytes per block %d.",
nBlocksPerRow, nBlocksPerColumn, nBlocks, nBytesPerBlock );
/* -------------------------------------------------------------------- */
/* Check whether we should create external large file with */
/* image. We create a spill file if the amount of imagery is */
/* close to 2GB. We don't check the amount of auxilary */
/* information, so in theory if there were an awful lot of */
/* non-imagery data our approximate size could be smaller than */
/* the file will actually we be. We leave room for 10MB of */
/* auxilary data. */
/* We can also force spill file creation using option */
/* SPILL_FILE=YES. */
/* -------------------------------------------------------------------- */
double dfApproxSize = (double)nBytesPerBlock * (double)nBlocks *
(double)nBands + 10000000.0;
if( dfApproxSize > 2147483648.0 && !bCreateAux )
bCreateLargeRaster = TRUE;
// erdas imagine creates this entry even if an external spill file is used
if( !bCreateAux )
{
HFAEntry *poImgFormat;
poImgFormat = new HFAEntry( psInfo, "IMGFormatInfo",
"ImgFormatInfo831", psInfo->poRoot );
poImgFormat->MakeData();
if ( bCreateLargeRaster )
{
poImgFormat->SetIntField( "spaceUsedForRasterData", 0 );
bCreateCompressed = FALSE; // Can't be compressed if we are creating a spillfile
}
else
{
poImgFormat->SetIntField( "spaceUsedForRasterData",
nBytesPerBlock*nBlocks*nBands );
}
}
/* -------------------------------------------------------------------- */
/* Create external file and write its header. */
/* -------------------------------------------------------------------- */
GIntBig nValidFlagsOffset = 0, nDataOffset = 0;
if( bCreateLargeRaster )
{
if( !HFACreateSpillStack( psInfo, nXSize, nYSize, nBands,
nBlockSize, nDataType,
&nValidFlagsOffset, &nDataOffset ) )
{
CPLFree( pszRawFilename );
CPLFree( pszFullFilename );
return NULL;
}
}
/* ==================================================================== */
/* Create each band (layer) */
/* ==================================================================== */
int iBand;
for( iBand = 0; iBand < nBands; iBand++ )
{
char szName[128];
sprintf( szName, "Layer_%d", iBand + 1 );
if( !HFACreateLayer( psInfo, psInfo->poRoot, szName, FALSE, nBlockSize,
bCreateCompressed, bCreateLargeRaster, bCreateAux,
nXSize, nYSize, nDataType, papszOptions,
nValidFlagsOffset, nDataOffset,
nBands, iBand ) )
{
HFAClose( psInfo );
return NULL;
}
}
/* -------------------------------------------------------------------- */
/* Initialize the band information. */
/* -------------------------------------------------------------------- */
HFAParseBandInfo( psInfo );
return psInfo;
}
/************************************************************************/
/* HFACreateOverview() */
/* */
/* Create an overview layer object for a band. */
/************************************************************************/
int HFACreateOverview( HFAHandle hHFA, int nBand, int nOverviewLevel,
const char *pszResampling )
{
if( nBand < 1 || nBand > hHFA->nBands )
return -1;
else
{
HFABand *poBand = hHFA->papoBand[nBand-1];
return poBand->CreateOverview( nOverviewLevel, pszResampling );
}
}
/************************************************************************/
/* HFAGetMetadata() */
/* */
/* Read metadata structured in a table called GDAL_MetaData. */
/************************************************************************/
char ** HFAGetMetadata( HFAHandle hHFA, int nBand )
{
HFAEntry *poTable;
if( nBand > 0 && nBand <= hHFA->nBands )
poTable = hHFA->papoBand[nBand - 1]->poNode->GetChild();
else if( nBand == 0 )
poTable = hHFA->poRoot->GetChild();
else
return NULL;
for( ; poTable != NULL && !EQUAL(poTable->GetName(),"GDAL_MetaData");
poTable = poTable->GetNext() ) {}
if( poTable == NULL || !EQUAL(poTable->GetType(),"Edsc_Table") )
return NULL;
if( poTable->GetIntField( "numRows" ) != 1 )
{
CPLDebug( "HFADataset", "GDAL_MetaData.numRows = %d, expected 1!",
poTable->GetIntField( "numRows" ) );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Loop over each column. Each column will be one metadata */
/* entry, with the title being the key, and the row value being */
/* the value. There is only ever one row in GDAL_MetaData */
/* tables. */
/* -------------------------------------------------------------------- */
HFAEntry *poColumn;
char **papszMD = NULL;
for( poColumn = poTable->GetChild();
poColumn != NULL;
poColumn = poColumn->GetNext() )
{
const char *pszValue;
int columnDataPtr;
// Skip the #Bin_Function# entry.
if( EQUALN(poColumn->GetName(),"#",1) )
continue;
pszValue = poColumn->GetStringField( "dataType" );
if( pszValue == NULL || !EQUAL(pszValue,"string") )
continue;
columnDataPtr = poColumn->GetIntField( "columnDataPtr" );
if( columnDataPtr == 0 )
continue;
/* -------------------------------------------------------------------- */
/* read up to nMaxNumChars bytes from the indicated location. */
/* allocate required space temporarily */
/* nMaxNumChars should have been set by GDAL orginally so we should*/
/* trust it, but who knows... */
/* -------------------------------------------------------------------- */
int nMaxNumChars = poColumn->GetIntField( "maxNumChars" );
if( nMaxNumChars == 0 )
{
papszMD = CSLSetNameValue( papszMD, poColumn->GetName(), "" );
}
else
{
char *pszMDValue = (char*) VSIMalloc(nMaxNumChars);
if (pszMDValue == NULL)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"HFAGetMetadata : Out of memory while allocating %d bytes", nMaxNumChars);
continue;
}
if( VSIFSeekL( hHFA->fp, columnDataPtr, SEEK_SET ) != 0 )
continue;
int nMDBytes = VSIFReadL( pszMDValue, 1, nMaxNumChars, hHFA->fp );
if( nMDBytes == 0 )
{
CPLFree( pszMDValue );
continue;
}
pszMDValue[nMaxNumChars-1] = '\0';
papszMD = CSLSetNameValue( papszMD, poColumn->GetName(),
pszMDValue );
CPLFree( pszMDValue );
}
}
return papszMD;
}
/************************************************************************/
/* HFASetGDALMetadata() */
/* */
/* This function is used to set metadata in a table called */
/* GDAL_MetaData. It is called by HFASetMetadata() for all */
/* metadata items that aren't some specific supported */
/* information (like histogram or stats info). */
/************************************************************************/
static CPLErr
HFASetGDALMetadata( HFAHandle hHFA, int nBand, char **papszMD )
{
if( papszMD == NULL )
return CE_None;
HFAEntry *poNode;
if( nBand > 0 && nBand <= hHFA->nBands )
poNode = hHFA->papoBand[nBand - 1]->poNode;
else if( nBand == 0 )
poNode = hHFA->poRoot;
else
return CE_Failure;
/* -------------------------------------------------------------------- */
/* Create the Descriptor table. */
/* Check we have no table with this name already */
/* -------------------------------------------------------------------- */
HFAEntry *poEdsc_Table = poNode->GetNamedChild( "GDAL_MetaData" );
if( poEdsc_Table == NULL || !EQUAL(poEdsc_Table->GetType(),"Edsc_Table") )
poEdsc_Table = new HFAEntry( hHFA, "GDAL_MetaData", "Edsc_Table",
poNode );
poEdsc_Table->SetIntField( "numrows", 1 );
/* -------------------------------------------------------------------- */
/* Create the Binning function node. I am not sure that we */
/* really need this though. */
/* Check it doesn't exist already */
/* -------------------------------------------------------------------- */
HFAEntry *poEdsc_BinFunction =
poEdsc_Table->GetNamedChild( "#Bin_Function#" );
if( poEdsc_BinFunction == NULL
|| !EQUAL(poEdsc_BinFunction->GetType(),"Edsc_BinFunction") )
poEdsc_BinFunction = new HFAEntry( hHFA, "#Bin_Function#",
"Edsc_BinFunction", poEdsc_Table );
// Because of the BaseData we have to hardcode the size.
poEdsc_BinFunction->MakeData( 30 );
poEdsc_BinFunction->SetIntField( "numBins", 1 );
poEdsc_BinFunction->SetStringField( "binFunction", "direct" );
poEdsc_BinFunction->SetDoubleField( "minLimit", 0.0 );
poEdsc_BinFunction->SetDoubleField( "maxLimit", 0.0 );
/* -------------------------------------------------------------------- */
/* Process each metadata item as a separate column. */
/* -------------------------------------------------------------------- */
for( int iColumn = 0; papszMD[iColumn] != NULL; iColumn++ )
{
HFAEntry *poEdsc_Column;
char *pszKey = NULL;
const char *pszValue;
pszValue = CPLParseNameValue( papszMD[iColumn], &pszKey );
if( pszValue == NULL )
continue;
/* -------------------------------------------------------------------- */
/* Create the Edsc_Column. */
/* Check it doesn't exist already */
/* -------------------------------------------------------------------- */
poEdsc_Column = poEdsc_Table->GetNamedChild(pszKey);
if( poEdsc_Column == NULL
|| !EQUAL(poEdsc_Column->GetType(),"Edsc_Column") )
poEdsc_Column = new HFAEntry( hHFA, pszKey, "Edsc_Column",
poEdsc_Table );
poEdsc_Column->SetIntField( "numRows", 1 );
poEdsc_Column->SetStringField( "dataType", "string" );
poEdsc_Column->SetIntField( "maxNumChars", strlen(pszValue)+1 );
/* -------------------------------------------------------------------- */
/* Write the data out. */
/* -------------------------------------------------------------------- */
int nOffset = HFAAllocateSpace( hHFA, strlen(pszValue)+1);
poEdsc_Column->SetIntField( "columnDataPtr", nOffset );
VSIFSeekL( hHFA->fp, nOffset, SEEK_SET );
VSIFWriteL( (void *) pszValue, 1, strlen(pszValue)+1, hHFA->fp );
CPLFree( pszKey );
}
return CE_Failure;
}
/************************************************************************/
/* HFASetMetadata() */
/************************************************************************/
CPLErr HFASetMetadata( HFAHandle hHFA, int nBand, char **papszMD )
{
char **papszGDALMD = NULL;
if( CSLCount(papszMD) == 0 )
return CE_None;
HFAEntry *poNode;
if( nBand > 0 && nBand <= hHFA->nBands )
poNode = hHFA->papoBand[nBand - 1]->poNode;
else if( nBand == 0 )
poNode = hHFA->poRoot;
else
return CE_Failure;
/* -------------------------------------------------------------------- */
/* Check if the Metadata is an "known" entity which should be */
/* stored in a better place. */
/* -------------------------------------------------------------------- */
char * pszBinValues = NULL;
int bCreatedHistogramParameters = FALSE;
int bCreatedStatistics = FALSE;
const char ** pszAuxMetaData = GetHFAAuxMetaDataList();
// check each metadata item
for( int iColumn = 0; papszMD[iColumn] != NULL; iColumn++ )
{
char *pszKey = NULL;
const char *pszValue;
pszValue = CPLParseNameValue( papszMD[iColumn], &pszKey );
if( pszValue == NULL )
continue;
// know look if its known
int i;
for( i = 0; pszAuxMetaData[i] != NULL; i += 4 )
{
if ( EQUALN( pszAuxMetaData[i + 2], pszKey, strlen(pszKey) ) )
break;
}
if ( pszAuxMetaData[i] != NULL )
{
// found one, get the right entry
HFAEntry *poEntry;
if( strlen(pszAuxMetaData[i]) > 0 )
poEntry = poNode->GetNamedChild( pszAuxMetaData[i] );
else
poEntry = poNode;
if( poEntry == NULL && strlen(pszAuxMetaData[i+3]) > 0 )
{
// child does not yet exist --> create it
poEntry = new HFAEntry( hHFA, pszAuxMetaData[i], pszAuxMetaData[i+3],
poNode );
if ( EQUALN( "Statistics", pszAuxMetaData[i], 10 ) )
bCreatedStatistics = TRUE;
if( EQUALN( "HistogramParameters", pszAuxMetaData[i], 19 ) )
{
// this is a bit nasty I need to set the string field for the object
// first because the SetStringField sets the count for the object
// BinFunction to the length of the string
poEntry->MakeData( 70 );
poEntry->SetStringField( "BinFunction.binFunctionType", "direct" );
bCreatedHistogramParameters = TRUE;
}
}
if ( poEntry == NULL )
{
CPLFree( pszKey );
continue;
}
const char *pszFieldName = pszAuxMetaData[i+1] + 1;
switch( pszAuxMetaData[i+1][0] )
{
case 'd':
{
double dfValue = atof( pszValue );
poEntry->SetDoubleField( pszFieldName, dfValue );
}
break;
case 'i':
case 'l':
{
int nValue = atoi( pszValue );
poEntry->SetIntField( pszFieldName, nValue );
}
break;
case 's':
case 'e':
{
poEntry->SetStringField( pszFieldName, pszValue );
}
break;
default:
CPLAssert( FALSE );
}
}
else if ( EQUALN( "STATISTICS_HISTOBINVALUES", pszKey, strlen(pszKey) ) )
{
pszBinValues = strdup( pszValue );
}
else
papszGDALMD = CSLAddString( papszGDALMD, papszMD[iColumn] );
CPLFree( pszKey );
}
/* -------------------------------------------------------------------- */
/* Special case to write out the histogram. */
/* -------------------------------------------------------------------- */
if ( pszBinValues != NULL )
{
HFAEntry * poEntry = poNode->GetNamedChild( "HistogramParameters" );
if ( poEntry != NULL && bCreatedHistogramParameters )
{
// if this node exists we have added Histogram data -- complete with some defaults
poEntry->SetIntField( "SkipFactorX", 1 );
poEntry->SetIntField( "SkipFactorY", 1 );
int nNumBins = poEntry->GetIntField( "BinFunction.numBins" );
double dMinLimit = poEntry->GetDoubleField( "BinFunction.minLimit" );
double dMaxLimit = poEntry->GetDoubleField( "BinFunction.maxLimit" );
// fill the descriptor table - check it isn't there already
poEntry = poNode->GetNamedChild( "Descriptor_Table" );
if( poEntry == NULL || !EQUAL(poEntry->GetType(),"Edsc_Table") )
poEntry = new HFAEntry( hHFA, "Descriptor_Table", "Edsc_Table", poNode );
poEntry->SetIntField( "numRows", nNumBins );
// bin function
HFAEntry * poBinFunc = poEntry->GetNamedChild( "#Bin_Function#" );
if( poBinFunc == NULL || !EQUAL(poBinFunc->GetType(),"Edsc_BinFunction") )
poBinFunc = new HFAEntry( hHFA, "#Bin_Function#", "Edsc_BinFunction", poEntry );
poBinFunc->MakeData( 30 );
poBinFunc->SetIntField( "numBins", nNumBins );
poBinFunc->SetDoubleField( "minLimit", dMinLimit );
poBinFunc->SetDoubleField( "maxLimit", dMaxLimit );
// direct for thematic layers, linear otherwise
if ( EQUALN ( poNode->GetStringField("layerType"), "thematic", 8) )
poBinFunc->SetStringField( "binFunctionType", "direct" );
else
poBinFunc->SetStringField( "binFunctionType", "linear" );
// we need a child named histogram
HFAEntry * poHisto = poEntry->GetNamedChild( "Histogram" );
if( poHisto == NULL || !EQUAL(poHisto->GetType(),"Edsc_Column") )
poHisto = new HFAEntry( hHFA, "Histogram", "Edsc_Column", poEntry );
poHisto->SetIntField( "numRows", nNumBins );
// allocate space for the bin values
GUInt32 nOffset = HFAAllocateSpace( hHFA, nNumBins*8 );
poHisto->SetIntField( "columnDataPtr", nOffset );
poHisto->SetStringField( "dataType", "real" );
poHisto->SetIntField( "maxNumChars", 0 );
// write out histogram data
char * pszWork = pszBinValues;
for ( int nBin = 0; nBin < nNumBins; ++nBin )
{
char * pszEnd = strchr( pszWork, '|' );
if ( pszEnd != NULL )
{
*pszEnd = 0;
VSIFSeekL( hHFA->fp, nOffset + 8*nBin, SEEK_SET );
double nValue = atof( pszWork );
HFAStandard( 8, &nValue );
VSIFWriteL( (void *)&nValue, 1, 8, hHFA->fp );
pszWork = pszEnd + 1;
}
}
}
else if ( poEntry != NULL )
{
// In this case, there are HistogramParameters present, but we did not
// create them. However, we might be modifying them, in the case where
// the data has changed and the histogram counts need to be updated. It could
// be worse than that, but that is all we are going to cope with for now.
// We are assuming that we did not change any of the other stuff, like
// skip factors and so forth. The main need for this case is for programs
// (such as Imagine itself) which will happily modify the pixel values
// without re-calculating the histogram counts.
int nNumBins = poEntry->GetIntField( "BinFunction.numBins" );
HFAEntry *poEntryDescrTbl = poNode->GetNamedChild( "Descriptor_Table" );
HFAEntry *poHisto = NULL;
if ( poEntryDescrTbl != NULL) {
poHisto = poEntryDescrTbl->GetNamedChild( "Histogram" );
}
if ( poHisto != NULL ) {
int nOffset = poHisto->GetIntField( "columnDataPtr" );
// write out histogram data
char * pszWork = pszBinValues;
// Check whether histogram counts were written as int or double
bool bCountIsInt = TRUE;
const char *pszDataType = poHisto->GetStringField("dataType");
if ( EQUALN(pszDataType, "real", strlen(pszDataType)) )
{
bCountIsInt = FALSE;
}
for ( int nBin = 0; nBin < nNumBins; ++nBin )
{
char * pszEnd = strchr( pszWork, '|' );
if ( pszEnd != NULL )
{
*pszEnd = 0;
if ( bCountIsInt ) {
// Histogram counts were written as ints, so re-write them the same way
VSIFSeekL( hHFA->fp, nOffset + 4*nBin, SEEK_SET );
int nValue = atoi( pszWork );
HFAStandard( 4, &nValue );
VSIFWriteL( (void *)&nValue, 1, 4, hHFA->fp );
} else {
// Histogram were written as doubles, as is now the default behaviour
VSIFSeekL( hHFA->fp, nOffset + 8*nBin, SEEK_SET );
double nValue = atof( pszWork );
HFAStandard( 8, &nValue );
VSIFWriteL( (void *)&nValue, 1, 8, hHFA->fp );
}
pszWork = pszEnd + 1;
}
}
}
}
free( pszBinValues );
}
/* -------------------------------------------------------------------- */
/* If we created a statistics node then try to create a */
/* StatisticsParameters node too. */
/* -------------------------------------------------------------------- */
if( bCreatedStatistics )
{
HFAEntry *poEntry =
new HFAEntry( hHFA, "StatisticsParameters",
"Eimg_StatisticsParameters830", poNode );
poEntry->MakeData( 70 );
//poEntry->SetStringField( "BinFunction.binFunctionType", "linear" );
poEntry->SetIntField( "SkipFactorX", 1 );
poEntry->SetIntField( "SkipFactorY", 1 );
}
/* -------------------------------------------------------------------- */
/* Write out metadata items without a special place. */
/* -------------------------------------------------------------------- */
if( CSLCount( papszGDALMD) != 0 )
{
CPLErr eErr = HFASetGDALMetadata( hHFA, nBand, papszGDALMD );
CSLDestroy( papszGDALMD );
return eErr;
}
else
return CE_Failure;
}
/************************************************************************/
/* HFAGetIGEFilename() */
/* */
/* Returns the .ige filename if one is associated with this */
/* object. For files not newly created we need to scan the */
/* bands for spill files. Presumably there will only be one. */
/* */
/* NOTE: Returns full path, not just the filename portion. */
/************************************************************************/
const char *HFAGetIGEFilename( HFAHandle hHFA )
{
if( hHFA->pszIGEFilename == NULL )
{
HFAEntry *poDMS = NULL;
std::vector<HFAEntry*> apoDMSList =
hHFA->poRoot->FindChildren( NULL, "ImgExternalRaster" );
if( apoDMSList.size() > 0 )
poDMS = apoDMSList[0];
/* -------------------------------------------------------------------- */
/* Get the IGE filename from if we have an ExternalRasterDMS */
/* -------------------------------------------------------------------- */
if( poDMS )
{
const char *pszRawFilename =
poDMS->GetStringField( "fileName.string" );
if( pszRawFilename != NULL )
{
VSIStatBufL sStatBuf;
CPLString osFullFilename =
CPLFormFilename( hHFA->pszPath, pszRawFilename, NULL );
if( VSIStatL( osFullFilename, &sStatBuf ) != 0 )
{
CPLString osExtension = CPLGetExtension(pszRawFilename);
CPLString osBasename = CPLGetBasename(hHFA->pszFilename);
CPLString osFullFilename =
CPLFormFilename( hHFA->pszPath, osBasename,
osExtension );
if( VSIStatL( osFullFilename, &sStatBuf ) == 0 )
hHFA->pszIGEFilename =
CPLStrdup(
CPLFormFilename( NULL, osBasename,
osExtension ) );
else
hHFA->pszIGEFilename = CPLStrdup( pszRawFilename );
}
else
hHFA->pszIGEFilename = CPLStrdup( pszRawFilename );
}
}
}
/* -------------------------------------------------------------------- */
/* Return the full filename. */
/* -------------------------------------------------------------------- */
if( hHFA->pszIGEFilename )
return CPLFormFilename( hHFA->pszPath, hHFA->pszIGEFilename, NULL );
else
return NULL;
}
/************************************************************************/
/* HFACreateSpillStack() */
/* */
/* Create a new stack of raster layers in the spill (.ige) */
/* file. Create the spill file if it didn't exist before. */
/************************************************************************/
int HFACreateSpillStack( HFAInfo_t *psInfo, int nXSize, int nYSize,
int nLayers, int nBlockSize, int nDataType,
GIntBig *pnValidFlagsOffset,
GIntBig *pnDataOffset )
{
/* -------------------------------------------------------------------- */
/* Form .ige filename. */
/* -------------------------------------------------------------------- */
char *pszFullFilename;
if (nBlockSize <= 0)
{
CPLError(CE_Failure, CPLE_IllegalArg, "HFACreateSpillStack : nBlockXSize < 0");
return FALSE;
}
if( psInfo->pszIGEFilename == NULL )
{
if( EQUAL(CPLGetExtension(psInfo->pszFilename),"rrd") )
psInfo->pszIGEFilename =
CPLStrdup( CPLResetExtension( psInfo->pszFilename, "rde" ) );
else if( EQUAL(CPLGetExtension(psInfo->pszFilename),"aux") )
psInfo->pszIGEFilename =
CPLStrdup( CPLResetExtension( psInfo->pszFilename, "axe" ) );
else
psInfo->pszIGEFilename =
CPLStrdup( CPLResetExtension( psInfo->pszFilename, "ige" ) );
}
pszFullFilename =
CPLStrdup( CPLFormFilename( psInfo->pszPath, psInfo->pszIGEFilename, NULL ) );
/* -------------------------------------------------------------------- */
/* Try and open it. If we fail, create it and write the magic */
/* header. */
/* -------------------------------------------------------------------- */
static const char *pszMagick = "ERDAS_IMG_EXTERNAL_RASTER";
VSILFILE *fpVSIL;
fpVSIL = VSIFOpenL( pszFullFilename, "r+b" );
if( fpVSIL == NULL )
{
fpVSIL = VSIFOpenL( pszFullFilename, "w+" );
if( fpVSIL == NULL )
{
CPLError( CE_Failure, CPLE_OpenFailed,
"Failed to create spill file %s.\n%s",
psInfo->pszIGEFilename, VSIStrerror( errno ) );
return FALSE;
}
VSIFWriteL( (void *) pszMagick, 1, strlen(pszMagick)+1, fpVSIL );
}
CPLFree( pszFullFilename );
/* -------------------------------------------------------------------- */
/* Work out some details about the tiling scheme. */
/* -------------------------------------------------------------------- */
int nBlocksPerRow, nBlocksPerColumn, nBlocks, nBytesPerBlock;
int nBytesPerRow, nBlockMapSize, iFlagsSize;
nBlocksPerRow = (nXSize + nBlockSize - 1) / nBlockSize;
nBlocksPerColumn = (nYSize + nBlockSize - 1) / nBlockSize;
nBlocks = nBlocksPerRow * nBlocksPerColumn;
nBytesPerBlock = (nBlockSize * nBlockSize
* HFAGetDataTypeBits(nDataType) + 7) / 8;
nBytesPerRow = ( nBlocksPerRow + 7 ) / 8;
nBlockMapSize = nBytesPerRow * nBlocksPerColumn;
iFlagsSize = nBlockMapSize + 20;
/* -------------------------------------------------------------------- */
/* Write stack prefix information. */
/* -------------------------------------------------------------------- */
GByte bUnknown;
GInt32 nValue32;
VSIFSeekL( fpVSIL, 0, SEEK_END );
bUnknown = 1;
VSIFWriteL( &bUnknown, 1, 1, fpVSIL );
nValue32 = nLayers;
HFAStandard( 4, &nValue32 );
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
nValue32 = nXSize;
HFAStandard( 4, &nValue32 );
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
nValue32 = nYSize;
HFAStandard( 4, &nValue32 );
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
nValue32 = nBlockSize;
HFAStandard( 4, &nValue32 );
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
bUnknown = 3;
VSIFWriteL( &bUnknown, 1, 1, fpVSIL );
bUnknown = 0;
VSIFWriteL( &bUnknown, 1, 1, fpVSIL );
/* -------------------------------------------------------------------- */
/* Write out ValidFlags section(s). */
/* -------------------------------------------------------------------- */
unsigned char *pabyBlockMap;
int iBand;
*pnValidFlagsOffset = VSIFTellL( fpVSIL );
pabyBlockMap = (unsigned char *) VSIMalloc( nBlockMapSize );
if (pabyBlockMap == NULL)
{
CPLError(CE_Failure, CPLE_OutOfMemory, "HFACreateSpillStack : Out of memory");
VSIFCloseL( fpVSIL );
return FALSE;
}
memset( pabyBlockMap, 0xff, nBlockMapSize );
for ( iBand = 0; iBand < nLayers; iBand++ )
{
int i, iRemainder;
nValue32 = 1; // Unknown
HFAStandard( 4, &nValue32 );
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
nValue32 = 0; // Unknown
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
nValue32 = nBlocksPerColumn;
HFAStandard( 4, &nValue32 );
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
nValue32 = nBlocksPerRow;
HFAStandard( 4, &nValue32 );
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
nValue32 = 0x30000; // Unknown
HFAStandard( 4, &nValue32 );
VSIFWriteL( &nValue32, 4, 1, fpVSIL );
iRemainder = nBlocksPerRow % 8;
CPLDebug( "HFACreate",
"Block map size %d, bytes per row %d, remainder %d.",
nBlockMapSize, nBytesPerRow, iRemainder );
if ( iRemainder )
{
for ( i = nBytesPerRow - 1; i < nBlockMapSize; i+=nBytesPerRow )
pabyBlockMap[i] = (GByte) ((1<<iRemainder) - 1);
}
VSIFWriteL( pabyBlockMap, 1, nBlockMapSize, fpVSIL );
}
CPLFree(pabyBlockMap);
pabyBlockMap = NULL;
/* -------------------------------------------------------------------- */
/* Extend the file to account for all the imagery space. */
/* -------------------------------------------------------------------- */
GIntBig nTileDataSize = ((GIntBig) nBytesPerBlock)
* nBlocksPerRow * nBlocksPerColumn * nLayers;
*pnDataOffset = VSIFTellL( fpVSIL );
if( VSIFSeekL( fpVSIL, nTileDataSize - 1 + *pnDataOffset, SEEK_SET ) != 0
|| VSIFWriteL( (void *) "", 1, 1, fpVSIL ) != 1 )
{
CPLError( CE_Failure, CPLE_FileIO,
"Failed to extend %s to full size (%g bytes),\n"
"likely out of disk space.\n%s",
psInfo->pszIGEFilename,
(double) nTileDataSize - 1 + *pnDataOffset,
VSIStrerror( errno ) );
VSIFCloseL( fpVSIL );
return FALSE;
}
VSIFCloseL( fpVSIL );
return TRUE;
}
/************************************************************************/
/* HFAReadAndValidatePoly() */
/************************************************************************/
static int HFAReadAndValidatePoly( HFAEntry *poTarget,
const char *pszName,
Efga_Polynomial *psRetPoly )
{
CPLString osFldName;
memset( psRetPoly, 0, sizeof(Efga_Polynomial) );
osFldName.Printf( "%sorder", pszName );
psRetPoly->order = poTarget->GetIntField(osFldName);
if( psRetPoly->order < 1 || psRetPoly->order > 3 )
return FALSE;
/* -------------------------------------------------------------------- */
/* Validate that things are in a "well known" form. */
/* -------------------------------------------------------------------- */
int numdimtransform, numdimpolynomial, termcount;
osFldName.Printf( "%snumdimtransform", pszName );
numdimtransform = poTarget->GetIntField(osFldName);
osFldName.Printf( "%snumdimpolynomial", pszName );
numdimpolynomial = poTarget->GetIntField(osFldName);
osFldName.Printf( "%stermcount", pszName );
termcount = poTarget->GetIntField(osFldName);
if( numdimtransform != 2 || numdimpolynomial != 2 )
return FALSE;
if( (psRetPoly->order == 1 && termcount != 3)
|| (psRetPoly->order == 2 && termcount != 6)
|| (psRetPoly->order == 3 && termcount != 10) )
return FALSE;
// we don't check the exponent organization for now. Hopefully
// it is always standard.
/* -------------------------------------------------------------------- */
/* Get coefficients. */
/* -------------------------------------------------------------------- */
int i;
for( i = 0; i < termcount*2 - 2; i++ )
{
osFldName.Printf( "%spolycoefmtx[%d]", pszName, i );
psRetPoly->polycoefmtx[i] = poTarget->GetDoubleField(osFldName);
}
for( i = 0; i < 2; i++ )
{
osFldName.Printf( "%spolycoefvector[%d]", pszName, i );
psRetPoly->polycoefvector[i] = poTarget->GetDoubleField(osFldName);
}
return TRUE;
}
/************************************************************************/
/* HFAReadXFormStack() */
/************************************************************************/
int HFAReadXFormStack( HFAHandle hHFA,
Efga_Polynomial **ppasPolyListForward,
Efga_Polynomial **ppasPolyListReverse )
{
if( hHFA->nBands == 0 )
return 0;
/* -------------------------------------------------------------------- */
/* Get the HFA node. */
/* -------------------------------------------------------------------- */
HFAEntry *poXFormHeader;
poXFormHeader = hHFA->papoBand[0]->poNode->GetNamedChild( "MapToPixelXForm" );
if( poXFormHeader == NULL )
return 0;
/* -------------------------------------------------------------------- */
/* Loop over children, collecting XForms. */
/* -------------------------------------------------------------------- */
HFAEntry *poXForm;
int nStepCount = 0;
*ppasPolyListForward = NULL;
*ppasPolyListReverse = NULL;
for( poXForm = poXFormHeader->GetChild();
poXForm != NULL;
poXForm = poXForm->GetNext() )
{
int bSuccess = FALSE;
Efga_Polynomial sForward, sReverse;
memset( &sForward, 0, sizeof(sForward) );
memset( &sReverse, 0, sizeof(sReverse) );
if( EQUAL(poXForm->GetType(),"Efga_Polynomial") )
{
bSuccess =
HFAReadAndValidatePoly( poXForm, "", &sForward );
if( bSuccess )
{
double adfGT[6], adfInvGT[6];
adfGT[0] = sForward.polycoefvector[0];
adfGT[1] = sForward.polycoefmtx[0];
adfGT[2] = sForward.polycoefmtx[2];
adfGT[3] = sForward.polycoefvector[1];
adfGT[4] = sForward.polycoefmtx[1];
adfGT[5] = sForward.polycoefmtx[3];
bSuccess = HFAInvGeoTransform( adfGT, adfInvGT );
sReverse.order = sForward.order;
sReverse.polycoefvector[0] = adfInvGT[0];
sReverse.polycoefmtx[0] = adfInvGT[1];
sReverse.polycoefmtx[2] = adfInvGT[2];
sReverse.polycoefvector[1] = adfInvGT[3];
sReverse.polycoefmtx[1] = adfInvGT[4];
sReverse.polycoefmtx[3] = adfInvGT[5];
}
}
else if( EQUAL(poXForm->GetType(),"GM_PolyPair") )
{
bSuccess =
HFAReadAndValidatePoly( poXForm, "forward.", &sForward );
bSuccess = bSuccess &&
HFAReadAndValidatePoly( poXForm, "reverse.", &sReverse );
}
if( bSuccess )
{
nStepCount++;
*ppasPolyListForward = (Efga_Polynomial *)
CPLRealloc( *ppasPolyListForward,
sizeof(Efga_Polynomial) * nStepCount);
memcpy( *ppasPolyListForward + nStepCount - 1,
&sForward, sizeof(sForward) );
*ppasPolyListReverse = (Efga_Polynomial *)
CPLRealloc( *ppasPolyListReverse,
sizeof(Efga_Polynomial) * nStepCount);
memcpy( *ppasPolyListReverse + nStepCount - 1,
&sReverse, sizeof(sReverse) );
}
}
return nStepCount;
}
/************************************************************************/
/* HFAEvaluateXFormStack() */
/************************************************************************/
int HFAEvaluateXFormStack( int nStepCount, int bForward,
Efga_Polynomial *pasPolyList,
double *pdfX, double *pdfY )
{
int iStep;
for( iStep = 0; iStep < nStepCount; iStep++ )
{
double dfXOut, dfYOut;
Efga_Polynomial *psStep;
if( bForward )
psStep = pasPolyList + iStep;
else
psStep = pasPolyList + nStepCount - iStep - 1;
if( psStep->order == 1 )
{
dfXOut = psStep->polycoefvector[0]
+ psStep->polycoefmtx[0] * *pdfX
+ psStep->polycoefmtx[2] * *pdfY;
dfYOut = psStep->polycoefvector[1]
+ psStep->polycoefmtx[1] * *pdfX
+ psStep->polycoefmtx[3] * *pdfY;
*pdfX = dfXOut;
*pdfY = dfYOut;
}
else if( psStep->order == 2 )
{
dfXOut = psStep->polycoefvector[0]
+ psStep->polycoefmtx[0] * *pdfX
+ psStep->polycoefmtx[2] * *pdfY
+ psStep->polycoefmtx[4] * *pdfX * *pdfX
+ psStep->polycoefmtx[6] * *pdfX * *pdfY
+ psStep->polycoefmtx[8] * *pdfY * *pdfY;
dfYOut = psStep->polycoefvector[1]
+ psStep->polycoefmtx[1] * *pdfX
+ psStep->polycoefmtx[3] * *pdfY
+ psStep->polycoefmtx[5] * *pdfX * *pdfX
+ psStep->polycoefmtx[7] * *pdfX * *pdfY
+ psStep->polycoefmtx[9] * *pdfY * *pdfY;
*pdfX = dfXOut;
*pdfY = dfYOut;
}
else if( psStep->order == 3 )
{
dfXOut = psStep->polycoefvector[0]
+ psStep->polycoefmtx[ 0] * *pdfX
+ psStep->polycoefmtx[ 2] * *pdfY
+ psStep->polycoefmtx[ 4] * *pdfX * *pdfX
+ psStep->polycoefmtx[ 6] * *pdfX * *pdfY
+ psStep->polycoefmtx[ 8] * *pdfY * *pdfY
+ psStep->polycoefmtx[10] * *pdfX * *pdfX * *pdfX
+ psStep->polycoefmtx[12] * *pdfX * *pdfX * *pdfY
+ psStep->polycoefmtx[14] * *pdfX * *pdfY * *pdfY
+ psStep->polycoefmtx[16] * *pdfY * *pdfY * *pdfY;
dfYOut = psStep->polycoefvector[1]
+ psStep->polycoefmtx[ 1] * *pdfX
+ psStep->polycoefmtx[ 3] * *pdfY
+ psStep->polycoefmtx[ 5] * *pdfX * *pdfX
+ psStep->polycoefmtx[ 7] * *pdfX * *pdfY
+ psStep->polycoefmtx[ 9] * *pdfY * *pdfY
+ psStep->polycoefmtx[11] * *pdfX * *pdfX * *pdfX
+ psStep->polycoefmtx[13] * *pdfX * *pdfX * *pdfY
+ psStep->polycoefmtx[15] * *pdfX * *pdfY * *pdfY
+ psStep->polycoefmtx[17] * *pdfY * *pdfY * *pdfY;
*pdfX = dfXOut;
*pdfY = dfYOut;
}
else
return FALSE;
}
return TRUE;
}
/************************************************************************/
/* HFAWriteXFormStack() */
/************************************************************************/
CPLErr HFAWriteXFormStack( HFAHandle hHFA, int nBand, int nXFormCount,
Efga_Polynomial **ppasPolyListForward,
Efga_Polynomial **ppasPolyListReverse )
{
if( nXFormCount == 0 )
return CE_None;
if( ppasPolyListForward[0]->order != 1 )
{
CPLError( CE_Failure, CPLE_AppDefined,
"For now HFAWriteXFormStack() only supports order 1 polynomials" );
return CE_Failure;
}
if( nBand < 0 || nBand > hHFA->nBands )
return CE_Failure;
/* -------------------------------------------------------------------- */
/* If no band number is provided, operate on all bands. */
/* -------------------------------------------------------------------- */
if( nBand == 0 )
{
CPLErr eErr = CE_None;
for( nBand = 1; nBand <= hHFA->nBands; nBand++ )
{
eErr = HFAWriteXFormStack( hHFA, nBand, nXFormCount,
ppasPolyListForward,
ppasPolyListReverse );
if( eErr != CE_None )
return eErr;
}
return eErr;
}
/* -------------------------------------------------------------------- */
/* Fetch our band node. */
/* -------------------------------------------------------------------- */
HFAEntry *poBandNode = hHFA->papoBand[nBand-1]->poNode;
HFAEntry *poXFormHeader;
poXFormHeader = poBandNode->GetNamedChild( "MapToPixelXForm" );
if( poXFormHeader == NULL )
{
poXFormHeader = new HFAEntry( hHFA, "MapToPixelXForm",
"Exfr_GenericXFormHeader", poBandNode );
poXFormHeader->MakeData( 23 );
poXFormHeader->SetPosition();
poXFormHeader->SetStringField( "titleList.string", "Affine" );
}
/* -------------------------------------------------------------------- */
/* Loop over XForms. */
/* -------------------------------------------------------------------- */
for( int iXForm = 0; iXForm < nXFormCount; iXForm++ )
{
Efga_Polynomial *psForward = *ppasPolyListForward + iXForm;
CPLString osXFormName;
osXFormName.Printf( "XForm%d", iXForm );
HFAEntry *poXForm = poXFormHeader->GetNamedChild( osXFormName );
if( poXForm == NULL )
{
poXForm = new HFAEntry( hHFA, osXFormName, "Efga_Polynomial",
poXFormHeader );
poXForm->MakeData( 136 );
poXForm->SetPosition();
}
poXForm->SetIntField( "order", 1 );
poXForm->SetIntField( "numdimtransform", 2 );
poXForm->SetIntField( "numdimpolynomial", 2 );
poXForm->SetIntField( "termcount", 3 );
poXForm->SetIntField( "exponentlist[0]", 0 );
poXForm->SetIntField( "exponentlist[1]", 0 );
poXForm->SetIntField( "exponentlist[2]", 1 );
poXForm->SetIntField( "exponentlist[3]", 0 );
poXForm->SetIntField( "exponentlist[4]", 0 );
poXForm->SetIntField( "exponentlist[5]", 1 );
poXForm->SetIntField( "polycoefmtx[-3]", EPT_f64 );
poXForm->SetIntField( "polycoefmtx[-2]", 2 );
poXForm->SetIntField( "polycoefmtx[-1]", 2 );
poXForm->SetDoubleField( "polycoefmtx[0]",
psForward->polycoefmtx[0] );
poXForm->SetDoubleField( "polycoefmtx[1]",
psForward->polycoefmtx[1] );
poXForm->SetDoubleField( "polycoefmtx[2]",
psForward->polycoefmtx[2] );
poXForm->SetDoubleField( "polycoefmtx[3]",
psForward->polycoefmtx[3] );
poXForm->SetIntField( "polycoefvector[-3]", EPT_f64 );
poXForm->SetIntField( "polycoefvector[-2]", 1 );
poXForm->SetIntField( "polycoefvector[-1]", 2 );
poXForm->SetDoubleField( "polycoefvector[0]",
psForward->polycoefvector[0] );
poXForm->SetDoubleField( "polycoefvector[1]",
psForward->polycoefvector[1] );
}
return CE_None;
}
/************************************************************************/
/* HFAReadCameraModel() */
/************************************************************************/
char **HFAReadCameraModel( HFAHandle hHFA )
{
if( hHFA->nBands == 0 )
return NULL;
/* -------------------------------------------------------------------- */
/* Get the camera model node, and confirm it's type. */
/* -------------------------------------------------------------------- */
HFAEntry *poXForm;
poXForm =
hHFA->papoBand[0]->poNode->GetNamedChild( "MapToPixelXForm.XForm0" );
if( poXForm == NULL )
return NULL;
if( !EQUAL(poXForm->GetType(),"Camera_ModelX") )
return NULL;
/* -------------------------------------------------------------------- */
/* Convert the values to metadata. */
/* -------------------------------------------------------------------- */
const char *pszValue;
int i;
char **papszMD = NULL;
static const char *apszFields[] = {
"direction", "refType", "demsource", "PhotoDirection", "RotationSystem",
"demfilename", "demzunits",
"forSrcAffine[0]", "forSrcAffine[1]", "forSrcAffine[2]",
"forSrcAffine[3]", "forSrcAffine[4]", "forSrcAffine[5]",
"forDstAffine[0]", "forDstAffine[1]", "forDstAffine[2]",
"forDstAffine[3]", "forDstAffine[4]", "forDstAffine[5]",
"invSrcAffine[0]", "invSrcAffine[1]", "invSrcAffine[2]",
"invSrcAffine[3]", "invSrcAffine[4]", "invSrcAffine[5]",
"invDstAffine[0]", "invDstAffine[1]", "invDstAffine[2]",
"invDstAffine[3]", "invDstAffine[4]", "invDstAffine[5]",
"z_mean", "lat0", "lon0",
"coeffs[0]", "coeffs[1]", "coeffs[2]",
"coeffs[3]", "coeffs[4]", "coeffs[5]",
"coeffs[6]", "coeffs[7]", "coeffs[8]",
"LensDistortion[0]", "LensDistortion[1]", "LensDistortion[2]",
NULL };
for( i = 0; apszFields[i] != NULL; i++ )
{
pszValue = poXForm->GetStringField( apszFields[i] );
if( pszValue == NULL )
pszValue = "";
papszMD = CSLSetNameValue( papszMD, apszFields[i], pszValue );
}
/* -------------------------------------------------------------------- */
/* Create a pseudo-entry for the MIFObject with the */
/* outputProjection. */
/* -------------------------------------------------------------------- */
HFAEntry *poProjInfo = HFAEntry::BuildEntryFromMIFObject( poXForm, "outputProjection" );
if (poProjInfo)
{
/* -------------------------------------------------------------------- */
/* Fetch the datum. */
/* -------------------------------------------------------------------- */
Eprj_Datum sDatum;
memset( &sDatum, 0, sizeof(sDatum));
sDatum.datumname =
(char *) poProjInfo->GetStringField("earthModel.datum.datumname");
sDatum.type = (Eprj_DatumType) poProjInfo->GetIntField(
"earthModel.datum.type");
for( i = 0; i < 7; i++ )
{
char szFieldName[60];
sprintf( szFieldName, "earthModel.datum.params[%d]", i );
sDatum.params[i] = poProjInfo->GetDoubleField(szFieldName);
}
sDatum.gridname = (char *)
poProjInfo->GetStringField("earthModel.datum.gridname");
/* -------------------------------------------------------------------- */
/* Fetch the projection parameters. */
/* -------------------------------------------------------------------- */
Eprj_ProParameters sPro;
memset( &sPro, 0, sizeof(sPro) );
sPro.proType = (Eprj_ProType) poProjInfo->GetIntField("projectionObject.proType");
sPro.proNumber = poProjInfo->GetIntField("projectionObject.proNumber");
sPro.proExeName = (char *) poProjInfo->GetStringField("projectionObject.proExeName");
sPro.proName = (char *) poProjInfo->GetStringField("projectionObject.proName");
sPro.proZone = poProjInfo->GetIntField("projectionObject.proZone");
for( i = 0; i < 15; i++ )
{
char szFieldName[40];
sprintf( szFieldName, "projectionObject.proParams[%d]", i );
sPro.proParams[i] = poProjInfo->GetDoubleField(szFieldName);
}
/* -------------------------------------------------------------------- */
/* Fetch the spheroid. */
/* -------------------------------------------------------------------- */
sPro.proSpheroid.sphereName = (char *)
poProjInfo->GetStringField("earthModel.proSpheroid.sphereName");
sPro.proSpheroid.a = poProjInfo->GetDoubleField("earthModel.proSpheroid.a");
sPro.proSpheroid.b = poProjInfo->GetDoubleField("earthModel.proSpheroid.b");
sPro.proSpheroid.eSquared =
poProjInfo->GetDoubleField("earthModel.proSpheroid.eSquared");
sPro.proSpheroid.radius =
poProjInfo->GetDoubleField("earthModel.proSpheroid.radius");
/* -------------------------------------------------------------------- */
/* Fetch the projection info. */
/* -------------------------------------------------------------------- */
char *pszProjection;
// poProjInfo->DumpFieldValues( stdout, "" );
pszProjection = HFAPCSStructToWKT( &sDatum, &sPro, NULL, NULL );
if( pszProjection )
{
papszMD =
CSLSetNameValue( papszMD, "outputProjection", pszProjection );
CPLFree( pszProjection );
}
delete poProjInfo;
}
/* -------------------------------------------------------------------- */
/* Fetch the horizontal units. */
/* -------------------------------------------------------------------- */
pszValue = poXForm->GetStringField( "outputHorizontalUnits.string" );
if( pszValue == NULL )
pszValue = "";
papszMD = CSLSetNameValue( papszMD, "outputHorizontalUnits", pszValue );
/* -------------------------------------------------------------------- */
/* Fetch the elevationinfo. */
/* -------------------------------------------------------------------- */
HFAEntry *poElevInfo = HFAEntry::BuildEntryFromMIFObject( poXForm, "outputElevationInfo" );
if ( poElevInfo )
{
//poElevInfo->DumpFieldValues( stdout, "" );
if( poElevInfo->GetDataSize() != 0 )
{
static const char *apszEFields[] = {
"verticalDatum.datumname",
"verticalDatum.type",
"elevationUnit",
"elevationType",
NULL };
for( i = 0; apszEFields[i] != NULL; i++ )
{
pszValue = poElevInfo->GetStringField( apszEFields[i] );
if( pszValue == NULL )
pszValue = "";
papszMD = CSLSetNameValue( papszMD, apszEFields[i], pszValue );
}
}
delete poElevInfo;
}
return papszMD;
}
/************************************************************************/
/* HFASetGeoTransform() */
/* */
/* Set a MapInformation and XForm block. Allows for rotated */
/* and shared geotransforms. */
/************************************************************************/
CPLErr HFASetGeoTransform( HFAHandle hHFA,
const char *pszProName,
const char *pszUnits,
double *padfGeoTransform )
{
/* -------------------------------------------------------------------- */
/* Write MapInformation. */
/* -------------------------------------------------------------------- */
int nBand;
for( nBand = 1; nBand <= hHFA->nBands; nBand++ )
{
HFAEntry *poBandNode = hHFA->papoBand[nBand-1]->poNode;
HFAEntry *poMI = poBandNode->GetNamedChild( "MapInformation" );
if( poMI == NULL )
{
poMI = new HFAEntry( hHFA, "MapInformation",
"Eimg_MapInformation", poBandNode );
poMI->MakeData( 18 + strlen(pszProName) + strlen(pszUnits) );
poMI->SetPosition();
}
poMI->SetStringField( "projection.string", pszProName );
poMI->SetStringField( "units.string", pszUnits );
}
/* -------------------------------------------------------------------- */
/* Write XForm. */
/* -------------------------------------------------------------------- */
Efga_Polynomial sForward, sReverse;
double adfAdjTransform[6], adfRevTransform[6];
// Offset by half pixel.
memcpy( adfAdjTransform, padfGeoTransform, sizeof(double) * 6 );
adfAdjTransform[0] += adfAdjTransform[1] * 0.5;
adfAdjTransform[0] += adfAdjTransform[2] * 0.5;
adfAdjTransform[3] += adfAdjTransform[4] * 0.5;
adfAdjTransform[3] += adfAdjTransform[5] * 0.5;
// Invert
HFAInvGeoTransform( adfAdjTransform, adfRevTransform );
// Assign to polynomial object.
sForward.order = 1;
sForward.polycoefvector[0] = adfRevTransform[0];
sForward.polycoefmtx[0] = adfRevTransform[1];
sForward.polycoefmtx[1] = adfRevTransform[4];
sForward.polycoefvector[1] = adfRevTransform[3];
sForward.polycoefmtx[2] = adfRevTransform[2];
sForward.polycoefmtx[3] = adfRevTransform[5];
sReverse = sForward;
Efga_Polynomial *psForward=&sForward, *psReverse=&sReverse;
return HFAWriteXFormStack( hHFA, 0, 1, &psForward, &psReverse );
}
/************************************************************************/
/* HFARenameReferences() */
/* */
/* Rename references in this .img file from the old basename to */
/* a new basename. This should be passed on to .aux and .rrd */
/* files and should include references to .aux, .rrd and .ige. */
/************************************************************************/
CPLErr HFARenameReferences( HFAHandle hHFA,
const char *pszNewBase,
const char *pszOldBase )
{
/* -------------------------------------------------------------------- */
/* Handle RRDNamesList updates. */
/* -------------------------------------------------------------------- */
size_t iNode;
std::vector<HFAEntry*> apoNodeList =
hHFA->poRoot->FindChildren( "RRDNamesList", NULL );
for( iNode = 0; iNode < apoNodeList.size(); iNode++ )
{
HFAEntry *poRRDNL = apoNodeList[iNode];
std::vector<CPLString> aosNL;
// Collect all the existing names.
int i, nNameCount = poRRDNL->GetFieldCount( "nameList" );
CPLString osAlgorithm = poRRDNL->GetStringField("algorithm.string");
for( i = 0; i < nNameCount; i++ )
{
CPLString osFN;
osFN.Printf( "nameList[%d].string", i );
aosNL.push_back( poRRDNL->GetStringField(osFN) );
}
// Adjust the names to the new form.
for( i = 0; i < nNameCount; i++ )
{
if( strncmp(aosNL[i],pszOldBase,strlen(pszOldBase)) == 0 )
{
CPLString osNew = pszNewBase;
osNew += aosNL[i].c_str() + strlen(pszOldBase);
aosNL[i] = osNew;
}
}
// try to make sure the RRDNamesList is big enough to hold the
// adjusted name list.
if( strlen(pszNewBase) > strlen(pszOldBase) )
{
CPLDebug( "HFA", "Growing RRDNamesList to hold new names" );
poRRDNL->MakeData( poRRDNL->GetDataSize()
+ nNameCount * (strlen(pszNewBase) - strlen(pszOldBase)) );
}
// Initialize the whole thing to zeros for a clean start.
memset( poRRDNL->GetData(), 0, poRRDNL->GetDataSize() );
// Write the updates back to the file.
poRRDNL->SetStringField( "algorithm.string", osAlgorithm );
for( i = 0; i < nNameCount; i++ )
{
CPLString osFN;
osFN.Printf( "nameList[%d].string", i );
poRRDNL->SetStringField( osFN, aosNL[i] );
}
}
/* -------------------------------------------------------------------- */
/* spill file references. */
/* -------------------------------------------------------------------- */
apoNodeList =
hHFA->poRoot->FindChildren( "ExternalRasterDMS", "ImgExternalRaster" );
for( iNode = 0; iNode < apoNodeList.size(); iNode++ )
{
HFAEntry *poERDMS = apoNodeList[iNode];
if( poERDMS == NULL )
continue;
// Fetch all existing values.
CPLString osFileName = poERDMS->GetStringField("fileName.string");
GInt32 anValidFlagsOffset[2], anStackDataOffset[2];
GInt32 nStackCount, nStackIndex;
anValidFlagsOffset[0] =
poERDMS->GetIntField( "layerStackValidFlagsOffset[0]" );
anValidFlagsOffset[1] =
poERDMS->GetIntField( "layerStackValidFlagsOffset[1]" );
anStackDataOffset[0] =
poERDMS->GetIntField( "layerStackDataOffset[0]" );
anStackDataOffset[1] =
poERDMS->GetIntField( "layerStackDataOffset[1]" );
nStackCount = poERDMS->GetIntField( "layerStackCount" );
nStackIndex = poERDMS->GetIntField( "layerStackIndex" );
// Update the filename.
if( strncmp(osFileName,pszOldBase,strlen(pszOldBase)) == 0 )
{
CPLString osNew = pszNewBase;
osNew += osFileName.c_str() + strlen(pszOldBase);
osFileName = osNew;
}
// Grow the node if needed.
if( strlen(pszNewBase) > strlen(pszOldBase) )
{
CPLDebug( "HFA", "Growing ExternalRasterDMS to hold new names" );
poERDMS->MakeData( poERDMS->GetDataSize()
+ (strlen(pszNewBase) - strlen(pszOldBase)) );
}
// Initialize the whole thing to zeros for a clean start.
memset( poERDMS->GetData(), 0, poERDMS->GetDataSize() );
// Write it all out again, this may change the size of the node.
poERDMS->SetStringField( "fileName.string", osFileName );
poERDMS->SetIntField( "layerStackValidFlagsOffset[0]",
anValidFlagsOffset[0] );
poERDMS->SetIntField( "layerStackValidFlagsOffset[1]",
anValidFlagsOffset[1] );
poERDMS->SetIntField( "layerStackDataOffset[0]",
anStackDataOffset[0] );
poERDMS->SetIntField( "layerStackDataOffset[1]",
anStackDataOffset[1] );
poERDMS->SetIntField( "layerStackCount", nStackCount );
poERDMS->SetIntField( "layerStackIndex", nStackIndex );
}
/* -------------------------------------------------------------------- */
/* DependentFile */
/* -------------------------------------------------------------------- */
apoNodeList =
hHFA->poRoot->FindChildren( "DependentFile", "Eimg_DependentFile" );
for( iNode = 0; iNode < apoNodeList.size(); iNode++ )
{
CPLString osFileName = apoNodeList[iNode]->
GetStringField("dependent.string");
// Grow the node if needed.
if( strlen(pszNewBase) > strlen(pszOldBase) )
{
CPLDebug( "HFA", "Growing DependentFile to hold new names" );
apoNodeList[iNode]->MakeData( apoNodeList[iNode]->GetDataSize()
+ (strlen(pszNewBase)
- strlen(pszOldBase)) );
}
// Update the filename.
if( strncmp(osFileName,pszOldBase,strlen(pszOldBase)) == 0 )
{
CPLString osNew = pszNewBase;
osNew += osFileName.c_str() + strlen(pszOldBase);
osFileName = osNew;
}
apoNodeList[iNode]->SetStringField( "dependent.string", osFileName );
}
return CE_None;
}
| mit |
xDShot/csgo_knives_sweps | lua/pointshop/items/weapons/csgo_karambit_gamma_doppler.lua | 479 | ITEM.Name = "Karambit Knife" .. " | " .. "Gamma Doppler"
ITEM.Price = 20000
ITEM.Model = "models/weapons/w_csgo_karambit.mdl"
ITEM.Skin = 18
ITEM.WeaponClass = "csgo_karambit_gamma_doppler"
function ITEM:OnEquip(ply)
ply:Give(self.WeaponClass)
end
function ITEM:OnBuy(ply)
ply:Give(self.WeaponClass)
ply:SelectWeapon(self.WeaponClass)
end
function ITEM:OnSell(ply)
ply:StripWeapon(self.WeaponClass)
end
function ITEM:OnHolster(ply)
ply:StripWeapon(self.WeaponClass)
end
| mit |
mximos/openproject-heroku | test/integration/api_test/news_test.rb | 3076 | #-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2013 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
require File.expand_path('../../../test_helper', __FILE__)
class ApiTest::NewsTest < ActionDispatch::IntegrationTest
fixtures :all
def setup
Setting.rest_api_enabled = '1'
end
context "GET /api/v1/news" do
context ".xml" do
should "return news" do
get '/api/v1/news.xml'
assert_tag :tag => 'news',
:attributes => {:type => 'array'},
:child => {
:tag => 'news',
:child => {
:tag => 'id',
:content => '2'
}
}
end
end
context ".json" do
should "return news" do
get '/api/v1/news.json'
json = ActiveSupport::JSON.decode(response.body)
assert_kind_of Hash, json
assert_kind_of Array, json['news']
assert_kind_of Hash, json['news'].first
assert_equal 2, json['news'].first['id']
end
end
end
context "GET /api/v1/projects/:project_id/news" do
context ".xml" do
should_allow_api_authentication(:get, "/api/v1/projects/onlinestore/news.xml")
should "return news" do
get '/api/v1/projects/ecookbook/news.xml'
assert_tag :tag => 'news',
:attributes => {:type => 'array'},
:child => {
:tag => 'news',
:child => {
:tag => 'id',
:content => '2'
}
}
end
end
context ".json" do
should_allow_api_authentication(:get, "/api/v1/projects/onlinestore/news.json")
should "return news" do
get '/api/v1/projects/ecookbook/news.json'
json = ActiveSupport::JSON.decode(response.body)
assert_kind_of Hash, json
assert_kind_of Array, json['news']
assert_kind_of Hash, json['news'].first
assert_equal 2, json['news'].first['id']
end
end
end
end
| mit |
madmaw/mvp.ts | mvp.ts/src/main/ts/Animation/IAnimationStateChangeListener.ts | 162 | module TS.Animation {
export interface IAnimationStateChangeListener {
(source: IAnimation, changeEvent: AnimationStateChangeEvent): void ;
}
} | mit |
AdityaHegde/ember-array-modifier | addon/array-modifier-groups/ArrayModifierGroup.js | 1409 | import Ember from "ember";
import ArrayModifierTypes from "../array-modifier-types/index";
import EmberObjectUtils from "ember-object-utils";
/**
* Basic array modifier group.
*
* @class ArrayModifier.ArrayModifierGroup
* @module ember-array-modifier
* @submodule ember-array-modifier-groups
*/
export default Ember.Object.extend(EmberObjectUtils.ObjectWithArrayMixin, {
type : "basic",
/**
* Array modifiers present in the group. Use object while creating.
*
* @property arrayModifiers
* @type Array
*/
arrayModifiers : EmberObjectUtils.hasMany(ArrayModifierTypes.ArrayModifiersMap, "type"),
arrayProps : ['arrayModifiers'],
/**
* Priority to run this modifier group
*
* @property priority
* @type Number
* @default 5
*/
priority : 5,
idx : 0,
/**
* Method that returns whether an item can be added or not.
*
* @method canAdd
* @param {Class} item Item that is to be checked whether it can be added or not.
* @return {Boolean}
*/
canAdd : function(/*item*/) {
return true;
},
/**
* Method called to modify an entire array.
*
* @method modify
* @param {Array} array The array to modify.
*/
modify : function(array) {
var arrayModifiers = this.get("arrayModifiers");
for(var i = 0; i < arrayModifiers.length; i++) {
array = arrayModifiers[i].modify(array);
}
return array;
},
});
| mit |
eliace/ergojs-site | samples/core/widget/layout/layout-autoheight-v.js | 467 |
var w = $.ergo({
etype: 'box',
renderTo: '#sample',
defaultItem: {
$title: {
},
$content: {
height: 200,
cls: 'my-widget',
items: [{
text: '1'
}, {
text: '2'
}]
},
set: {
'text': function(v) { this.$title.opt('text', v); }
}
},
items: [{
text: 'До:'
}, {
text: 'После:',
$content: {
defaultItem: {
autoHeight: true
}
}
}]
});
// обновляем компоновку
w._layoutChanged();
| mit |
romeOz/rock-route | src/RouteException.php | 164 | <?php
namespace rock\route;
use rock\base\BaseException;
class RouteException extends BaseException
{
const UNKNOWN_FORMAT = 'Unknown format: {format}.';
} | mit |
mplaine/xformsdb | webapps/xformsdb/weather/src/fi/tkk/media/widgets/weather/handler/WeatherHandler.java | 5096 | package fi.tkk.media.widgets.weather.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nu.xom.Builder;
import nu.xom.Document;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import fi.tkk.media.widgets.weather.servlet.WeatherServlet;
import fi.tkk.tml.xformsdb.core.Constants;
import fi.tkk.tml.xformsdb.error.HandlerException;
import fi.tkk.tml.xformsdb.error.XMLException;
import fi.tkk.tml.xformsdb.handler.ResponseHandler;
import fi.tkk.tml.xformsdb.util.IOUtils;
import fi.tkk.tml.xformsdb.util.StringUtils;
import fi.tkk.tml.xformsdb.util.XMLUtils;
/**
* Handle weather requests.
*
*
* @author Markku Laine
* @version 1.0 Created on November 25, 2009
*/
public class WeatherHandler extends ResponseHandler {
// PRIVATE STATIC FINAL VARIABLES
private static final Logger logger = Logger.getLogger( WeatherHandler.class );
// PUBLIC CONSTURCTORS
public WeatherHandler() {
super();
logger.log( Level.DEBUG, "Constructor has been called." );
}
// PRIVATE METHODS
// PUBLIC METHODS
public void handle( WeatherServlet weatherServlet, HttpServletRequest request, HttpServletResponse response ) throws HandlerException {
logger.log( Level.DEBUG, "Method has been called." );
Builder builder = null;
Document document = null;
String weather = null;
String hl = null;
String uriString = null;
HttpClient httpClient = null;
HttpGet httpGet = null;
HttpResponse httpResponse = null;
HttpEntity httpEntity = null;
StatusLine statusLine = null;
String xmlString = null;
String xmlStringFiltered = null;
try {
// Parse the input stream (XML document)
builder = new Builder();
document = builder.build( request.getInputStream() );
// Retrieve city and language
weather = document.getRootElement().getFirstChildElement( "city" ).getValue(); // Retrieve city
hl = document.getRootElement().getFirstChildElement( "language" ).getValue(); // Retrieve language
// Update the URI string i.e. set the weather and hl parameter values
uriString = "http://www.google.com/ig/api?weather={weather}&hl={hl}";
uriString = uriString.replace( "{weather}", weather );
uriString = uriString.replace( "{hl}", hl );
// Create an instance of HttpClient
httpClient = new DefaultHttpClient();
// Create an instance of HttpGet
httpGet = new HttpGet( StringUtils.toSafeASCIIString( uriString ) ); // Important for encoding the URI correctly!
// Execute the HTTP request
logger.log( Level.DEBUG, "Executing HTTP request: " + httpGet.getURI() );
httpResponse = httpClient.execute( httpGet );
// Retrieve the HTTP response entity
httpEntity = httpResponse.getEntity();
if ( httpEntity != null ) {
// Retrieve the HTTP response status line
statusLine = httpResponse.getStatusLine();
if ( statusLine.getStatusCode() == HttpServletResponse.SC_OK ) {
xmlString = EntityUtils.toString( httpEntity );
}
}
// Ensure that the result does not consist only of the XML declaration
try {
xmlStringFiltered = XMLUtils.filterXMLDeclaration( xmlString );
} catch ( XMLException xmlex ) {
xmlStringFiltered = null;
} catch ( Exception ex ) {
xmlStringFiltered = null;
}
// Select files query did not result any data
if ( xmlString == null || xmlStringFiltered.length() == 0 ) {
throw new HandlerException( 3, "The weather query did not return any data." );
}
// Write the response
super.handle( response, request, Constants.MIME_TYPE_APPLICATION_XML, Constants.XFORMSDB_CONFIG_DEFAULT_ENCODING, Constants.XFORMSDB_CONFIG_DEFAULT_ENCODING, IOUtils.convert( xmlString, Constants.XFORMSDB_CONFIG_DEFAULT_ENCODING ), true );
logger.log( Level.DEBUG, "Result of the weather query:" + Constants.LINE_SEPARATOR + xmlString );
} catch ( ClientProtocolException cpex ) {
throw new HandlerException( 4, "Failed to execute the REST method.", cpex );
} catch ( IOException ioex ) {
throw new HandlerException( 5, "Failed to execute the REST method.", ioex );
} catch ( HandlerException hex ) {
throw hex;
} catch ( Exception ex ) {
throw new HandlerException( 6, "Failed to handle the weather request.", ex );
} finally {
if ( httpClient != null ) {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
}
}
}
} | mit |
gtracy/sms-reminders | main.py | 5912 | import os
import logging
import time
from datetime import date, datetime
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api.taskqueue import Task
from twilio import twiml
from twilio import TwilioRestException
from twilio.rest import TwilioRestClient
import configuration
import timezone
#
# Valid request formats:
# xx <message> - minutes until reminder
# xxd <message> - days until reminder
# x:xx[ap] <message> - time of current day (am or pm)
#
shortcuts = { 'a':5, 'd':10, 'g':15, 'j':30, 'm':60 }
class RequestLog(db.Model):
phone = db.StringProperty(indexed=True)
date = db.DateTimeProperty(auto_now_add=True)
request = db.StringProperty()
## end
class ReminderTaskHandler(webapp.RequestHandler):
def post(self):
phone = self.request.get('phone')
msg = self.request.get('msg')
try:
client = TwilioRestClient(configuration.TWILIO_ACCOUNT_SID,
configuration.TWILIO_AUTH_TOKEN)
logging.debug('sending SMS - %s - to %s' % (msg,phone))
message = client.sms.messages.create(to=phone,
from_=configuration.TWILIO_CALLER_ID,
body=msg)
except TwilioRestException,te:
logging.error('Unable to send SMS message! %s' % te)
## end
class MainHandler(webapp.RequestHandler):
def post(self):
# who called? and what did they say?
phone = self.request.get("From")
body = self.request.get("Body")
logging.debug('New request from %s : %s' % (phone, body))
createLog(phone,body)
cmd = body.split()
# assume everything to the left of the first space is the command, and
# everything to the right of the first space is the reminder message
command = cmd[0]
logging.debug('new request command is %s' % command)
msg = ''
for m in cmd:
if m == command:
continue
msg += m + ' '
# parse the command
# a shortcut code request
if command.isdigit() == False and len(command) == 1:
# single letters are default minute values
# a = 5 d = 10 g = 15 j = 30 m = 60
command = command.lower()
if command not in shortcuts:
response = 'illegal shortcut code - a, d, g, j, m are the only valid shortcuts'
else:
mins = shortcuts[command]
createTask(phone, msg, mins * 60)
response = "got it. we'll remind you in %s minutes" % mins
# a minute request
elif command.isdigit():
# create a task in <command> minutes
createTask(phone, msg, int(command)*60)
response = "got it. we'll remind you in %s minutes" % command
# an hour request
elif command.lower().find('h') > 0:
# create a task in a certain number of days
hours = command.lower().split('h')[0]
sec = int(hours) * 60 * 60
createTask(phone, msg, sec)
response = "got it. we'll remind you in %s day" % hours
# a day request
elif command.lower().find('d') > 0:
# create a task in a certain number of days
days = command.lower().split('d')[0]
sec = int(days) * 24 * 60 * 60
createTask(phone, msg, sec)
response = "got it. we'll remind you in %s day" % days
# a specific time request
elif command.find(':') > 0:
# create a task at a specified time
local = timezone.LocalTimezone()
tod = datetime.strptime(command, "%H:%M")
eta = datetime.combine(date.today(), tod.time()).replace(tzinfo=local)
now = datetime.now(local)
delta = eta - now
createTask(phone, msg, delta.seconds)
response = "got it. we'll remind you at %s" % eta
logging.debug('ETA : %s' % eta)
logging.debug('... now : %s' % now)
logging.debug('... delta : %s' % delta.seconds)
else:
response = '<minutes>, <hours>h, <days>d or hh:mm <reminder-message>'
# ignore positive feedback on new requests
if response.lower().find('got it') == -1:
self.response.out.write(smsResponse(response))
else:
logging.debug('NOT sending response to caller : %s' % response)
return
## end MainHandler
class IndexHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("You've wondered to a strange place my friend. <a href=http://twitter.com/gregtracy>@gregtracy</a>")
## end IndexHandler
def smsResponse(msg):
r = twiml.Response()
r.append(twiml.Sms(msg))
return r
def createTask(phone,msg,sec):
logging.debug("Creating new task to fire in %s minutes" % str(int(sec)/60))
task = Task(url='/reminder',
params={'phone':phone,'msg':msg},
countdown=sec)
task.add('reminders')
# end
def createLog(phone,request):
log = RequestLog()
log.phone = phone
log.request = request
log.put()
def main():
logging.getLogger().setLevel(logging.DEBUG)
application = webapp.WSGIApplication([('/sms', MainHandler),
('/test', MainHandler),
('/reminder', ReminderTaskHandler),
('/.*', IndexHandler)
],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| mit |
goldsborough/ig | ig/serve.py | 2378 | '''The server that serves the web visualization.'''
import json
import logging
import os
import shutil
import socket
import webbrowser
from ig import paths
try:
import socketserver
import http.server as http
except ImportError:
import SocketServer as socketserver
import SimpleHTTPServer as http
log = logging.getLogger(__name__)
class Server(object):
def __init__(self, directory):
'''
Constructor.
Args:
directory: The directory to serve from.
'''
self.delete_directory = directory is None
self.directory = paths.create_directory(directory)
def run(self, open_immediately, port):
'''
Serves the `www` directory.
Args:
open_immediately: Whether to open the web browser immediately
port: The port at which to serve the graph
'''
os.chdir(self.directory)
handler = http.SimpleHTTPRequestHandler
handler.extensions_map.update({
'.webapp': 'application/x-web-app-manifest+json',
})
server = socketserver.TCPServer(('', port), handler)
server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
address = 'http://localhost:{0}/graph.html'.format(port)
log.info('Serving at %s', address)
if open_immediately:
log.debug('Opening webbrowser')
webbrowser.open(address)
server.serve_forever()
def write(self, payload):
'''
Writes the given JSON representation to the served location.
Args:
payload: The playlod to JSONify and store.
'''
path = os.path.join(self.directory, 'graph.json')
with open(path, 'w') as graph_file:
graph_file.write(json.dumps(payload, indent=4))
log.debug('Wrote graph file to {0}'.format(path))
def cleanup(self):
if self.delete_directory:
assert self.directory is not None
shutil.rmtree(self.directory, ignore_errors=True)
log.debug('Deleted directory %s', self.directory)
def __enter__(self):
return self
def __exit__(self, error_type, error_value, traceback):
self.cleanup()
if error_type == KeyboardInterrupt:
return True # Supresses the exception
# Any other exception is propagated up
| mit |
starikov-kirill/symfonyljms | src/Ljms/GeneralBundle/Helper/EncryptPasswordHelper.php | 917 | <?php
namespace Ljms\GeneralBundle\Helper;
class EncryptPasswordHelper {
private $container;
public function __construct($container)
{
$this->container = $container;
}
public function encryptPassword($user, $method)
{
$container = $this->container;
try
{
$factory = $container->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
if ($method == 'edit')
{
$password = $encoder->encodePassword($user->getNewpassword(), $user->getSalt());
$user->setNewpassword($password);
} elseif ($method == 'add')
{
$password = $encoder->encodePassword($user->getpassword(), $user->getSalt());
}
$user->setPassword($password);
return $password;
} catch(Exception $e)
{
return new Response($e);
}
}
} | mit |
alketii/MGreet | main.py | 1759 | import socket , datetime, time , sqlite3
nick = "MGreet"
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect(("irc.freenode.net",6667))
irc.send("NICK "+nick+"\r\n")
irc.send("USER "+nick+" MGreet MGreet :MGreet\r\n")
irc.send("JOIN #mgreet\r\n")
con = sqlite3.connect('mgbot.sql')
con.text_factory = str
cur = con.cursor()
while True:
data = irc.recv(4096)
print data
for line in data.split('\n'):
word = line.split(' ')
if len(word) == 3:
if word[1] == "JOIN":
player = word[0].split('!')[0][1:]
clean_player = player.split('_')
if len(clean_player) == 3:
clean_player = clean_player[1]
if player[:3] == "MG_" and player[3:9] == "newbie":
irc.send("PRIVMSG #megaglest-lobby :Hi "+player+" , Welcome to Megaglest .Plesae consider changing your nick at Menu > Options ,also try playing tutorials and some scenarios first if you didn't already. If you did , please wait for someone to join.\r\n")
elif player[:3] == "MG_" and player[3:9] != "newbie":
date = datetime.datetime.now().strftime("%H:%M:%S")
cur.execute("SELECT * FROM players WHERE nick=?",[clean_player])
row = cur.fetchone()
if row:
joins = row[1]+1
con.execute("UPDATE players SET joins=? , last_join=? WHERE nick=? ",[joins,clean_player,date])
else:
cur.execute("SELECT last_join FROM players ORDER BY last_join DESC LIMIT 1")
last_join = cur.fetchone()
irc.send("PRIVMSG #megaglest-lobby :Hi "+player+" , The last player online was seen at "+last_join[0]+" .\r\n")
con.execute("INSERT INTO players VALUES(?,?,?)",[date,clean_player,1])
con.commit()
elif len(word) == 2:
if word[0] == "PING":
irc.send("PONG "+word[1][1:])
time.sleep(1) | mit |
isaachermens/QuickPower | QuickPower/Properties/Settings.Designer.cs | 2074 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace QuickPower.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("00000000-0000-0000-0000-000000000000")]
public global::System.Guid ChargingScheme {
get {
return ((global::System.Guid)(this["ChargingScheme"]));
}
set {
this["ChargingScheme"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("00000000-0000-0000-0000-000000000000")]
public global::System.Guid DischargingScheme {
get {
return ((global::System.Guid)(this["DischargingScheme"]));
}
set {
this["DischargingScheme"] = value;
}
}
}
}
| mit |
DragonSpark/Framework | DragonSpark/Diagnostics/Logging/Text/OutputTemplate.cs | 299 | namespace DragonSpark.Diagnostics.Logging.Text;
public sealed class OutputTemplate : DragonSpark.Text.Text
{
public static OutputTemplate Default { get; } = new OutputTemplate();
OutputTemplate() : base($"{TemplateHeader.Default} ({{SourceContext}}) {{Message}}{{NewLine}}{{Exception}}") {}
} | mit |
nini77/laravelcast | public/js/vueSam.js | 352 | var demo = new Vue({
el: '#demo',
data: {
title: 'todos',
todos: [
{
done: true,
content: 'Learn JavaScript'
},
{
done: false,
content: 'Learn Vue.js'
},
{
done: false,
content: 'Laravel + Learn Vue.js'
}
]
}
})
| mit |
UshalNaidoo/Android-Bubble-Game | app/src/main/java/com/goodguygames/bubblegame/physics/Speed.java | 208 | package com.goodguygames.bubblegame.physics;
public enum Speed {
REVERSE(-1),
STOP(0),
SLOW(2),
NORMAL(5),
FAST(8),
SUPERFAST(11);
public int value;
Speed(int i) {
this.value = i;
}
} | mit |
archan937/rich_i18n | test/tests/core/enriched_string_test.rb | 571 | require File.expand_path(File.join(File.dirname(__FILE__), "..", "test_helper.rb"))
module Core
class EnrichedStringTest < ActiveSupport::TestCase
setup do
I18n.locale = Rich::I18n::Engine.init :nl
end
test "current locale" do
assert_equal I18n.locale, :nl
end
test "to_output" do
Rich::I18n::Engine.enable_enriched_output = true
# assert_equal "<i18n data-value=\"meer\" data-key=\"word.more\" data-derivative_key=\"More\" data-locale=\"nl\" data-i18n_translation=\"Meer\"></i18n>", "More".t.to_output
end
end
end | mit |
inphinit/inphinit | system/application/Config/debug.php | 80 | <?php
return array(
'searcherror' => 'https://duckduckgo.com/?q=%error%'
);
| mit |
nayashooter/ES6_React-Bootstrap | public/jspm_packages/npm/material-ui@0.14.4/lib/svg-icons/device/signal-cellular-null.js | 946 | /* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);
var _svgIcon = require('../../svg-icon');
var _svgIcon2 = _interopRequireDefault(_svgIcon);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var DeviceSignalCellularNull = _react2.default.createClass({
displayName: 'DeviceSignalCellularNull',
mixins: [_reactAddonsPureRenderMixin2.default],
render: function render() {
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M20 6.83V20H6.83L20 6.83M22 2L2 22h20V2z'}));
}
});
exports.default = DeviceSignalCellularNull;
module.exports = exports['default'];
| mit |
Shopify/unity-buy-sdk | Assets/Shopify/Unity/SDK/iOS/iOSWebCheckout.cs | 1098 | #if UNITY_IOS
namespace Shopify.Unity.SDK.iOS {
using System.Runtime.InteropServices;
using System;
using Shopify.Unity.SDK;
class iOSWebCheckout : WebCheckout {
[DllImport("__Internal")]
private static extern void _CheckoutWithWebView(string unityDelegateObjectName, string checkoutURL);
private ShopifyClient _client;
private Cart _cart;
protected override ShopifyClient Client {
get {
return _client;
}
}
protected override Cart Cart {
get {
return _cart;
}
}
public iOSWebCheckout(Cart cart, ShopifyClient client) {
_cart = cart;
_client = client;
}
public override void Checkout(string checkoutURL, CheckoutSuccessCallback success, CheckoutCancelCallback cancelled, CheckoutFailureCallback failure) {
SetupWebCheckoutMessageReceiver(success, cancelled, failure);
_CheckoutWithWebView(GetNativeMessageReceiverName(), checkoutURL);
}
}
}
#endif
| mit |
michaelcullum/yukari | bin/yukari.php | 1298 | <?php
/**
*
*===================================================================
*
* Yukari
*-------------------------------------------------------------------
* @category Yukari
* @package Yukari
* @author Damian Bushong
* @copyright (c) 2009 - 2011 Damian Bushong
* @license MIT License
* @link http://github.com/damianb/yukari
*
*===================================================================
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*
*/
/**
* @ignore
*/
define('YUKARI', dirname(dirname(__FILE__)));
define('YUKARI_PHAR', 'lib/yukari.phar');
define('YUKARI_MIN_PHP', '5.3.0');
define('Codebite\\Yukari\\RUN_PHAR', true);
error_reporting(-1);
// Check running PHP version against the minimum supported PHP version...
if(version_compare(YUKARI_MIN_PHP, PHP_VERSION, '>'))
{
echo sprintf('Yukari requires PHP version %1$s or better, while the currently installed PHP version is %2$s.' . PHP_EOL, YUKARI_MIN_PHP, PHP_VERSION);
exit(1);
}
// If we are running Yukari using the Phar archive, then
if(\Codebite\Yukari\RUN_PHAR === true)
{
require 'phar://' . YUKARI_PHAR . '/Codebite/Yukari/Bootstrap.php';
}
else
{
require YUKARI . '/src/Codebite/Yukari/Bootstrap.php';
}
| mit |
panthomakos/lynx | lib/lynx/pipe/p_open.rb | 359 | require 'lynx/pipe/basic'
module Lynx
module Pipe
class POpen < Basic
def initialize(logger)
@logger = logger
end
def perform(command)
IO.popen(command.to_s) do |io|
while (line = io.gets) do
@logger.info("[Lynx:POpen] #{line}") if @logger
end
end
end
end
end
end
| mit |
tonypeng/FRCDash | Controls/Code/CheckBox.cs | 5584 | ////////////////////////////////////////////////////////////////
// //
// Neoforce Controls //
// //
////////////////////////////////////////////////////////////////
// //
// File: CheckBox.cs //
// //
// Version: 0.7 //
// //
// Date: 11/09/2010 //
// //
// Author: Tom Shane //
// //
////////////////////////////////////////////////////////////////
// //
// Copyright (c) by Tom Shane //
// //
////////////////////////////////////////////////////////////////
#region //// Using /////////////
////////////////////////////////////////////////////////////////////////////
using Microsoft.Xna.Framework;
////////////////////////////////////////////////////////////////////////////
#endregion
namespace TomShane.Neoforce.Controls
{
public class CheckBox: ButtonBase
{
#region //// Consts ////////////
////////////////////////////////////////////////////////////////////////////
private const string skCheckBox = "CheckBox";
private const string lrCheckBox = "Control";
private const string lrChecked = "Checked";
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
private bool state = false;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Properties ////////
////////////////////////////////////////////////////////////////////////////
public virtual bool Checked
{
get
{
return state;
}
set
{
state = value;
Invalidate();
if (!Suspended) OnCheckedChanged(new EventArgs());
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Events ////////////
////////////////////////////////////////////////////////////////////////////
public event EventHandler CheckedChanged;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Construstors //////
////////////////////////////////////////////////////////////////////////////
public CheckBox(Manager manager): base(manager)
{
CheckLayer(Skin, lrChecked);
Width = 64;
Height = 16;
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Methods ///////////
////////////////////////////////////////////////////////////////////////////
public override void Init()
{
base.Init();
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected internal override void InitSkin()
{
base.InitSkin();
Skin = new SkinControl(Manager.Skin.Controls[skCheckBox]);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected override void DrawControl(Renderer renderer, Rectangle rect, GameTime gameTime)
{
SkinLayer layer = Skin.Layers[lrChecked];
SkinText font = Skin.Layers[lrChecked].Text;
if (!state)
{
layer = Skin.Layers[lrCheckBox];
font = Skin.Layers[lrCheckBox].Text;
}
rect.Width = layer.Width;
rect.Height = layer.Height;
Rectangle rc = new Rectangle(rect.Left + rect.Width + 4, rect.Y, Width - (layer.Width + 4), rect.Height);
renderer.DrawLayer(this, layer, rect);
renderer.DrawString(this, layer, Text, rc, false, 0, 0);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected override void OnClick(EventArgs e)
{
MouseEventArgs ex = (e is MouseEventArgs) ? (MouseEventArgs)e : new MouseEventArgs();
if (ex.Button == MouseButton.Left || ex.Button == MouseButton.None)
{
Checked = !Checked;
}
base.OnClick(e);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected virtual void OnCheckedChanged(EventArgs e)
{
if (CheckedChanged != null) CheckedChanged.Invoke(this, e);
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
}
| mit |
zainbudha/tv-guide | app/episodes/episodes.js | 310 | angular.module('tvGuide.episodes', ['tvGuide.model', 'ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/episodeList/:showName/:showId', {
templateUrl: 'episodes/episodeList.html',
controller: 'EpisodeController',
controllerAs: 'episodeCtrl'
})
}]); | mit |
3runoDesign/setRobot | app/clean-up.php | 3281 | <?php
namespace App;
/*
* Remove default dashboard metaboxes
*/
add_action('wp_dashboard_setup', function () {
remove_action('welcome_panel', 'wp_welcome_panel');
remove_meta_box('dashboard_primary', 'dashboard', 'normal');
remove_meta_box('dashboard_secondary', 'dashboard', 'normal');
remove_meta_box('dashboard_incoming_links', 'dashboard', 'normal');
remove_meta_box('dashboard_quick_press', 'dashboard', 'side');
remove_meta_box('dashboard_recent_drafts', 'dashboard', 'side');
});
/*
* Remove WP logo and comments menu from admin bar
*/
add_action('admin_bar_menu', function ($wp_admin_bar) {
$wp_admin_bar->remove_node('wp-logo');
$wp_admin_bar->remove_node('view-site');
$wp_admin_bar->remove_menu('customize');
$wp_admin_bar->remove_menu('comments');
}, 100);
/*
* Move Yoast SEO metabox to a lower position
*/
add_filter('wpseo_metabox_prio', function () {
return 'low';
});
/*
* Remove the "help" section on top of admin pages
*/
add_filter('contextual_help', function ($old_help, $screen_id, $screen) {
$screen->remove_help_tabs();
return $old_help;
}, 11, 3);
/*
* Remove emojis, clean up the <head> and remove WP default gallery style
*/
add_action('init', function () {
/** Remove emojis */
remove_action('admin_print_styles', 'print_emoji_styles');
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
add_filter('emoji_svg_url', '__return_false');
add_filter('tiny_mce_plugins', function ($plugins) {
return is_array($plugins) ? array_diff($plugins, ['wpemoji']) : [];
});
/** Clean the <head> */
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10);
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'parent_post_rel_link', 10);
remove_action('wp_head', 'rel_canonical', 10);
remove_action('wp_head', 'rest_output_link_wp_head', 10);
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'start_post_rel_link', 10);
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');
remove_action('wp_head', 'wp_shortlink_wp_head', 10);
/** Remove default gallery style */
add_filter('use_default_gallery_style', '__return_false');
});
/*
* Remove recent comment styles from <head>
*/
add_action('widgets_init', function () {
global $wp_widget_factory;
if (isset($wp_widget_factory->widgets['WP_Widget_Recent_Comments'])) {
remove_action(
'wp_head',
[
$wp_widget_factory->widgets['WP_Widget_Recent_Comments'],
'recent_comments_style',
]
);
}
});
/*
* Remove WP version from the <head> and RSS feeds
*/
add_filter('the_generator', '__return_false');
| mit |
javimey/buzz | lib/buzz/notifier.rb | 928 | module Buzz
class Notifier
attr_accessor :buzz_api_key
attr_accessor :buzz_secret_token
attr_accessor :endpoint
DEFAULT_ENDPOINT = 'http://buzzerbox.herokuapp.com/api/track'
def initialize
@endpoint = DEFAULT_ENDPOINT
end
def self.configure
configuration.enabled = true if configuration.enabled.nil?
yield(configuration)
end
def configuration
@configuration ||= Configuration.new
end
def notify(api_key, api_secret, buzz_key, params = {})
begin
parameters = {buzz_key: buzz_key, BUZZBOX_KEY: api_key,BUZZBOX_SECRET: api_secret }
parameters[:data1] = params[0]
response = Net::HTTP.post_form(URI.parse(DEFAULT_ENDPOINT), parameters)
if response.class == Net::HTTPUnauthorized
return {status: 401}
end
return {status: 200}
rescue => e
{status: 401}
end
end
end
end
| mit |
singaporesamara/SOAS-DASHBOARD | app/containers/User/ChangePasswordPage/index.js | 3779 | import React, { PropTypes } from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { merge } from 'lodash';
import { ROUTES } from '../../../constants/routes';
import NonAuthContainer, { FOOTER_LINKS } from '../NonAuthContainer';
import BaseComponent from '../../Base';
import { Button, TextInput, TEXT_INPUT_THEMES, SuccessNotice, Notice } from '../../../components/UIKit';
import { layoutUpdate, validateForm } from '../../../actions/common';
import { LAYOUT_NO_FOOTER } from '../../../constants/common';
import { RULES } from '../../../utils/validation';
import { changePassword } from './actions';
import styles from './styles.scss';
export class ChangePasswordPage extends BaseComponent {
static propTypes = {
page: PropTypes.object.isRequired,
checkword: PropTypes.string,
layoutUpdate: PropTypes.func.isRequired,
validateForm: PropTypes.func.isRequired,
changePassword: PropTypes.func.isRequired,
};
constructor(props, context) {
super(props, context);
this.state = { password: null, passwordConfirmation: null };
this.restorePassword = this.restorePassword.bind(this);
this.onValueChange = this.onValueChange.bind(this);
}
componentWillMount() {
this.props.layoutUpdate(LAYOUT_NO_FOOTER);
}
restorePassword(event) {
const form = { password: this.state.password, passwordConfirmation: this.state.passwordConfirmation };
const rules = { password: RULES.required, passwordConfirmation: merge({}, RULES.required, RULES.equalsTo('password')) };
event.preventDefault();
this.props.validateForm({ form, rules, name: 'changePassword' }, { onSuccess: () => { this.props.changePassword({ password: this.state.password, checkword: this.props.checkword }); } });
}
renderMessage() {
const page = this.props.page.toJS();
const message = 'Your password was successfully changed!';
return page.show.message ? (
<div className={styles.pageMessage}>
<SuccessNotice message={message} />
</div>
) : null;
}
renderForm() {
const page = this.props.page.toJS();
return page.show.form ? (
<div>
<div className={styles.pageTitle}>Change your password</div>
<form className={styles.pageForm} onSubmit={this.restorePassword}>
<div className={styles.pageFormInput}>
<Notice page="changePassword" />
</div>
<div className={styles.pageFormInput}>
<TextInput theme={TEXT_INPUT_THEMES.MATERIAL} type="password" label="PASSWORD" onChange={this.onValueChange('password')} error={page.errors.password} />
</div>
<div className={styles.pageFormInput}>
<TextInput theme={TEXT_INPUT_THEMES.MATERIAL} type="password" label="PASSWORD CONFIRMATION" onChange={this.onValueChange('passwordConfirmation')} error={page.errors.passwordConfirmation} />
</div>
<div className={styles.pageFormButton}>
<Button>Change password</Button>
</div>
</form>
</div>
) : null;
}
render() {
const links = merge({}, FOOTER_LINKS, { right: null, left: { title: 'Already have an account?', url: ROUTES.USER.LOGIN } });
return (
<NonAuthContainer footerLinks={links}>
<Helmet title="Login Page" />
<div className={styles.page}>
{this.renderForm()}
{this.renderMessage()}
</div>
</NonAuthContainer>
);
}
}
function mapStateToProps(state, ownProps) {
const { router } = ownProps;
const { checkword } = router.location.query;
return {
page: state.getIn(['pages', 'changePassword']),
checkword,
};
}
export default connect(mapStateToProps, { layoutUpdate, validateForm, changePassword })(ChangePasswordPage);
| mit |
padamaszek/FrontendDev | src/app/carparts.component.ts | 1369 | import { Component, OnInit } from '@angular/core';
import { Carpart } from './carpart';
import { CarpartService } from './carpart.service';
import { Router } from '@angular/router';
@Component({
selector: 'my-carparts',
templateUrl: './carparts.component.html',
styleUrls: [ './carparts.component.css' ],
providers: [CarpartService]
})
export class CarpartsComponent implements OnInit {
title = 'Tour of Carparts';
carparts: Carpart[];
selectedCarpart: Carpart;
constructor(
private router: Router,
private carpartService: CarpartService) { }
getCarparts(): void {
this.carpartService.getCarparts().then(carparts => this.carparts = carparts);
}
ngOnInit(): void {
this.getCarparts();
}
onSelect(carpart: Carpart): void {
this.selectedCarpart = carpart;
}
gotoDetail(): void {
this.router.navigate(['/detail', this.selectedCarpart.id]);
}
add(name: string): void {
name = name.trim();
if (!name) { return; }
this.carpartService.create(name)
.then(carpart => {
this.carparts.push(carpart);
this.selectedCarpart = null;
});
}
delete(carpart: Carpart): void {
this.carpartService
.delete(carpart.id)
.then(() => {
this.carparts = this.carparts.filter(c => c !== carpart);
if (this.selectedCarpart === carpart) { this.selectedCarpart = null; }
});
}
} | mit |
rickyngk/card-stack-view | src/main/java/R/cardstack/CardStackViewDelegate.java | 506 | package R.cardstack;
import android.view.View;
/**
* Created by duynk on 1/5/16.
*/
public interface CardStackViewDelegate {
void onStarted(CardStackView v);
View onLoadView(CardStackView v, int index);
View onLoadEmptyView(CardStackView v);
int getCount();
void onDrag(CardStackView v, float confidence);
void onActive(CardStackView v, int index);
void onEndOfStack(CardStackView v);
void onOpen(CardStackView v, int index);
void onRollback(CardStackView v);
}
| mit |
myid999/javademo | core/src/main/java/demo/java/v2c01io/FindDirectories/FindDirectories.java | 1144 | package demo.java.v2c01io.FindDirectories;
import java.io.*;
public class FindDirectories {
public static void main(String[] args) {
// if no arguments provided, start at the parent directory
if (args.length == 0)
args = new String[] { "." };
try {
File pathName = new File(args[0]);
String[] fileNames = pathName.list(new ExtensionFilter("txt"));
// String[] fileNames = pathName.list();
// enumerate all files in the directory
for (int i = 0; i < fileNames.length; i++) {
File f = new File(pathName.getPath(), fileNames[i]);
// if the file is again a directory, call the main method
// recursively
System.out.println(f.getCanonicalPath());
if (f.isDirectory()) {
main(new String[] { f.getPath() });
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ExtensionFilter implements FilenameFilter{
private String ext;
public ExtensionFilter(String ext){
this.ext=ext;
}
@Override
public boolean accept(File dir, String name) {
return name.endsWith(this.ext);
}
}
}
| mit |
emartinpi/TypeScript | TS Modulo 5/CookBook/scripts/initializer.ts | 717 | var recipeCategories: RecipeCategories;
var renderer: Renderer = null;
window.onload = () => {
var categoriesSelect = (<HTMLSelectElement> document.getElementById('RecipeCategory'));
categoriesSelect.onchange = () => loadRecipes();
var loader = new RecipeLoader("/JSON/recipeTypes.json");
loader.load();
renderer = new Renderer();
};
function loadRecipes() {
var el = (<HTMLSelectElement> document.getElementById('RecipeCategory'));
try {
var category = recipeCategories.items
.filter(i => i.name === el.value)
.reduce(i => (new BaseRecipeCategory()));
renderer.renderCategory(category);
}
catch (ex) { alert(ex.message) }
}
| mit |
georghinkel/ttc2017smartGrids | solutions/ModelJoin/src/main/java/COSEM/InterfaceClasses/impl/UtilitytablesImpl.java | 746 | /**
*/
package COSEM.InterfaceClasses.impl;
import COSEM.InterfaceClasses.InterfaceClassesPackage;
import COSEM.InterfaceClasses.Utilitytables;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Utilitytables</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class UtilitytablesImpl extends BaseImpl implements Utilitytables {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected UtilitytablesImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return InterfaceClassesPackage.Literals.UTILITYTABLES;
}
} //UtilitytablesImpl
| mit |
xErik/pdfmake-fonts-google | build/script/ofl-folder2/timmana.map.js | 204 | window.pdfMake = window.pdfMake || {}; window.pdfMake.fonts = {"Timmana":{"normal":"Timmana-Regular.ttf","bold":"Timmana-Regular.ttf","italics":"Timmana-Regular.ttf","bolditalics":"Timmana-Regular.ttf"}}; | mit |
gpestana/kapacitor-unit | cmd/kapacitor-unit/main_test.go | 2154 | package main
import (
"log"
"os"
"testing"
)
//Helper function to create an YAML configuration file to be used in the tests
func createConfFile(p string, conf string) {
f, err := os.Create(p)
if err != nil {
log.Fatal("TestConfigLoad: Test setup failed")
}
_, err = f.Write([]byte(conf))
if err != nil {
log.Fatal("TestConfigLoad: Test setup failed")
}
}
func TestConfigValidYAML(t *testing.T) {
p := "./conf.yaml"
c := `
tests:
- name: test1
task_name: "test 1"
db: test
rp: default
expects:
ok: 0
warn: 1
crit: 0
data:
- data 1
- data 2
- name: test2
task_name: "test 2"
db: test
rp: default
data:
- example of data
expects:
ok: 0
warn: 0
crit: 1
`
defer os.Remove(p)
createConfFile(p, c)
tests, err := testConfig(p)
if err != nil {
t.Error(err)
}
if tests[0].Name != "test1" {
t.Error("Test name not parsed as expected")
}
if tests[0].Data[1] != "data 2" {
t.Error("Data not parsed as expected")
}
//if cmap.Tests[1].Expects != "critical" {
// t.Error("Expects not parsed as expected")
//}
}
func TestConfigInvalidYAML(t *testing.T) {
p := "./conf2.yaml"
c := "not yaml"
defer os.Remove(p)
createConfFile(p, c)
_, err := testConfig(p)
if err == nil {
t.Error("YAML is invalid, there should be an error")
}
}
func TestConfigLoadWrongPath(t *testing.T) {
_, err := testConfig("err")
if err == nil {
t.Error("Wrong path shuld return error")
}
}
func TestInitTests(t *testing.T) {
p := "./conf.yaml"
c := `
tests:
- name: "alert 2"
task_name: alert_2.tick
db: test
rp: default
expects:
ok: 0
warn: 1
crit: 0
data:
- data 1
- data 2
- name: "alert 2 - another"
task_name: "alert_2.tick"
db: test
rp: default
data:
- example of data
expects:
ok: 0
warn: 0
crit: 1
`
defer os.Remove(p)
createConfFile(p, c)
tests, err := testConfig(p)
if err != nil {
t.Error(err)
}
err = initTests(tests, "../../sample/tick_scripts")
if err != nil {
t.Error(err)
}
if tests[0].Task.Name != "alert_2.tick" {
t.Error(tests[0].Task.Name)
}
}
| mit |